From 39de36d3af7d795c0ce52da4fa3718267b0453ec Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Mon, 19 Oct 2026 09:11:22 -0400 Subject: [PATCH] Snapshot for release 2026.10.19.1 (internal f0bdcf8) --- .../Combat/AttackPowerPlanner.cs | 119 +++ .../Combat/BuffManager.HpFailsafe.cs | 59 ++ .../Combat/BuffManager.cs | 147 ++- .../Combat/CombatManager.EnvironmentImpact.cs | 523 ++++++++++ .../Combat/CombatManager.Kite.cs | 244 +++++ .../Combat/CombatManager.cs | 343 ++++++- .../Combat/EnvironmentImpact.cs | 178 ++++ .../Combat/FellowshipTracker.cs | 3 + .../Combat/KiteModes.cs | 79 ++ .../Combat/MissileCraftingManager.cs | 96 +- .../Combat/PetManager.cs | 104 +- .../Combat/WeaponElementTracker.cs | 6 +- .../Combat/WieldRequirements.cs | 2 +- .../CombatHookInterface.cs | 1 + .../CorpseOpenController.cs | 82 +- .../RynthCore.Plugin.RynthAi/HubInterface.cs | 9 + .../Huds/CombatHudTracker.cs | 3 +- .../Huds/MiniRemoteHeader.cs | 27 + .../Huds/MiniRemoteHud.cs | 61 +- .../Huds/MovedTabs.cs | 7 + .../Huds/SectionsManifest.cs | 4 + .../LegacyUi/LegacyAdvancedSettingsUi.cs | 87 +- .../LegacyUi/LegacyDashboardRenderer.cs | 211 +++- .../LegacyUi/LegacyUiSettings.cs | 81 +- .../Loot/InventoryManager.cs | 41 +- .../Loot/LootEditorBridge.cs | 6 +- .../ManaStoneManager.cs | 13 +- .../Meta/ExpressionEngine.cs | 14 + .../MiniRemote/MiniRemoteState.cs | 7 + .../MiniRemote/PetCaptureRules.cs | 164 ++++ .../MiniRemote/PetsTab.cs | 249 +++++ .../NavigationEngine.cs | 7 +- .../VirindiTankProfileImporter.cs | 4 + .../RynthAiCommands.cs | 21 +- .../RynthAiPlugin.LocalFeatures.cs | 2 + .../RynthAiPlugin.Safety.cs | 13 + .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 456 +++++++-- .../RynthCore.Plugin.RynthAi.csproj | 2 + .../Trade/AutoTradeManager.cs | 2 +- .../Vendor/AutoVendorManager.cs | 2 +- .../RynthCore.Plugin.RynthChat/ChatBuffer.cs | 2 +- .../ChatClassifier.cs | 33 +- .../RynthCore.Plugin.RynthDreamWeave.csproj | 2 +- .../ServerData.cs | 53 +- .../Hub/IltBanking.cs | 79 +- .../Hub/IltChunkClap.cs | 454 +++++++-- .../Hub/IltFeatureCatalog.cs | 2 +- .../Hub/IltHubController.cs | 34 +- .../Hub/IltHubState.cs | 28 +- .../RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs | 1 + .../Hub/IltInventory.cs | 70 +- .../RynthCore.Plugin.RynthILT/Hub/IltLog.cs | 3 + .../RynthCore.Plugin.RynthILT/Hub/IltParse.cs | 18 +- .../Hub/IltProgression.cs | 68 +- .../Hub/IltSections.cs | 19 +- .../Hub/IltVaultedDungeons.cs | 919 ++++++++++++++++++ .../Hub/RynthAiClient.cs | 38 + .../RynthCore.Plugin.RynthILT.csproj | 4 + .../RynthILTPlugin.cs | 16 +- .../RynthInventoryPlugin.cs | 3 + Plugins/RynthCore.Plugin.RynthNav/Atlas.cs | 16 + .../RynthNavPlugin.Travel.cs | 25 + .../Data/QuestText.cs | 41 + .../Data/QuestTimerWatcher.cs | 44 + .../OracleContext.cs | 24 +- .../OracleSettings.cs | 8 + .../PluginExports.cs | 2 +- .../RynthOraclePlugin.cs | 95 +- .../Views/AboutTab.cs | 4 + .../Views/BoardsTab.cs | 8 - .../Views/ConquestTab.cs | 15 - .../Views/OracleView.cs | 62 +- .../Views/QuestTimersView.cs | 7 +- .../Views/QuestsTab.cs | 21 +- .../Views/RefreshBar.cs | 213 ++++ .../Views/SkillsEmbed.cs | 90 ++ .../PluginExports.cs | 15 + .../RynthSortPlugin.cs | 10 + Plugins/Shared/ActionPacer.cs | 45 +- Plugins/Shared/PetCaptureLines.cs | 29 + Plugins/Shared/RynthAiHubApi.cs | 15 + Plugins/Shared/RynthIltHubApi.cs | 2 + .../RynthCore.LootSdk/Editing/LootEditWire.cs | 50 + .../Editing/LootItemAttributes.cs | 539 ++++++++++ .../Editing/LootItemRules.cs | 150 +-- .../RynthCore.LootSdk/Editing/LootRuleText.cs | 87 +- Tools/RynthCore.LootEditor/LongValuePicker.cs | 12 +- .../LootAddAttributeTests.cs | 192 ++++ .../LootValueNameTests.cs | 7 + Tools/RynthCore.LootSdkTests/Program.cs | 1 + .../RynthCore.MonsterEditor/MainWindow.axaml | 12 + .../MainWindow.axaml.cs | 3 + Tools/RynthCore.MonsterEditor/Models.cs | 5 + .../Fakes/FakeHost.cs | 32 +- Tools/RynthCore.RynthAiHostTests/Program.cs | 6 + .../Tests/ActionPacingTests.cs | 44 +- .../Tests/AutoStackTests.cs | 38 + .../Tests/BuffTests.cs | 172 +++- .../Tests/CombatHookTests.cs | 41 + .../Tests/CorpseCloseTests.cs | 114 +++ .../Tests/EnvironmentImpactTests.cs | 514 ++++++++++ .../Tests/GiveTests.cs | 541 +++++++++++ .../Tests/HpFailsafeTests.cs | 129 ++- .../Tests/IdRefusalTests.cs | 80 ++ .../Tests/IgnoreMonsterTests.cs | 36 + .../Tests/MiniRemoteMoveTests.cs | 36 + .../Tests/MissileCraftingTests.cs | 182 ++++ .../Tests/MonsterEditorTests.cs | 1 + .../Tests/NavEngineTests.cs | 30 + .../Tests/NavOverlayTests.cs | 29 + .../Tests/PetRefillTests.cs | 59 +- .../Tests/ProfileLoadTests.cs | 161 +++ .../Tests/RingEvadeTests.cs | 97 ++ .../Tests/SectionsTests.cs | 20 + .../Tests/SkCombatAddonTests.cs | 492 ++++++++++ .../Tests/StuckCastTests.cs | 190 ++++ Tools/RynthCore.RynthAiTests/Program.cs | 2 + .../RynthCore.RynthAiTests.csproj | 3 + .../Tests/ChatClassifierTests.cs | 46 + .../Tests/PetCaptureRulesTests.cs | 108 ++ Tools/RynthILT.Tests/AetheriaChunkTests.cs | 235 +++++ Tools/RynthILT.Tests/AttributeRaiserTests.cs | 59 ++ Tools/RynthILT.Tests/BankCommandTests.cs | 26 + Tools/RynthILT.Tests/ChunkTargetTests.cs | 173 ++++ Tools/RynthILT.Tests/MoveTests.cs | 12 +- Tools/RynthILT.Tests/Program.cs | 2 + Tools/RynthILT.Tests/VaultedDungeonsTests.cs | 527 ++++++++++ Tools/RynthLua.CompatTests/Program.cs | 33 + Tools/RynthNav.RouteTests/Program.cs | 9 + Tools/RynthOracle.Tests/Program.cs | 345 +++++++ Tools/RynthSort.Tests/Program.cs | 12 + 131 files changed, 11278 insertions(+), 532 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/AttackPowerPlanner.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.EnvironmentImpact.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Kite.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/EnvironmentImpact.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/KiteModes.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHeader.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetCaptureRules.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Data/QuestText.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Data/QuestTimerWatcher.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Views/SkillsEmbed.cs create mode 100644 Plugins/Shared/PetCaptureLines.cs create mode 100644 Shared/RynthCore.LootSdk/Editing/LootItemAttributes.cs create mode 100644 Tools/RynthCore.LootSdkTests/LootAddAttributeTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/AutoStackTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/EnvironmentImpactTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/IdRefusalTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/MissileCraftingTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/RingEvadeTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/SkCombatAddonTests.cs create mode 100644 Tools/RynthCore.RynthAiTests/Tests/ChatClassifierTests.cs create mode 100644 Tools/RynthCore.RynthAiTests/Tests/PetCaptureRulesTests.cs create mode 100644 Tools/RynthILT.Tests/ChunkTargetTests.cs create mode 100644 Tools/RynthILT.Tests/VaultedDungeonsTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/AttackPowerPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/AttackPowerPlanner.cs new file mode 100644 index 0000000..9dd1338 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/AttackPowerPlanner.cs @@ -0,0 +1,119 @@ +using System; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +// ============================================================================ +// Per-monster attack power (2026-10-12): MonsterRule.AttackPower. +// +// Default the DEFAULT line's choice; on the DEFAULT line, the global +// Melee/Missile Power settings (Auto = 100%, or 80% with Use +// Recklessness and the skill trained) +// High 100% every swing or shot +// Reckless 80%: inside the band where Recklessness adds damage (ACE: +// 10%-90% of the bar, retail wiki: 20%-80%, so 80% is in both) +// Variable a new random power each attack, Variable Power Min..Max +// Reckless + Variable random each attack, inside the Recklessness band (20%-80%) +// and the Variable range +// +// Recklessness only adds damage when the skill is trained or specialized; with it +// untrained a reckless choice falls back to High (or Variable), since a short bar +// would only cost damage. Magic doesn't use attack power. +// ============================================================================ + +/// Names and resolution of . +public static class AttackPowerModes +{ + public const string Default = "Default"; + public const string High = "High"; + public const string Reckless = "Reckless"; + public const string Variable = "Variable"; + public const string RecklessVariable = "Reckless + Variable"; + + /// Every choice, in the order the editors list them. + public static readonly string[] All = { Default, High, Reckless, Variable, RecklessVariable }; + + /// The bar fraction a fixed reckless attack uses. + public const float RecklessPower = 0.8f; + /// The Recklessness band used for a varied reckless attack (retail wiki: 20%-80%). + public const int RecklessBandMinPct = 20; + public const int RecklessBandMaxPct = 80; + + /// A saved value as one of ; blank or unknown is Default. + public static string Normalize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return Default; + string v = value.Trim(); + foreach (string m in All) + if (m.Equals(v, StringComparison.OrdinalIgnoreCase)) return m; + // Hand-typed and meta spellings: "RecklessVariable", "reckless+variable". + string squeezed = v.Replace(" ", "").Replace("+", ""); + if (squeezed.Equals("RecklessVariable", StringComparison.OrdinalIgnoreCase)) return RecklessVariable; + return Default; + } + + /// + /// The mode that applies to a monster: its own rule's, else the DEFAULT line's, else + /// Default (the global settings). may be the same object. + /// + public static string Effective(MonsterRule? rule, MonsterRule? defaultRule) + { + string own = Normalize(rule?.AttackPower); + if (own != Default) return own; + return Normalize(defaultRule?.AttackPower); + } + + /// + /// The power bar fraction (0..1) for one attack. + /// is the global Melee/Missile Power (-1 = Auto); + /// returns a value in [0, 1). + /// + public static float Resolve(string mode, int globalPct, bool useRecklessness, bool recklessTrained, + int variableMinPct, int variableMaxPct, Func random01) + { + switch (Normalize(mode)) + { + case High: + return 1.0f; + + case Reckless: + return recklessTrained ? RecklessPower : 1.0f; + + case Variable: + { + var (lo, hi) = VariableRange(variableMinPct, variableMaxPct); + return Pick(lo, hi, random01); + } + + case RecklessVariable: + { + var (lo, hi) = VariableRange(variableMinPct, variableMaxPct); + if (!recklessTrained) return Pick(lo, hi, random01); + int rlo = Math.Max(lo, RecklessBandMinPct); + int rhi = Math.Min(hi, RecklessBandMaxPct); + // The Variable range doesn't overlap the band (e.g. 85-100): the whole band. + if (rlo > rhi) { rlo = RecklessBandMinPct; rhi = RecklessBandMaxPct; } + return Pick(rlo, rhi, random01); + } + + default: + if (globalPct < 0) + return useRecklessness && recklessTrained ? RecklessPower : 1.0f; + return Math.Clamp(globalPct, 0, 100) / 100f; + } + } + + /// The Variable range in percent, clamped to 0..100 and put in order. + public static (int Lo, int Hi) VariableRange(int minPct, int maxPct) + { + int lo = Math.Clamp(minPct, 0, 100), hi = Math.Clamp(maxPct, 0, 100); + return lo <= hi ? (lo, hi) : (hi, lo); + } + + private static float Pick(int loPct, int hiPct, Func random01) + { + double r = Math.Clamp(random01(), 0.0, 1.0); + double pct = loPct + (hiPct - loPct) * r; + return (float)(Math.Round(pct) / 100.0); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs index d8864e9..b27ee76 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs @@ -24,6 +24,9 @@ // yield (MayRestartMacro), and a death drops the pending recall (the player's // Stop Macro On Death stands). // Health back over the line (or 100%) ends the episode. Nothing counts in portal space. +// The failsafe (jump included) is for a character that can heal: it arms only with a heal that went +// out in the last minute, or a heal spell / kit / health potion at hand (HealCapableNow). A melee +// character with nothing to heal with is not jumped or recalled. HpFailsafeRecall defaults to off. // ============================================================================ using System; @@ -92,6 +95,9 @@ public partial class BuffManager ResetHpFailsafe(); return; } + // Only a character that can heal at all: a melee character with no spell, kit or potion + // (resting, or out-healed) has nothing for the failsafe to retry, and a recall there is wrong. + if (!HealCapableNow(now)) { ResetHpFailsafe(); return; } if (!_fsActive) { _fsActive = true; @@ -146,6 +152,59 @@ public partial class BuffManager StartFailsafeRecall(now, hp, failedSec); } + // A heal (spell, kit or potion) that actually went out: the failsafe's proof the character can heal. + private DateTime _lastHealSentAt = DateTime.MinValue; + private DateTime _healCapableCheckAt = DateTime.MinValue; + private bool _healCapableCached; + /// A heal sent this recently proves the character can heal (kit used up since, a script's drain). + internal const double HealSentProofMs = 60_000; + + /// Every heal that goes out (cast, kit, potion) records itself here, then feeds the latency tracker. + private void NoteHealSent(string action) + { + _lastHealSentAt = Now; + _healLatency.HealSent(Now, action); + } + + /// + /// Can this character heal at all? A heal went out in the last HealSentProofMs, or one could now: a known + /// Heal Self / Stamina to Health Self with Life Magic trained, a healing kit, or a health potion + /// (Use Potions on and one listed or in the pack). Read at most once a second (it walks the pack). + /// + private bool HealCapableNow(DateTime now) + { + if (_lastHealSentAt != DateTime.MinValue && (now - _lastHealSentAt).TotalMilliseconds < HealSentProofMs) return true; + if ((now - _healCapableCheckAt).TotalMilliseconds < 1000 && _healCapableCheckAt != DateTime.MinValue) return _healCapableCached; + _healCapableCheckAt = now; + bool capable = false; + try + { + if (IsSkillUsable(AcSkillType.LifeMagic)) + { + foreach (string spell in new[] { "Heal Self", "Stamina to Health Self" }) + { + if (_spellManager.GetDynamicSelfBuffId(spell, AcSkillType.LifeMagic) != 0 + || _spellManager.GetSelfSpellIdAboveAllowedTier(spell, AcSkillType.LifeMagic) != 0) { capable = true; break; } + } + } + if (!capable && _worldObjectCache != null) + { + if (BestPackHealingKit() != null) capable = true; + else + { + foreach (var r in _settings.ConsumableRules) + if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase) + && !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase) + && ConsumableLookup.Resolve(_worldObjectCache, r) != null) { capable = true; break; } + } + if (!capable && _settings.UsePotions && HasListedPotion("HealthPotion")) capable = true; + } + } + catch { capable = false; } + _healCapableCached = capable; + return capable; + } + private void ResetHpFailsafe() { _fsActive = false; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 66a588e..c86f1c4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -156,6 +156,20 @@ public partial class BuffManager : IDisposable // like any cast. private int _pendingUpgradeSpellId; + // Consecutive SILENT no-shows of an upgrade, per family (the registry never moved / no chat for an + // item spell). An upgrade's no-show is no strike on the family (see the no-show branches), so + // without a bound a cast the server silently drops loops forever: an item enchant whose lower + // record is still on the books after the armor was lost or the weapon swapped (nothing to bind + // to), or a self-buff the server ignores. In a force/batch run that holds _isForceRebuffing, and + // with it buffing's priority over fighting, for good. After UpgradeNoShowThreshold of them the + // UPGRADE alone is parked for UpgradeParkCooldown: the family is not blacklisted or put in + // _buffFailCooldownUntil, and the level it was cast over keeps refreshing as a normal cast. + // Cleared by any confirmed cast of the family (NoteBuffConfirmed) and by Force Rebuff. + private readonly Dictionary _upgradeNoShowCounts = new(); + private readonly Dictionary _upgradeParkedUntil = new(); + private const int UpgradeNoShowThreshold = 3; + private static readonly TimeSpan UpgradeParkCooldown = TimeSpan.FromMinutes(5); + // Per-family diagnostic throttle — last reason string we logged. Suppresses // dup spam when IsBuffActive is polled every tick by NeedsAnyBuff + CheckAndCastSelfBuffs. private readonly Dictionary _lastArmorRecastReason = new(); @@ -974,6 +988,20 @@ public partial class BuffManager : IDisposable public void RequestForceFullRebuff() => System.Threading.Interlocked.Exchange(ref _forceRebuffRequested, 1); public void RequestCancelBuffing() => System.Threading.Interlocked.Exchange(ref _cancelBuffingRequested, 1); + // /ra buff skipped runs on AC's chat-command thread; building the list there would write the pump's + // kit and skip fields from a second thread. The command only sets this; the pump builds and reports. + private int _skipReportRequested; + public void RequestSkipReport() => System.Threading.Interlocked.Exchange(ref _skipReportRequested, 1); + + private void ReportFilterSkips() + { + BuildDynamicBuffList(); // refreshes the skip list, even with buffing off + string summary = _filterSummary; + _host.WriteToChat(summary.Length == 0 + ? "[RynthAi] Buff filter: nothing is being skipped." + : $"[RynthAi] Buff filter skips: {summary}", 1); + } + public void ForceFullRebuff() { _isForceRebuffing = true; @@ -984,8 +1012,11 @@ public partial class BuffManager : IDisposable _unsatisfiedStrikes.Clear(); // ditto for the post-batch satisfaction audit _castIssuedAtByFamily.Clear(); _expiryAtCastByFamily.Clear(); + _upgradeNoShowCounts.Clear(); // and a fresh try at parked upgrades + _upgradeParkedUntil.Clear(); _ramBuffTimers.Clear(); _itemSpellTimers.Clear(); + EndPendingUpgrade(_pendingSpellId, "a new Force Rebuff"); _pendingSpellId = 0; _lastCastAttempt = DateTime.MinValue; SaveBuffTimers(); @@ -1005,6 +1036,7 @@ public partial class BuffManager : IDisposable _isRechargingMana = false; _isRechargingStamina = false; _isHealingSelf = false; + EndPendingUpgrade(_pendingSpellId, "buffing cancelled"); _pendingSpellId = 0; _chain.PassEnd("cancelled", s => _host.Log(s)); _host.WriteToChat("[RynthAi] Sequence cancelled.", 5); @@ -1237,6 +1269,8 @@ public partial class BuffManager : IDisposable ForceFullRebuff(); if (System.Threading.Interlocked.Exchange(ref _cancelBuffingRequested, 0) != 0) CancelBuffing(); + if (System.Threading.Interlocked.Exchange(ref _skipReportRequested, 0) != 0) + ReportFilterSkips(); // Post-cast diffs for the bufftest experiment run unconditionally — even if the // user toggled the macro off mid-experiment, we still want to capture and log them. @@ -1347,6 +1381,7 @@ public partial class BuffManager : IDisposable && CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)) && !BusyHoldsHeal()) { _host.Log($"[BuffDiag] health {_vitals.HealthPct}% under a heal line: released pending buff id={_pendingSpellId} to heal first."); + EndPendingUpgrade(_pendingSpellId, "released to heal"); _pendingSpellId = 0; _onCastResolved?.Invoke("released to heal"); } @@ -1444,6 +1479,7 @@ public partial class BuffManager : IDisposable if (isUpgrade) { _host.Log($"[BuffDiag] upgrade '{pendingSpell.Name}' (id={_pendingSpellId}, fam={fam}) not in the live registry after {sinceCastMs:0}ms (the lower level is unchanged): no strike, tried again."); + NoteUpgradeNoShow(_pendingSpellId); // bounded: parks the upgrade (only) after UpgradeNoShowThreshold in a row } else { @@ -1493,6 +1529,8 @@ public partial class BuffManager : IDisposable bool confirmedKnown = _spellManager.IsKnownSnapshotWarm && _spellManager.IsKnownSpellId(stuckId); if (!confirmedKnown && !isUpgrade) _spellManager.MarkSpellUnresolvable(stuckId); + if (isUpgrade) + NoteUpgradeNoShow(stuckId); // bounded: parks the upgrade (only) after UpgradeNoShowThreshold in a row // 2026-05-25 — per-family silent-no-show bookkeeping on the // ARMOR path, mirroring the self-buff path above. @@ -2241,7 +2279,7 @@ public partial class BuffManager : IDisposable if (_pendingVitalLabel == LabelHealing) { _healSpellIds.Add(spellId); - _healLatency.HealSent(Now, what); + NoteHealSent(what); } return true; } @@ -2292,7 +2330,7 @@ public partial class BuffManager : IDisposable _host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list"); _lastPotionAt = DateTime.Now; _lastCastAttempt = DateTime.Now; - if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name); + if (IsHealthPotionType(types)) NoteHealSent(rule.Name); return true; } if (listedOnly) return VitalNo("none listed in Consumables"); @@ -2308,7 +2346,7 @@ public partial class BuffManager : IDisposable _host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack"); _lastPotionAt = DateTime.Now; _lastCastAttempt = DateTime.Now; - if (IsHealthPotionType(types)) _healLatency.HealSent(Now, wo.Name ?? "health potion"); + if (IsHealthPotionType(types)) NoteHealSent(wo.Name ?? "health potion"); return true; } return VitalNo("none in the Items list or the pack"); @@ -2461,7 +2499,7 @@ public partial class BuffManager : IDisposable _host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself"); _lastCastAttempt = DateTime.Now; MarkKitUsed(); - _healLatency.HealSent(Now, kit.Name ?? "healing kit"); + NoteHealSent(kit.Name ?? "healing kit"); return true; } @@ -3119,7 +3157,8 @@ public partial class BuffManager : IDisposable // run cast (the priority buffs landed and raised the skill, or a higher spell was // learned). Never lower: a skill that dropped leaves the run's cast alone. if (_forceRebuffCastFamilies.Contains(targetSpell.Family)) - return !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran); + return UpgradeParked(targetSpell.Family) + || !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran); if (!_isAutoBatchRebuff) return false; rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining); } @@ -3142,7 +3181,7 @@ public partial class BuffManager : IDisposable { if (_itemSpellTimers.TryGetValue(targetSpell.Family, out ItemSpellRecord? itemTimer)) { - if (itemTimer.SpellLevel < targetLevel) + if (itemTimer.SpellLevel < targetLevel && !UpgradeParked(targetSpell.Family)) { LogArmorRecast(targetSpell, $"tier-upgrade recordedLvl={itemTimer.SpellLevel} < targetLvl={targetLevel} (recorded='{itemTimer.SpellName}')"); return false; @@ -3184,7 +3223,7 @@ public partial class BuffManager : IDisposable // login) keeps the cap, so a relog doesn't recast every capped Incantation. int effectiveTarget = EffectiveTargetLevel(targetSpell); - if (timer.SpellLevel < effectiveTarget) + if (timer.SpellLevel < effectiveTarget && !UpgradeParked(targetSpell.Family)) { LogPlayerRecast(targetSpell, $"tier-upgrade storedLvl={timer.SpellLevel} < effTarget={effectiveTarget} (nominal={targetLevel}, achievedCap={(_familyAchievedTier.TryGetValue(targetSpell.Family, out int a2) ? a2 : -1)}, stored='{timer.SpellName}')"); return false; @@ -3240,6 +3279,8 @@ public partial class BuffManager : IDisposable int level = GetSpellLevel(spell); if (!_familyAttemptedTier.TryGetValue(spell.Family, out int prev) || level > prev) _familyAttemptedTier[spell.Family] = level; + // A cast of the family landed: the server takes it, so no upgrade no-show streak or park stands. + ClearUpgradeNoShows(spell.Family); // The pending upgrade (or better) landed. if (_pendingUpgradeSpellId != 0 && SpellTableStub.GetById(_pendingUpgradeSpellId) is { } up && up.Family == spell.Family && level >= GetSpellLevel(up)) @@ -3253,8 +3294,9 @@ public partial class BuffManager : IDisposable /// /// The pending upgrade cast did not take (fizzle, refusal, no mana, /// no-show): it is no longer pending, and it is cast again at the next opportunity. No try cap, - /// and no rest after a fizzle, a client refusal or a no-show; a server mana or component refusal - /// still rests the family as it does for any buff. + /// and no rest after a fizzle or a client refusal; a server mana or component refusal still rests + /// the family as it does for any buff. A SILENT no-show is the exception to "no cap": after + /// UpgradeNoShowThreshold in a row the upgrade (only) is parked (NoteUpgradeNoShow). /// private void EndPendingUpgrade(int spellId, string why) { @@ -3262,6 +3304,41 @@ public partial class BuffManager : IDisposable _pendingUpgradeSpellId = 0; _host.Log($"[Buff] upgrade to {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} did not take ({why}); cast again at the next opportunity."); } + + /// True while upgrades of are parked after repeated silent no-shows. + private bool UpgradeParked(int family) + => family != 0 && _upgradeParkedUntil.TryGetValue(family, out DateTime until) && DateTime.Now < until; + + /// + /// The pending upgrade was a silent no-show (nothing showed in the + /// registry / no chat). Counts it; at UpgradeNoShowThreshold in a row the family's upgrades are + /// parked for UpgradeParkCooldown (and the count starts over for the next window). Nothing else + /// is touched: no strike, no family park, no blacklist. + /// + private void NoteUpgradeNoShow(int spellId) + { + int family = SpellTableStub.GetById(spellId)?.Family ?? 0; + if (family == 0) return; + int count = _upgradeNoShowCounts.TryGetValue(family, out int prev) ? prev + 1 : 1; + if (count >= UpgradeNoShowThreshold) + { + _upgradeNoShowCounts.Remove(family); + _upgradeParkedUntil[family] = DateTime.Now + UpgradeParkCooldown; + _host.Log($"[Buff] upgrade of family {family} ({SpellTableStub.GetById(spellId)?.Name}) never showed {count} times in a row: upgrades of it parked {UpgradeParkCooldown.TotalMinutes:0}min " + + "(the level it was cast over still refreshes as a normal cast; the family is not blacklisted)."); + } + else + { + _upgradeNoShowCounts[family] = count; + _host.Log($"[Buff] upgrade of family {family} did not show ({count}/{UpgradeNoShowThreshold} before it is parked)."); + } + } + + private void ClearUpgradeNoShows(int family) + { + _upgradeNoShowCounts.Remove(family); + _upgradeParkedUntil.Remove(family); + } /// /// The level IsBuffActive holds a player buff to: the target spell's level, capped at the /// highest level that family has landed at, once the target level has been confirmed and @@ -3283,6 +3360,9 @@ public partial class BuffManager : IDisposable /// private int ActiveLevelBelow(int family, int newLevel) { + // Upgrades parked after repeated silent no-shows: a cast of the family now is the normal + // refresh of what is on (no upgrade line, and its no-show is judged like any other buff's). + if (UpgradeParked(family)) return 0; int on = 0; if (_isForceRebuffing && _forceRebuffCastFamilies.Contains(family)) on = CastLevelThisRun(family); else if (_ramBuffTimers.TryGetValue(family, out RamTimerInfo? t) @@ -3902,6 +3982,14 @@ public partial class BuffManager : IDisposable private DateTime _filterSkipLoggedAt = DateTime.MinValue; private string _filterSkipLoggedSummary = ""; private const double FilterSkipLogMinSec = 30; + // "skill untrained" is true of nearly every character (an unspecialised melee skill has no mastery to cast), + // so it would make the chat line print at every buff run. It stays in the summary (/ra buff skipped, the + // Buffing page) and the log, and is left out of the chat line. + internal const string SkillUntrainedReason = "skill untrained"; + private string _filterChatSummary = ""; + private int _filterChatCount; + private DateTime _filterChatLoggedAt = DateTime.MinValue; + private string _filterChatLoggedSummary = ""; private const int SummaryNamesPerReason = 5; private void SetFilterSkips(List<(string Buff, string Reason)> skips) @@ -3912,6 +4000,9 @@ public partial class BuffManager : IDisposable if (same) return; _filterSkips = skips.Count == 0 ? Array.Empty<(string, string)>() : skips; _filterSummary = BuildSummary(skips); + var notable = skips.FindAll(s => s.Reason != SkillUntrainedReason); + _filterChatCount = notable.Count; + _filterChatSummary = notable.Count == skips.Count ? _filterSummary : BuildSummary(notable); } /// "skill untrained: A, B, C, D, E (+12 more); no melee or missile weapon listed: Blood Drinker, Heart Seeker". @@ -3946,19 +4037,27 @@ public partial class BuffManager : IDisposable /// The skipped buffs grouped by reason, or "". public string FilterSkipSummary() => _filterSummary; - // One line per buff run (Force Rebuff, or the automatic batch starting). Same content as the - // last line is held back for FilterSkipLogMinSec; different content prints at once. Reads the - // skips of the BuildDynamicBuffList pass the caller just made. + // One log line and (when something besides untrained skills is skipped) one chat line per buff run + // (Force Rebuff, or the automatic batch starting). Same content as the last line is held back for + // FilterSkipLogMinSec; different content prints at once. Reads the skips of the BuildDynamicBuffList + // pass the caller just made. private void LogFilterSkips() { + var now = DateTime.Now; string summary = _filterSummary; if (summary.Length == 0) return; - var now = DateTime.Now; - if (summary == _filterSkipLoggedSummary && (now - _filterSkipLoggedAt).TotalSeconds < FilterSkipLogMinSec) return; - _filterSkipLoggedAt = now; - _filterSkipLoggedSummary = summary; - _host.WriteToChat($"[RynthAi] Buff run skips {_filterSkips.Count} buff(s) this character can't use - {summary}", 1); - _host.Log($"[Buff] filter skips: {summary}"); + if (summary != _filterSkipLoggedSummary || (now - _filterSkipLoggedAt).TotalSeconds >= FilterSkipLogMinSec) + { + _filterSkipLoggedAt = now; + _filterSkipLoggedSummary = summary; + _host.Log($"[Buff] filter skips: {summary}"); + } + string chat = _filterChatSummary; + if (chat.Length == 0) return; + if (chat == _filterChatLoggedSummary && (now - _filterChatLoggedAt).TotalSeconds < FilterSkipLogMinSec) return; + _filterChatLoggedAt = now; + _filterChatLoggedSummary = chat; + _host.WriteToChat($"[RynthAi] Buff run skips {_filterChatCount} buff(s) this character can't use - {chat}", 1); } internal List BuildDynamicBuffList() { @@ -4009,7 +4108,7 @@ public partial class BuffManager : IDisposable if (!IsSkillUsable(kvp.Key)) { // Always left out (no skill, no mastery to cast); the setting only decides whether it is reported. - if (filter && !BaseCreatureBuffs.Contains(kvp.Value)) skips.Add((kvp.Value, "skill untrained")); + if (filter && !BaseCreatureBuffs.Contains(kvp.Value)) skips.Add((kvp.Value, SkillUntrainedReason)); continue; } if (kvp.Value.Contains("Creature Enchantment Mastery")) @@ -5387,9 +5486,13 @@ public partial class BuffManager : IDisposable { if ((DateTime.Now - asked.At).TotalSeconds >= WandIdRetrySec) { - _host.RequestId(uid); - _wandIdAsked[wo.Id] = (asked.Count + 1, DateTime.Now); - _host.Log($"[WieldGate] identifying 0x{uid:X8} '{wo.Name}' before using it to buff (its wield requirement isn't known yet)"); + // Counted only when the engine took it: a refused ask (a death or a portal) is not one of the + // WandIdMaxAsks, and the wand is held back and asked about again. + if (_host.RequestId(uid)) + { + _wandIdAsked[wo.Id] = (asked.Count + 1, DateTime.Now); + _host.Log($"[WieldGate] identifying 0x{uid:X8} '{wo.Name}' before using it to buff (its wield requirement isn't known yet)"); + } } return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.EnvironmentImpact.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.EnvironmentImpact.cs new file mode 100644 index 0000000..10dac6c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.EnvironmentImpact.cs @@ -0,0 +1,523 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Environment-impact throttle (2026-10-12). Rules and bookkeeping in EnvironmentImpact.cs. +/// +/// missile "Your missile attack hit the environment." in Missile mode counts one hit on the +/// target the server's attack is bound to. +/// magic each single-target war/void cast is watched: our projectiles (named like the +/// shape, "Flame Bolt") are claimed as they appear next to the player, followed until +/// they stop or vanish, and the cast counts one hit when every projectile stopped +/// short of the target (ProjectileImpactJudge) and no hit, resist or evade line came +/// back for it. Rings and walls aren't watched: they don't fly at the target. +/// +/// At EnvironmentImpactLimit hits within the window the throttle trips: the server's attack is +/// released (a magic cast in flight finishes first) and the chosen response runs: an approach +/// (autorun toward the target, at most EnvironmentApproachMeters, never nearer than +/// EnvironmentMinDistance, bounded in time and by progress), or a new target (this one skipped +/// for EnvironmentSkipSec). Off = no detection at all. +/// +public partial class CombatManager +{ + /// Clock for the throttle and the projectile watch; tests replace it. + internal Func EnvClock { get; set; } = () => DateTime.Now; + + internal EnvironmentImpactThrottle EnvThrottle { get; } = new(); + + /// The start of the chat line ACE sends the shooter (ProjectileCollisionHelper.OnCollideEnvironment, + /// a Broadcast line). Matched at the line's start only: a player's copy has their name in front. + internal const string MissileEnvironmentText = "Your missile attack hit the environment"; + + // A cast's projectiles appear once its windup ends (up to ~2.5 s for a high tier). + private const double CastClaimWindowMs = 4000; + // Our projectile spawns at the caster; farther than this at its first sight it isn't ours. + private const double ClaimRadiusMeters = 8.0; + // Still this long after flying counts as stopped (ACE zeroes its velocity on impact). + private const double StoppedForMs = 250; + private const double StillMeters = 0.05; + // A projectile still flying after this is dropped from the watch (no verdict). + private const double ProjectileMaxFlightMs = 8000; + // After the last projectile stops, a hit/resist/evade line still has this long to arrive. + private const double ImpactEvidenceGraceMs = 1000; + private const int MaxCastWatches = 4; + // An approach that hasn't gained this much ground in ApproachNoProgressMs is blocked. + private const double ApproachProgressMeters = 0.5; + private const double ApproachNoProgressMs = 2500; + private const double ApproachMaxMs = 8000; + private const double ApproachRunRefreshMs = 1000; + private const double ApproachTurnRefreshMs = 300; + private const double ApproachFaceToleranceDeg = 10; + // Think stopped driving the approach (buffing took over, out of range): let go of autorun. + private const double ApproachOrphanMs = 1500; + + private enum EnvKind { Missile, Magic } + + private sealed class TrackedProjectile + { + public uint Id; + public double StartX, StartY, StartZ; + public double LastX, LastY, LastZ; + public DateTime FirstSeen, LastMoved; + public double Travel; + public bool Resolved, Short; + } + + private sealed class CastWatch + { + public int TargetId; + public string SpellName = ""; + public DateTime CastAt; + public double CasterX, CasterY, CasterZ; + public bool HasCasterPos; + public readonly List Projectiles = new(); + public DateTime LastImpactAt = DateTime.MinValue; + } + + // Creates are queued and claimed by the heartbeat poll (the name lands a moment later). + private readonly ConcurrentQueue<(uint Id, DateTime At)> _envCreated = new(); + private readonly List<(uint Id, DateTime At)> _envCandidates = new(); + private readonly List _castWatches = new(); + private readonly Dictionary _envSkipUntil = new(); + private DateTime _envLastEvidenceAt = DateTime.MinValue; + + // The trip waiting for Think, and the approach in progress. + private int _envPendingTargetId; + private EnvKind _envPendingKind; + private int _envApproachTargetId; + private EnvKind _envApproachKind; + private double _envApproachGoal, _envApproachBestDist; + private DateTime _envApproachStartedAt, _envApproachProgressAt, _envApproachRunAt, _envApproachTurnAt, _envApproachTickAt; + private bool _envApproachUsedMotions; + + /// True while combat is walking toward a target for its environment hits. + internal bool EnvironmentApproachActive => _envApproachTargetId != 0; + + private EnvironmentResponse ResponseFor(EnvKind kind) => EnvironmentImpactPlanner.Parse( + kind == EnvKind.Missile ? _settings.MissileEnvironmentResponse : _settings.MagicEnvironmentResponse); + + // ── Signals ──────────────────────────────────────────────────────────────── + + /// A new object. Only queued while the macro runs with magic detection on + /// (the heartbeat poll that drains the queue runs only then). Separate from OnObjectCreated, + /// which feeds the ghost tracker on every create. + public void OnEnvironmentObjectCreated(uint objectId) + { + if (objectId == 0 || _settings.MagicEnvironmentResponse == 0 || !_settings.IsMacroRunning) return; + _envCreated.Enqueue((objectId, EnvClock())); + } + + /// From OnObjectDeleted: a projectile that vanished has hit something, and a + /// monster id that's gone forgets its hits, approaches and skip. + private void OnEnvironmentObjectDeleted(uint objectId) + { + int id = (int)objectId; + EnvThrottle.Forget(id); + _envSkipUntil.Remove(id); + if (_castWatches.Count == 0) return; + DateTime now = EnvClock(); + foreach (var w in _castWatches) + foreach (var p in w.Projectiles) + if (p.Id == objectId && !p.Resolved) ResolveProjectile(w, p, now); + } + + /// The missile line, from HandleChatForDamage. True when it was that line. + private bool NoteMissileEnvironmentChat(string text) + { + if (!ChatSource.StartsWithMarker(text, MissileEnvironmentText, StringComparison.OrdinalIgnoreCase)) return false; + if (ResponseFor(EnvKind.Missile) == EnvironmentResponse.Off) return true; + if (CurrentCombatMode != CombatMode.Missile) return true; + int target = _serverAttackTargetId != 0 ? _serverAttackTargetId : activeTargetId; + if (target != 0) RecordEnvironmentImpact(target, EnvKind.Missile, "missile hit the environment"); + return true; + } + + /// Any sign an attack reached a monster (hit, resist, evade, a health drop): + /// a cast with one of these after it didn't only hit the environment. + private void NoteEnvironmentEvidence() => _envLastEvidenceAt = EnvClock(); + + /// A single-target cast just went out (AttackWithMagic): watch its projectiles. + internal void RegisterCastWatch(int targetId, string spellName) + { + if (ResponseFor(EnvKind.Magic) == EnvironmentResponse.Off || targetId == 0) return; + DateTime now = EnvClock(); + var w = new CastWatch { TargetId = targetId, SpellName = spellName, CastAt = now }; + if (TryGetPlayerGlobal(out double px, out double py, out double pz)) + { + w.CasterX = px; w.CasterY = py; w.CasterZ = pz; w.HasCasterPos = true; + } + if (_castWatches.Count >= MaxCastWatches) _castWatches.RemoveAt(0); + _castWatches.Add(w); + } + + /// Counts one environment hit; at the limit, arms the response for Think. + private void RecordEnvironmentImpact(int targetId, EnvKind kind, string detail) + { + DateTime now = EnvClock(); + int limit = Math.Max(1, _settings.EnvironmentImpactLimit); + int window = Math.Max(1, _settings.EnvironmentImpactWindowSec); + int n = EnvThrottle.Record(targetId, now, window); + string name = _worldFilter[targetId]?.Name ?? ""; + _host.Log($"[EnvImpact] {kind.ToString().ToLowerInvariant()}: {detail} — 0x{(uint)targetId:X8} '{name}' {n}/{limit} in {window}s"); + if (n < limit || targetId != activeTargetId) return; + if (_envApproachTargetId == targetId) return; // already moving closer to it + _envPendingTargetId = targetId; + _envPendingKind = kind; + } + + // ── Heartbeat: projectile watch and the approach's safety net ───────────── + + /// Every heartbeat while the macro runs (pump thread). + internal void PollEnvironmentImpact() + { + DateTime now = EnvClock(); + + if (_settings.MagicEnvironmentResponse == 0) + { + while (_envCreated.TryDequeue(out _)) { } + _envCandidates.Clear(); + _castWatches.Clear(); + } + else + { + while (_envCreated.TryDequeue(out var c)) _envCandidates.Add(c); + ClaimProjectiles(now); + TrackProjectiles(now); + JudgeCastWatches(now); + } + + // Think drives the approach; when it stops (another activity, out of range, combat off) + // or the deadline passes, autorun must not be left on. + if (_envApproachTargetId != 0 + && ((now - _envApproachTickAt).TotalMilliseconds > ApproachOrphanMs + || (now - _envApproachStartedAt).TotalMilliseconds > ApproachMaxMs + ApproachOrphanMs + || !_settings.EnableCombat)) + EndEnvironmentApproach("combat stopped driving it"); + + // Same for the re-sync sidestep's movement key: Think releases it after ResyncStepMs, + // but only while it keeps ticking in magic mode. + if (_resyncState == 2 && (TargetClock() - _resyncAt).TotalMilliseconds > ResyncStepMs + ApproachOrphanMs) + AbandonResync("combat stopped driving it"); + } + + private void ClaimProjectiles(DateTime now) + { + if (_envCandidates.Count == 0) return; + bool havePlayer = TryGetPlayerGlobal(out double px, out double py, out double pz); + for (int i = _envCandidates.Count - 1; i >= 0; i--) + { + var (id, at) = _envCandidates[i]; + string name = _worldFilter[(int)id]?.Name ?? ""; + if (name.Length == 0 && _host.TryGetObjectName(id, out string n2)) name = n2; + if (name.Length == 0) + { + // The name lands a moment after the create; give it a second. + if ((now - at).TotalMilliseconds > 1000) _envCandidates.RemoveAt(i); + continue; + } + _envCandidates.RemoveAt(i); + if (!IsWatchedProjectileName(name)) continue; + if (!havePlayer || !TryGetObjectGlobal(id, out double x, out double y, out double z)) continue; + if (Dist(px, py, pz, x, y, z) > ClaimRadiusMeters) continue; + + // The newest cast still taking projectiles (a blast's several share one cast). + CastWatch? owner = null; + for (int w = _castWatches.Count - 1; w >= 0; w--) + { + double age = (at - _castWatches[w].CastAt).TotalMilliseconds; + if (age >= -50 && age <= CastClaimWindowMs) { owner = _castWatches[w]; break; } + } + if (owner == null) continue; + owner.Projectiles.Add(new TrackedProjectile + { + Id = id, StartX = x, StartY = y, StartZ = z, LastX = x, LastY = y, LastZ = z, + FirstSeen = now, LastMoved = now, + }); + } + } + + /// A war/void projectile: the shape names (SpellShapes/VoidSpellShapes), or any + /// name ending in a flying shape (lore-named projectiles of the same shapes). + internal static bool IsWatchedProjectileName(string name) + { + if (IsSpellProjectileName(name)) return !name.EndsWith(" Ring", StringComparison.OrdinalIgnoreCase); + return name.EndsWith(" Bolt", StringComparison.OrdinalIgnoreCase) + || name.EndsWith(" Streak", StringComparison.OrdinalIgnoreCase) + || name.EndsWith(" Arc", StringComparison.OrdinalIgnoreCase) + || name.EndsWith(" Blast", StringComparison.OrdinalIgnoreCase); + } + + private void TrackProjectiles(DateTime now) + { + foreach (var w in _castWatches) + { + foreach (var p in w.Projectiles) + { + if (p.Resolved) continue; + if ((now - p.FirstSeen).TotalMilliseconds > ProjectileMaxFlightMs) + { + p.Resolved = true; // no verdict: treated as not short + continue; + } + if (!TryGetObjectGlobal(p.Id, out double x, out double y, out double z)) continue; + if (Dist(x, y, z, p.LastX, p.LastY, p.LastZ) > StillMeters) + { + p.LastX = x; p.LastY = y; p.LastZ = z; + p.LastMoved = now; + p.Travel = Math.Max(p.Travel, Dist(x, y, z, p.StartX, p.StartY, p.StartZ)); + continue; + } + if (p.Travel >= ProjectileImpactJudge.MinTravelMeters + && (now - p.LastMoved).TotalMilliseconds >= StoppedForMs) + ResolveProjectile(w, p, now); + } + } + } + + private void ResolveProjectile(CastWatch w, TrackedProjectile p, DateTime now) + { + p.Resolved = true; + w.LastImpactAt = now; + if (p.Travel < ProjectileImpactJudge.MinTravelMeters) return; + if (!TryGetObjectGlobal((uint)w.TargetId, out double tx, out double ty, out double tz)) return; + double cx = w.CasterX, cy = w.CasterY, cz = w.CasterZ; + if (!w.HasCasterPos) { cx = p.StartX; cy = p.StartY; cz = p.StartZ; } + p.Short = ProjectileImpactJudge.StoppedShort( + Dist(p.LastX, p.LastY, p.LastZ, tx, ty, tz), + Dist(cx, cy, cz, p.LastX, p.LastY, p.LastZ), + Dist(cx, cy, cz, tx, ty, tz)); + } + + private void JudgeCastWatches(DateTime now) + { + for (int i = _castWatches.Count - 1; i >= 0; i--) + { + var w = _castWatches[i]; + double age = (now - w.CastAt).TotalMilliseconds; + if (w.Projectiles.Count == 0) + { + if (age > CastClaimWindowMs + 500) _castWatches.RemoveAt(i); // refused or never seen + continue; + } + // A blast's projectiles all appear together; wait out the claim window only briefly. + bool allResolved = w.Projectiles.TrueForAll(p => p.Resolved); + if (!allResolved) continue; + if ((now - w.LastImpactAt).TotalMilliseconds < ImpactEvidenceGraceMs) continue; + _castWatches.RemoveAt(i); + + bool reached = _envLastEvidenceAt >= w.CastAt; + bool allShort = w.Projectiles.TrueForAll(p => p.Short); + if (!reached && allShort) + RecordEnvironmentImpact(w.TargetId, EnvKind.Magic, + $"'{w.SpellName}' stopped short of the target ({w.Projectiles.Count} projectile{(w.Projectiles.Count == 1 ? "" : "s")})"); + } + } + + // ── Think: the response ─────────────────────────────────────────────────── + + /// + /// In ThinkCore once the target is valid and in reach. True = this tick belongs to the + /// response (an approach under way, or the target just switched): no attack. + /// + internal bool RunEnvironmentImpact(WorldObject targetObj, double currentDist) + { + DateTime now = EnvClock(); + if (_envApproachTargetId != 0) + { + if (_envApproachTargetId == activeTargetId) + return ContinueEnvironmentApproach(targetObj, currentDist, now); + EndEnvironmentApproach("the target changed"); + } + + if (_envPendingTargetId == 0) return false; + if (_envPendingTargetId != activeTargetId) { _envPendingTargetId = 0; return false; } + EnvKind kind = _envPendingKind; + // The cast in flight finishes first: turning or running now would cancel it. + if (kind == EnvKind.Magic && IsCastInFlight()) return true; + // A re-sync sidestep already holding a movement key finishes first: running or turning + // over it would send two movement states at once. + if (_resyncState == 2) return true; + + int id = activeTargetId; + _envPendingTargetId = 0; + EnvThrottle.ResetHits(id); + EnvironmentResponse response = ResponseFor(kind); + int minDist = Math.Max(1, _settings.EnvironmentMinDistance); + EnvironmentAction action = EnvironmentImpactPlanner.Decide(response, EnvThrottle.Approaches(id), + currentDist, minDist, HasAlternateTarget(id)); + string who = $"0x{(uint)id:X8} '{targetObj.Name}' at {currentDist:0.0}m"; + string why = kind == EnvKind.Missile ? "missiles" : "spells"; + + switch (action) + { + case EnvironmentAction.NewTarget: + { + if (_serverAttackTargetId != 0) ReleaseServerAttack("environment hits", log: false); + int skip = Math.Max(1, _settings.EnvironmentSkipSec); + _envSkipUntil[id] = now.AddSeconds(skip); + _host.Log($"[EnvImpact] {why} keep hitting the environment: leaving {who}, skipping it {skip}s ({EnvironmentImpactPlanner.Name((int)response)})"); + SupersedeResync("a new target"); + ForgetScanned(id); + DropTarget("environment hits: new target"); + return true; + } + case EnvironmentAction.Approach: + { + if (_serverAttackTargetId != 0) ReleaseServerAttack("environment hits", log: false); + double goal = EnvironmentImpactPlanner.ApproachGoal(currentDist, _settings.EnvironmentApproachMeters, minDist); + EnvThrottle.NoteApproach(id); + _envApproachTargetId = id; + _envApproachKind = kind; + _envApproachGoal = goal; + _envApproachBestDist = currentDist; + _envApproachStartedAt = _envApproachProgressAt = _envApproachTickAt = now; + _envApproachRunAt = _envApproachTurnAt = DateTime.MinValue; + _envApproachUsedMotions = false; + _host.Log($"[EnvImpact] {why} keep hitting the environment: moving closer to {who}, stopping at {goal:0.0}m ({EnvironmentImpactPlanner.Name((int)response)})"); + SupersedeResync("moving closer"); + return ContinueEnvironmentApproach(targetObj, currentDist, now); + } + default: + _host.Log($"[EnvImpact] {why} keep hitting the environment on {who}, but it's the only monster in reach and already close: attacking on"); + return false; + } + } + + /// + /// The throttle acted on misses the magic re-sync (TickResyncStep) was also counting. The + /// misses are explained (a wall in the way), so the re-sync's count starts over, and a + /// sidestep that is wanted but not yet started is dropped. Moving closer is itself real + /// movement, which re-syncs the server's copy of our position anyway. + /// + private void SupersedeResync(string by) + { + _magicMissesSinceHit = 0; + if (_resyncState != 1) return; + _resyncState = 0; + _host.Log($"[EnvImpact] re-sync sidestep dropped: {by} answers the misses"); + } + + /// Stops a re-sync sidestep where it is, letting go of its movement key if held. + private void AbandonResync(string why) + { + if (_resyncState == 0) return; + if (_resyncState == 2) _host.SetMotionBy("Combat/Resync", _resyncMotion, false); + _resyncState = 0; + _host.Log($"[CombatCast] re-sync sidestep stopped: {why}"); + } + + private bool ContinueEnvironmentApproach(WorldObject targetObj, double currentDist, DateTime now) + { + _envApproachTickAt = now; + if (currentDist <= _envApproachGoal) + { + EndEnvironmentApproach($"reached {currentDist:0.0}m"); + return false; + } + if ((now - _envApproachStartedAt).TotalMilliseconds > ApproachMaxMs) + { + EndEnvironmentApproach($"timed out at {currentDist:0.0}m"); + return false; + } + if (currentDist < _envApproachBestDist - ApproachProgressMeters) + { + _envApproachBestDist = currentDist; + _envApproachProgressAt = now; + } + else if ((now - _envApproachProgressAt).TotalMilliseconds > ApproachNoProgressMs) + { + EndEnvironmentApproach($"no progress (blocked?) at {currentDist:0.0}m"); + return false; + } + + // Face the target, then run. A held call (the pacer, a use) is simply tried next tick. + if ((now - _envApproachTurnAt).TotalMilliseconds >= ApproachTurnRefreshMs + && TryGetHeadingTo(activeTargetId, out double desiredDeg, out double err) + && err > ApproachFaceToleranceDeg) + { + if (_host.HasTurnToHeading) + { + if (_host.TurnToHeadingBy("Combat/Approach", (float)desiredDeg)) _envApproachTurnAt = now; + } + else + { + FaceTarget(activeTargetId); + _envApproachUsedMotions = true; + _envApproachTurnAt = now; + } + } + if ((now - _envApproachRunAt).TotalMilliseconds >= ApproachRunRefreshMs + && _host.SetAutoRunBy("Combat/Approach", true)) + _envApproachRunAt = now; + + _stallWatch.Hold(now); + LastCombatSkipReason = "env-approach"; // D4 record-only + return true; + } + + /// Stops an approach in progress (autorun off). Safe to call when none is. + private void EndEnvironmentApproach(string why) + { + if (_envApproachTargetId == 0) return; + int id = _envApproachTargetId; + _envApproachTargetId = 0; + if (_envApproachRunAt != DateTime.MinValue) _host.SetAutoRunBy("Combat/Approach", false); + if (_envApproachUsedMotions) ClearCombatTurnMotions(); + _host.Log($"[EnvImpact] {_envApproachKind.ToString().ToLowerInvariant()} approach to 0x{(uint)id:X8} ended: {why}"); + } + + /// True while is being skipped for its environment hits. + private bool IsEnvironmentSkipped(int id) + { + if (_envSkipUntil.Count == 0 || !_envSkipUntil.TryGetValue(id, out DateTime until)) return false; + if (EnvClock() < until) return true; + _envSkipUntil.Remove(id); + return false; + } + + /// Clears every environment-impact state (macro stop, new character). + private void ResetEnvironmentImpact(string why) + { + EndEnvironmentApproach(why); + AbandonResync(why); + _envPendingTargetId = 0; + _castWatches.Clear(); + _envCandidates.Clear(); + while (_envCreated.TryDequeue(out _)) { } + EnvThrottle.Clear(); + _envSkipUntil.Clear(); + } + + // ── Positions (global metres: landblock x/y * 192 + the in-block offset) ── + + private bool TryGetObjectGlobal(uint id, out double x, out double y, out double z) + { + x = y = z = 0; + if (!_host.TryGetObjectPosition(id, out uint cell, out float lx, out float ly, out float lz)) return false; + x = ((cell >> 24) & 0xFF) * 192.0 + lx; + y = ((cell >> 16) & 0xFF) * 192.0 + ly; + z = lz; + return true; + } + + private bool TryGetPlayerGlobal(out double x, out double y, out double z) + { + x = y = z = 0; + if (!_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, + out _, out _, out _, out _)) return false; + x = ((cell >> 24) & 0xFF) * 192.0 + lx; + y = ((cell >> 16) & 0xFF) * 192.0 + ly; + z = lz; + return true; + } + + private static double Dist(double ax, double ay, double az, double bx, double by, double bz) + { + double dx = ax - bx, dy = ay - by, dz = az - bz; + return Math.Sqrt(dx * dx + dy * dy + dz * dz); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Kite.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Kite.cs new file mode 100644 index 0000000..07fac25 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Kite.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.Shared; // TurnToHeadingBy / SetAutoRunBy + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Kite / pull-away (2026-10-16). Rules in KiteModes.cs; distance in LegacyUiSettings.KitePullMeters. +/// +/// When the effective monster rule is PullAway, combat tags the mob (one hit window), then +/// autoruns away from its lock-spot origin until the mob has been dragged that many metres +/// clear of where it stood, then stops and kills it. Default and per-mob via MonsterRule.Kite. +/// +public partial class CombatManager +{ + /// Clock for the kite state machine; tests replace it. + internal Func KiteClock { get; set; } = () => DateTime.Now; + + // Face-away + autorun cadence (mirrors EnvironmentApproach). + private const double KiteTurnRefreshMs = 300; + private const double KiteRunRefreshMs = 1000; + // Think stopped driving the kite (buffing took over): let go of autorun. + private const double KiteOrphanMs = 1500; + // Tag window: allow attacks so aggro sticks before we turn and run. + private const double KiteTagMaxMs = 2500; + // A pull that never gets far enough (blocked, mob leashed) gives up and fights in place. + private const double KiteMaxMs = 20000; + // Don't outrun the chase: stop autorun when farther than this from the mob. + private const double KiteCatchUpSlackMeters = 1.5; + // Progress toward the pull goal; no gain in this long ⇒ blocked / leashed. + private const double KiteProgressMeters = 0.75; + private const double KiteNoProgressMs = 4000; + + private enum KitePhase { None, Tag, Flee, Done } + + private int _kiteTargetId; + private KitePhase _kitePhase = KitePhase.None; + private double _kiteOriginX, _kiteOriginY, _kiteOriginZ; + private bool _kiteHasOrigin; + private double _kiteBestPull; + private DateTime _kiteStartedAt, _kiteProgressAt, _kiteRunAt, _kiteTurnAt, _kiteTickAt; + private bool _kiteUsedMotions; + // Targets already pulled this engagement (object id): do not re-kite mid-fight. + private readonly HashSet _kiteDoneIds = new(); + + /// True while combat is tagging or running a pull-away for the locked target. + internal bool KiteActive => _kitePhase is KitePhase.Tag or KitePhase.Flee; + + /// + /// In ThinkCore once the target is valid. True = this tick belongs to the kite (flee under + /// way): no attack. Tag phase returns false so the first hit(s) can land. + /// + internal bool RunKite(WorldObject targetObj, double currentDist) + { + DateTime now = KiteClock(); + int id = activeTargetId; + if (id == 0) { EndKite("no target"); return false; } + + // Already pulled this object id for this engagement: fight in place. + if (_kiteDoneIds.Contains(id)) + { + if (_kiteTargetId == id) EndKite("already pulled"); + return false; + } + + var rule = GetRuleForTarget(targetObj); + if (!KiteModes.WantsPullAway(rule, DefaultMonsterRule())) + { + if (_kiteTargetId == id) EndKite("rule Off"); + return false; + } + + // Start (or retarget) a pull for this lock. + if (_kiteTargetId != id || _kitePhase == KitePhase.None) + { + if (_kiteTargetId != 0 && _kiteTargetId != id) + EndKite("the target changed"); + BeginKite(id, targetObj, now); + } + + _kiteTickAt = now; + double pullMeters = Math.Max(3.0, _settings.KitePullMeters); + + if (_kitePhase == KitePhase.Tag) + { + bool tagged = _lastDamageDealtAt != DateTime.MinValue && _lastDamageDealtAt >= _kiteStartedAt; + bool tagTimedOut = (now - _kiteStartedAt).TotalMilliseconds >= KiteTagMaxMs; + if (!_settings.KiteTagFirst || tagged || tagTimedOut) + { + _kitePhase = KitePhase.Flee; + _kiteBestPull = PullDistance(id); + _kiteProgressAt = now; + _kiteRunAt = _kiteTurnAt = DateTime.MinValue; + string why = !_settings.KiteTagFirst ? "tag skipped" + : tagged ? "tagged" + : "tag timed out"; + _host.Log($"[Kite] pull-away on 0x{(uint)id:X8} '{targetObj.Name}': fleeing ({why}), goal {pullMeters:0}m from origin"); + EndEnvironmentApproach("kite pull-away"); + } + else + { + LastCombatSkipReason = "kite-tag"; + return false; // let Think attack once so aggro sticks + } + } + + if (_kitePhase != KitePhase.Flee) return false; + + double pulled = PullDistance(id); + if (pulled >= pullMeters) + { + FinishKite(id, $"pulled {pulled:0.0}m"); + return false; + } + if ((now - _kiteStartedAt).TotalMilliseconds > KiteMaxMs) + { + FinishKite(id, $"timed out at {pulled:0.0}m"); + return false; + } + if (pulled > _kiteBestPull + KiteProgressMeters) + { + _kiteBestPull = pulled; + _kiteProgressAt = now; + } + else if ((now - _kiteProgressAt).TotalMilliseconds > KiteNoProgressMs) + { + FinishKite(id, $"no progress (blocked/leashed?) at {pulled:0.0}m"); + return false; + } + + // Don't outrun the chase past disengage: wait for the mob to catch up. + double catchUp = Math.Max(1.0, DisengageDistance - KiteCatchUpSlackMeters); + bool waiting = currentDist > catchUp; + + // Face away from the mob while fleeing; face it while waiting for catch-up. + if ((now - _kiteTurnAt).TotalMilliseconds >= KiteTurnRefreshMs + && TryGetHeadingTo(id, out double towardDeg, out _)) + { + double faceDeg = waiting ? towardDeg : (towardDeg + 180.0) % 360.0; + if (_host.HasTurnToHeading) + { + if (_host.TurnToHeadingBy("Combat/Kite", (float)faceDeg)) _kiteTurnAt = now; + } + else + { + // No heading snap: FaceTarget only faces toward the mob (useful while waiting). + if (waiting) { FaceTarget(id); _kiteUsedMotions = true; } + _kiteTurnAt = now; + } + } + + if (waiting) + { + if (_kiteRunAt != DateTime.MinValue) + { + _host.SetAutoRunBy("Combat/Kite", false); + _kiteRunAt = DateTime.MinValue; + } + LastCombatSkipReason = "kite-wait"; + _stallWatch.Hold(now); + return true; + } + + if ((now - _kiteRunAt).TotalMilliseconds >= KiteRunRefreshMs + && _host.SetAutoRunBy("Combat/Kite", true)) + _kiteRunAt = now; + + _stallWatch.Hold(now); + LastCombatSkipReason = "kite-flee"; + return true; + } + + private void BeginKite(int id, WorldObject targetObj, DateTime now) + { + _kiteTargetId = id; + _kitePhase = _settings.KiteTagFirst ? KitePhase.Tag : KitePhase.Flee; + _kiteHasOrigin = TryGetObjectGlobal((uint)id, out _kiteOriginX, out _kiteOriginY, out _kiteOriginZ); + if (!_kiteHasOrigin) + _kiteHasOrigin = TryGetPlayerGlobal(out _kiteOriginX, out _kiteOriginY, out _kiteOriginZ); + _kiteBestPull = 0; + _kiteStartedAt = _kiteProgressAt = _kiteTickAt = now; + _kiteRunAt = _kiteTurnAt = DateTime.MinValue; + _kiteUsedMotions = false; + string phase = _kitePhase == KitePhase.Tag ? "tag then flee" : "flee"; + _host.Log($"[Kite] pull-away start 0x{(uint)id:X8} '{targetObj.Name}' ({phase}, {_settings.KitePullMeters}m)"); + if (_kitePhase == KitePhase.Flee) + EndEnvironmentApproach("kite pull-away"); + } + + /// How far the mob has been dragged from its lock-spot origin (metres). + private double PullDistance(int id) + { + if (!_kiteHasOrigin) return 0; + if (!TryGetObjectGlobal((uint)id, out double x, out double y, out double z)) + return _kiteBestPull; + return Dist(x, y, z, _kiteOriginX, _kiteOriginY, _kiteOriginZ); + } + + /// Pull succeeded or gave up: remember the id and fight in place. + private void FinishKite(int id, string why) + { + _kiteDoneIds.Add(id); + if (_kiteDoneIds.Count > 64) _kiteDoneIds.Clear(); + EndKite(why); + _host.Log($"[Kite] pull-away done 0x{(uint)id:X8}: {why} — attacking"); + } + + /// Stops a kite in progress (autorun off). Safe to call when none is. + private void EndKite(string why) + { + if (_kitePhase == KitePhase.None && _kiteTargetId == 0) return; + int id = _kiteTargetId; + bool wasRunning = _kiteRunAt != DateTime.MinValue; + _kiteTargetId = 0; + _kitePhase = KitePhase.None; + _kiteHasOrigin = false; + if (wasRunning) _host.SetAutoRunBy("Combat/Kite", false); + if (_kiteUsedMotions) ClearCombatTurnMotions(); + _kiteRunAt = _kiteTurnAt = DateTime.MinValue; + if (id != 0) + _host.Log($"[Kite] ended 0x{(uint)id:X8}: {why}"); + } + + /// Clears kite state (macro stop, new character). + private void ResetKite(string why) + { + EndKite(why); + _kiteDoneIds.Clear(); + } + + /// + /// Pump-thread orphan watch: Think drives the flee; when it stops (another activity, + /// combat off) autorun must not be left on. + /// + internal void PollKite() + { + if (_kitePhase == KitePhase.None) return; + DateTime now = KiteClock(); + if ((now - _kiteTickAt).TotalMilliseconds > KiteOrphanMs + || !_settings.EnableCombat + || !_settings.IsMacroRunning) + EndKite("combat stopped driving it"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index e88c14d..0fe8f80 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -1033,6 +1033,9 @@ public partial class CombatManager : IDisposable // A ghost (the server doesn't have it for us): skipped until it shows it is real. if (Ghosts.IsGhost(wo.Id)) { _ghostsSkippedInScan++; continue; } + // Left for hitting the environment (New target): skipped for EnvironmentSkipSec. + if (IsEnvironmentSkipped(wo.Id)) continue; + // Just killed (KillerNotification) but not yet a corpse — skip so we // don't re-lock and cast at it during its death animation. if (_recentlyKilled.ContainsKey(wo.Id)) continue; @@ -1135,6 +1138,7 @@ public partial class CombatManager : IDisposable _hitAt.Remove(id); _blacklistManager.ForgetTarget(id); Ghosts.NoteDeleted(id); + OnEnvironmentObjectDeleted(objectId); if (id == activeTargetId || id == _lockedTargetId || id == _lastAttackedTargetId) _awaitingCastResolution = false; @@ -1436,13 +1440,15 @@ public partial class CombatManager : IDisposable _damageStore!.RecordTaken(src, name, ElementFromWord(m.Groups["type"].Value), amount); } - /// A chat line for the damage meter and the stall watchdog. + /// A chat line for the damage meter, the stall watchdog and the environment throttle. /// is the line's eChatTypes (-1 = not known). public void HandleChatForDamage(string text, int chatType = -1) { if (string.IsNullOrEmpty(text)) return; // Combat lines come from the server; one in a player's chat type is someone's imitation. if (RynthCore.Plugin.Shared.ChatSource.IsPlayerAuthored(chatType)) return; + // An arrow into a wall: the environment-impact throttle's missile signal. + if (NoteMissileEnvironmentChat(text)) return; // A miss is a swing too (stall watchdog). "You evaded X!" is the monster's miss, not ours. if (text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase) > 0) NoteSwingEvidence("miss"); @@ -1455,6 +1461,7 @@ public partial class CombatManager : IDisposable if (critLine) _lastCritChatAt = now; if (!CombatText.TryParseOutgoingHit(text, out string victim, out int amount)) return; + NoteEnvironmentEvidence(); // a cast that hit something didn't only hit the environment bool crit = critLine || (now - _lastCritChatAt).TotalMilliseconds <= CRIT_WINDOW_MS; // Which monster the line is about. One spell can hurt several (rings, walls, blasts, @@ -1878,12 +1885,214 @@ public partial class CombatManager : IDisposable /// Test seam: one judged magic cast with no damage. internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid); + // ── Empyrean Handler lethal-ring evade (chat-triggered back-jump) ───────── + // ACECustom Handler emote: "The handler briefly channels infused Empyrean hatred + // to release a lethal ring." The ring can't be melee-evaded — if the character is + // inside its cast radius they die. On that line, when still in range of a Handler, + // cancel the current swing/cast and back-jump away, then resume combat (target kept). + private const string HandlerRingChannelHint = "channels infused Empyrean hatred to release a lethal ring"; + private const string HandlerRingChannelStart = "The handler briefly channels"; + private const string HandlerNameHint = "Empyrean Handler"; + /// Yards: Handler lethal ring is treated as at least this wide (RingRange when larger). + internal const double HandlerRingDangerYards = 12.0; + /// Back-jump charge (ms) — run-back + jump must clear ~ring radius. + private const int HandlerRingJumpHoldMs = 750; + private const double HandlerRingEvadeCooldownMs = 4_000; + + private DateTime _handlerRingEvadeAt = DateTime.MinValue; + private DateTime _handlerRingEvadeUntil = DateTime.MinValue; + private int _handlerRingEvadeId; + private bool _handlerRingJumpStarted; + + /// + /// Plugin wires this to Jumper.Start("xs", faceHeading, ms) — face the Handler + /// then run-back jump (x+s) so the body moves away. Returns false if the jumper refused. + /// + public Func? RequestBackJump { get; set; } + + /// True while the wired jumper is mid-turn / charge / settle. + public Func? JumpBusy { get; set; } + + /// True while a Handler-ring evade is holding combat (jump or settle). + public bool RingEvadeActive => + _handlerRingEvadeUntil != DateTime.MinValue && DateTime.Now < _handlerRingEvadeUntil; + + /// + /// Chat line from RynthAiPlugin.OnChatWindowText. Starts a back-jump evade when the + /// Handler channels its lethal ring and the character is still inside ring range. + /// + public void HandleChatForRingEvade(string? text, int chatType = -1) + { + if (string.IsNullOrEmpty(text)) return; + // Gate: only while the macro is running with combat on, and only if the setting allows it. + // Otherwise a Handler line heard while the character is idle or being driven by hand (or by a + // meta) would take over the keyboard for a back-jump. + if (!_settings.HandlerRingEvade || !_settings.IsMacroRunning || !_settings.EnableCombat) return; + // Handler channel is an Emote (0x0C). ChatSource.IsPlayerAuthored treats Emote as + // player speech, which would skip every real Handler line — anchor on the unique + // phrase starting the line instead (player copies are "Name says, \"...\"). + bool anchored = + RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, HandlerRingChannelStart, StringComparison.OrdinalIgnoreCase) + || (RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase) + && text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) >= 0); + if (!anchored) + { + // Mid-line only when the type is clearly not player speech (some clients strip "The "). + if (chatType is RynthCore.Plugin.Shared.ChatSource.Speech + or RynthCore.Plugin.Shared.ChatSource.Tell + or RynthCore.Plugin.Shared.ChatSource.OutgoingTell + or RynthCore.Plugin.Shared.ChatSource.Channel + or RynthCore.Plugin.Shared.ChatSource.ChannelSend + or RynthCore.Plugin.Shared.ChatSource.Allegiance + or RynthCore.Plugin.Shared.ChatSource.Fellowship) + return; + if (text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return; + if (text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) >= 0 + || text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) >= 0) + return; + } + + DateTime now = DateTime.Now; + if (_handlerRingEvadeAt != DateTime.MinValue + && (now - _handlerRingEvadeAt).TotalMilliseconds < HandlerRingEvadeCooldownMs) + return; + + if (!TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name)) + { + _host.Log("[CombatEvade] Handler lethal-ring channel heard, but no Empyrean Handler is nearby — no jump."); + return; + } + + double danger = Math.Max(HandlerRingDangerYards, Math.Max(1, _settings.RingRange)); + if (dist > danger) + { + _host.Log($"[CombatEvade] Handler lethal-ring channel; '{name}' at {dist:0.0} m (outside {danger:0.#} m) — staying put."); + return; + } + + // Face the Handler, then Jumper "xs" (back + run) moves the body away from it. + // Facing away + back-jump would leap into the ring. + float faceHandler = 0f; + if (TryGetHeadingTo(handlerId, out double toHandler, out _)) + faceHandler = (float)(toHandler % 360.0); + else if (_host.TryGetPlayerHeading(out float curr)) + faceHandler = curr; + + _handlerRingEvadeAt = now; + _handlerRingEvadeId = handlerId; + _handlerRingJumpStarted = false; + // Hold combat long enough for turn + charge + land + one re-engage tick. + _handlerRingEvadeUntil = now.AddMilliseconds(HandlerRingJumpHoldMs + 2_200); + + // Stop the bound melee/missile attack so the jump isn't eaten by the swing servo. + try + { + if (_host.HasCancelAttack) _host.CancelAttack(); + ReleaseHeldTurn(); + } + catch { } + + bool started = RequestBackJump?.Invoke(faceHandler, HandlerRingJumpHoldMs) == true; + if (started) + { + _handlerRingJumpStarted = true; + _host.Log($"[CombatEvade] Empyrean Handler lethal ring — back-jump away from '{name}' " + + $"at {dist:0.0} m (danger {danger:0.#} m), face {faceHandler:0}° then xs."); + } + else + { + _handlerRingEvadeUntil = DateTime.MinValue; + _handlerRingEvadeId = 0; + _host.Log("[CombatEvade] Empyrean Handler lethal ring heard in range, but the back-jump did not start."); + } + } + + /// + /// Holds Think from attacking while the Handler-ring back-jump runs. Keeps the target + /// so combat re-engages as soon as the jumper settles. + /// + private bool TickRingEvade() + { + if (_handlerRingEvadeUntil == DateTime.MinValue) return false; + DateTime now = DateTime.Now; + bool jumperBusy = JumpBusy?.Invoke() == true; + + // Jump never started / failed: clear early. + if (_handlerRingJumpStarted && !jumperBusy && now >= _handlerRingEvadeUntil) + { + _handlerRingEvadeUntil = DateTime.MinValue; + _handlerRingEvadeId = 0; + _handlerRingJumpStarted = false; + _host.Log("[CombatEvade] Handler ring evade done — re-engaging."); + return false; + } + + if (jumperBusy || now < _handlerRingEvadeUntil) + { + LastCombatSkipReason = "handler-ring-evade"; + _tickWait = CombatLatencyTracker.Wait.Other; + return true; + } + + _handlerRingEvadeUntil = DateTime.MinValue; + _handlerRingEvadeId = 0; + _handlerRingJumpStarted = false; + _host.Log("[CombatEvade] Handler ring evade done — re-engaging."); + return false; + } + + /// Nearest Empyrean Handler (active target preferred when it is one). + private bool TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name) + { + handlerId = 0; dist = double.MaxValue; name = ""; + int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(); + if (me == 0) return false; + + int bestId = 0; + double bestDist = double.MaxValue; + string bestName = ""; + + void Consider(int id, string? nm) + { + if (id == 0 || string.IsNullOrEmpty(nm)) return; + if (nm.IndexOf(HandlerNameHint, StringComparison.OrdinalIgnoreCase) < 0) return; + double d = _worldFilter.Distance(me, id); + if (d < 0 || d >= bestDist) return; + bestDist = d; bestId = id; bestName = nm; + } + + if (activeTargetId != 0) + Consider(activeTargetId, _worldFilter[activeTargetId]?.Name); + + foreach (var s in _scannedTargets) + Consider(s.Id, s.Name); + + // Landscape fallback when the scan hasn't listed it yet (channel can land mid-approach). + if (bestId == 0) + { + try + { + foreach (WorldObject wo in _worldFilter.GetLandscape()) + { + if ((int)wo.ObjectClass != (int)AcObjectClass.Monster) continue; + Consider(wo.Id, wo.Name); + } + } + catch { } + } + + if (bestId == 0) return false; + handlerId = bestId; dist = bestDist; name = bestName; + return true; + } + public void ReportDamageOnTarget(int targetId) { _magicMissesSinceHit = 0; // something we cast landed: the server's position is fine // Damage / health change on the cast we're judging → that cast HIT. if (targetId == _pendingJudgeTargetId) _damageSincePendingCast = true; + NoteEnvironmentEvidence(); // Immediate positive feedback on the engaged target clears the streak. if (targetId == _lastAttackedTargetId) _consecutiveCastMisses = 0; @@ -1904,6 +2113,7 @@ public partial class CombatManager : IDisposable int i = text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase); if (i < 0) i = text.IndexOf(" resists your spell", StringComparison.OrdinalIgnoreCase); if (i <= 0) return; + NoteEnvironmentEvidence(); // the spell or swing reached a monster string who = text.Substring(0, i).Trim(); if (who.StartsWith("The ", StringComparison.Ordinal)) who = who.Substring(4); if (who.Length == 0) return; @@ -2225,6 +2435,9 @@ public partial class CombatManager : IDisposable _host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason} [{DescribeTargetPos(activeTargetId)}]"); activeTargetId = 0; _lockedTargetId = 0; + EndKite("target dropped"); + EndEnvironmentApproach("target dropped"); + _envPendingTargetId = 0; // A turn held toward the dropped target must be let go, or the character keeps // spinning until something else happens to release it. if (_facingTarget) ClearCombatTurnMotions(); @@ -2675,9 +2888,15 @@ public partial class CombatManager : IDisposable // one busy-count tick; only the first encounter of a wcid pays it. if (!_fightAppraiseRequested) { - _fightAppraiseRequested = true; - try { if (_host.HasRequestId) _host.RequestId((uint)_fightTargetId); } catch { } - try { if (_host.HasQueryHealth) _host.QueryHealth((uint)_fightTargetId); } catch { } + // Done only once the engine took the request (it refuses around a death or a portal; a refused one + // is asked again next tick). No RequestId at all: nothing to wait for. + bool idTaken = true; + try { if (_host.HasRequestId) idTaken = _host.RequestId((uint)_fightTargetId); } catch { } + if (idTaken) + { + _fightAppraiseRequested = true; + try { if (_host.HasQueryHealth) _host.QueryHealth((uint)_fightTargetId); } catch { } + } } } @@ -2727,6 +2946,7 @@ public partial class CombatManager : IDisposable int id = _scannedTargets[i].Id; if (id == excludeId) continue; if (_recentlyKilled.ContainsKey(id)) continue; + if (IsEnvironmentSkipped(id)) continue; return true; } return false; @@ -2878,6 +3098,11 @@ public partial class CombatManager : IDisposable return true; } + // Empyrean Handler lethal-ring back-jump: hold casts/swings until the jump settles, + // then fall through and re-engage the same target. + if (TickRingEvade()) + return true; + double acDistanceLimit = _settings.MonsterRange; // Hysteresis: a locked target is retained (and kept under attack) out to // the larger disengage distance, while new targets are still only @@ -2977,7 +3202,7 @@ public partial class CombatManager : IDisposable ForgetScanned(activeTargetId); DropTarget("hp=0"); } - else if (target != null && + else if (target != null && !KiteActive && _worldFilter.Distance(_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId) > disengageLimit) DropTarget("out of range"); // If target == null here it's a transient world-filter miss — keep the lock, @@ -3098,9 +3323,18 @@ public partial class CombatManager : IDisposable // step-back — instead of dropping to peace and restarting the approach. double currentDist = _worldFilter.Distance( _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId); + // Pull-away kite runs before the disengage gate: fleeing intentionally stretches + // range, and the kite itself waits for catch-up rather than idling here. + if (RunKite(targetObj, currentDist)) + return true; if (currentDist > disengageLimit) return true; + // Environment-impact throttle: too many missiles/spells into walls short of this target + // stop the attack and move closer or switch target (CombatManager.EnvironmentImpact.cs). + if (RunEnvironmentImpact(targetObj, currentDist)) + return true; + // Melee/missile stall safety net (see CombatStallWatchdog). Holds the attack while // one of its steps is settling. if (RunStallWatchdog(targetObj, currentDist)) @@ -3929,13 +4163,23 @@ public partial class CombatManager : IDisposable { _wasMacroRunning = false; ClearCombatTurnMotions(); + ResetEnvironmentImpact("macro stopped"); + ResetKite("macro stopped"); } return; } _wasMacroRunning = true; + NotePriorityZeroRules(); LogCombatStateIfChanged(); + // Environment-impact throttle: follow our spell projectiles, judge finished casts, and + // let go of an approach Think stopped driving. + try { PollEnvironmentImpact(); } + catch (Exception ex) { _host.Log($"[EnvImpact] poll crashed: {ex.Message}"); } + try { PollKite(); } + catch (Exception ex) { _host.Log($"[Kite] poll crashed: {ex.Message}"); } + // A combat mode change ends the server's attack (HandleActionChangeCombatMode → // HandleActionCancelAttack), so out of Melee/Missile there is nothing bound to release. if (_serverAttackTargetId != 0) @@ -4016,6 +4260,8 @@ public partial class CombatManager : IDisposable { if (_scannedTargets.Count == 0) return; if (TryLockForcedTarget()) return; // Target lock (/ra targetlock): CombatManager.TargetLock.cs + // Pull-away in progress: keep the incumbent until the kite ends (do not switch mid-flee). + if (KiteActive && _lockedTargetId != 0) return; // Boost Loot Priority: the next target waits for the last kill's corpse. Without this the // next lock went out a few ms after each kill, 1-3 s before ACE creates the corpse, so the // arbiter always saw combat engaged and corpses were looted in batches (2026-10-14). @@ -4236,6 +4482,35 @@ public partial class CombatManager : IDisposable return progress != DateTime.MinValue && (now - progress).TotalMilliseconds <= UndamagedCommitmentMaxMs; } + private List? _priorityZeroNoticeRules; + private string _priorityZeroNoticeKey = ""; + + /// + /// Priority 0 on a monster rule now means "never attacked or tracked" (before, it was a lowest + /// priority that still fought back). A profile written under the old meaning would silently stop + /// fighting those monsters, so the first time a rule list holds any, one log line and one chat + /// notice say what it does now (again only if the set of Priority 0 rules changes, e.g. another + /// profile loads). Behavior is not changed. + /// + internal void NotePriorityZeroRules() + { + var rules = _settings.MonsterRules; + if (ReferenceEquals(rules, _priorityZeroNoticeRules)) return; + _priorityZeroNoticeRules = rules; + List? zero = null; + foreach (var rule in rules) + if (rule.Priority <= 0) (zero ??= new List()).Add(string.IsNullOrWhiteSpace(rule.Name) ? "(unnamed)" : rule.Name); + if (zero == null) { _priorityZeroNoticeKey = ""; return; } + string key = string.Join("|", zero).ToLowerInvariant(); + if (key == _priorityZeroNoticeKey) return; + _priorityZeroNoticeKey = key; + string names = zero.Count <= 5 ? string.Join(", ", zero) : string.Join(", ", zero.GetRange(0, 5)) + $" and {zero.Count - 5} more"; + string line = $"[RynthAi] Monsters: Priority 0 now means 'never attacked or tracked', even if the monster attacks you " + + $"(rows with Priority 0: {names}). Raise the row's Priority to fight it."; + _host.Log(line); + _host.WriteToChat(line, 2); + } + /// True when the monster rule for says Priority 0 (never attacked). internal bool IsIgnored(int id) => id != ForcedTargetId && PriorityOf(id) <= 0; @@ -6101,17 +6376,26 @@ public partial class CombatManager : IDisposable return false; } - float power; + // Power: the monster rule's Attack Power (High / Reckless / Variable / Reckless + + // Variable), else the global Melee/Missile Power (AttackPowerPlanner.cs). int powerPct = isMissile ? _settings.MissileAttackPower : _settings.MeleeAttackPower; - if (powerPct < 0) + bool recklessTrained = _charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2; + // No rule asking for a power (every rule on Default, as saved before this existed): + // the rule lookup is skipped, the global setting applies exactly as it always did. + WorldObject? powerTarget = null; + string powerMode = AttackPowerModes.Default; + if (AnyAttackPowerRule()) { - power = 1.0f; - if (_settings.UseRecklessness && (_charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2)) - power = 0.8f; + powerTarget = _worldFilter[activeTargetId]; + powerMode = AttackPowerModes.Effective(GetRuleForTarget(powerTarget), DefaultMonsterRule()); } - else + float power = AttackPowerModes.Resolve(powerMode, powerPct, _settings.UseRecklessness, recklessTrained, + _settings.VariablePowerMin, _settings.VariablePowerMax, PowerRandom); + if (powerMode != AttackPowerModes.Default && _powerLoggedTargetId != activeTargetId) { - power = powerPct / 100f; + _powerLoggedTargetId = activeTargetId; + _host.Log($"[AttackPower] 0x{targetId:X8} '{powerTarget?.Name}': {powerMode}" + + (recklessTrained ? "" : " (Recklessness untrained: no reckless band)") + $", first attack at {power * 100:0}%"); } int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight; @@ -6173,10 +6457,25 @@ public partial class CombatManager : IDisposable if (matches) return r; } - return _settings.MonsterRules.FirstOrDefault( - m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + return DefaultMonsterRule(); } + /// The Monsters tab's DEFAULT line (the catch-all rule), or null. + private MonsterRule? DefaultMonsterRule() => _settings.MonsterRules.FirstOrDefault( + m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + + /// True when some monster rule has an Attack Power other than Default. + private bool AnyAttackPowerRule() + { + foreach (MonsterRule r in _settings.MonsterRules) + if (AttackPowerModes.Normalize(r.AttackPower) != AttackPowerModes.Default) return true; + return false; + } + + /// Random source for Variable attack power, [0, 1); tests replace it. + internal Func PowerRandom { get; set; } = Random.Shared.NextDouble; + private int _powerLoggedTargetId; + private void AttackWithMagic(WorldObject target) { _wallFaceHeld = false; @@ -6282,11 +6581,8 @@ public partial class CombatManager : IDisposable } } - // A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for - // its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no - // answer in time falls through to RynthAi's own choice below, this same tick. - if (TryScriptAttack(target, element)) return; - + // A rule with no attack shape on means no offensive cast at this monster: a script's choice + // is no exception (it used to be asked first, and cast at a monster the owner turned casting off for). if (rule != null && PickBaseShape(rule) < 0) { _host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast/Wall all false) — no offensive cast"); @@ -6294,6 +6590,11 @@ public partial class CombatManager : IDisposable return; } + // A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for + // its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no + // answer in time falls through to RynthAi's own choice below, this same tick. + if (TryScriptAttack(target, element)) return; + int warTier = _spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0; int voidTier = _spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0; int offensiveSpellId = FindBestShapedSpell(element, rule, out bool isRing, out int castShape, arcTargetId: activeTargetId); @@ -6353,6 +6654,10 @@ public partial class CombatManager : IDisposable _pendingOffensiveCastAt = DateTime.Now; _pendingOffensiveTargetId = activeTargetId; NoteOffensiveSeq(); + // Environment-impact throttle: follow this cast's projectiles (rings and walls + // don't fly at the target, so they aren't judged). + if (!multiTarget) + RegisterCastWatch(activeTargetId, SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}"); // Tag this cast's weapon + element + tier so the pushed damage event // can be attributed to it, count it for casts-to-kill learning, then diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/EnvironmentImpact.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/EnvironmentImpact.cs new file mode 100644 index 0000000..fac06f3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/EnvironmentImpact.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +// ============================================================================ +// Environment-impact throttle (2026-10-12): pure rules and bookkeeping. +// +// A missile or a war/void projectile that hits a wall, a pillar, the ceiling +// or another object short of the target does no damage, and before this the bot +// kept firing into it until the no-damage blacklist (several settle windows) or +// the no-progress timeout gave up. Now, once a target has taken +// EnvironmentImpactLimit such hits within EnvironmentImpactWindowSec, combat +// stops attacking it and does what the player chose for that kind of combat: +// move closer, pick another target, or move closer once and then pick another. +// +// The signals (CombatManager.EnvironmentImpact.cs): +// missile ACE ProjectileCollisionHelper.OnCollideEnvironment sends the shooter +// "Your missile attack hit the environment." (also when the arrow hits +// an object that isn't its target). +// magic ACE sends nothing (SpellProjectile.OnCollideEnvironment only +// explodes the projectile), so the bot follows its own projectiles and +// judges where they stopped (ProjectileImpactJudge). +// +// Everything here is pure (no host, no clock of its own) so the host tests can +// drive it directly. +// ============================================================================ + +/// What combat does once a target has taken too many environment hits. +/// Stored as an int in the settings (MissileEnvironmentResponse / MagicEnvironmentResponse). +public enum EnvironmentResponse +{ + /// No detection; keep attacking (the behaviour before 2026-10-12). + Off = 0, + /// Move toward the target each time; once already close, pick another target. + MoveCloser = 1, + /// Skip the target for a while and pick another (moves closer when there is no other). + NewTarget = 2, + /// Move closer once; if the shots still hit the environment, pick another target. + CloserThenNewTarget = 3, +} + +/// The step combat takes for one throttle trip. +public enum EnvironmentAction { None, Approach, NewTarget } + +/// Choices and the decision for one throttle trip. +public static class EnvironmentImpactPlanner +{ + /// Combo labels, in order (plugin and engine settings panels). + public static readonly string[] ResponseNames = + { "Off", "Move closer", "New target", "Move closer, then new target" }; + + /// Approaching is pointless within this much of the closest allowed distance. + public const double ApproachSlackMeters = 0.5; + + /// A saved int as a response; anything out of range is Off. + public static EnvironmentResponse Parse(int value) + => value is >= 0 and <= 3 ? (EnvironmentResponse)value : EnvironmentResponse.Off; + + /// The label for a saved value (logs and the settings panels). + public static string Name(int value) => ResponseNames[(int)Parse(value)]; + + /// + /// The step for a throttle trip on a target metres away that + /// has already been approached times for this reason. + /// Never approaches nearer than . A new target needs another + /// monster in reach: skipping the only one would leave it free to hit the bot while combat + /// idles, so then the bot moves closer if it still can, or keeps attacking (None). + /// + public static EnvironmentAction Decide(EnvironmentResponse response, int approachesDone, + double distance, double minDistance, bool hasAlternateTarget) + { + bool canApproach = double.IsFinite(distance) && distance > minDistance + ApproachSlackMeters; + EnvironmentAction approachElseNone = canApproach ? EnvironmentAction.Approach : EnvironmentAction.None; + EnvironmentAction newTargetElse = hasAlternateTarget ? EnvironmentAction.NewTarget : approachElseNone; + return response switch + { + EnvironmentResponse.MoveCloser => canApproach ? EnvironmentAction.Approach : newTargetElse, + EnvironmentResponse.NewTarget => newTargetElse, + EnvironmentResponse.CloserThenNewTarget => approachesDone == 0 && canApproach + ? EnvironmentAction.Approach : newTargetElse, + _ => EnvironmentAction.None, + }; + } + + /// + /// Where an approach stops: nearer than now, never nearer + /// than . + /// + public static double ApproachGoal(double distance, double stepMeters, double minDistance) + => Math.Max(Math.Max(0.5, minDistance), distance - Math.Max(1.0, stepMeters)); +} + +/// +/// Environment hits per target inside a sliding window, and how many times each target has +/// been approached for them. Pump thread only. +/// +public sealed class EnvironmentImpactThrottle +{ + private readonly Dictionary> _hits = new(); + private readonly Dictionary _approaches = new(); + // A long session meets thousands of monsters; ids are forgotten on delete, this is the backstop. + private const int MaxTracked = 256; + + /// Records one hit on and returns the hits within the window. + public int Record(int targetId, DateTime now, double windowSec) + { + if (targetId == 0) return 0; + if (_hits.Count >= MaxTracked && !_hits.ContainsKey(targetId)) _hits.Clear(); + if (!_hits.TryGetValue(targetId, out var list)) _hits[targetId] = list = new List(4); + list.Add(now); + Prune(list, now, windowSec); + return list.Count; + } + + /// Hits on within the window (no new hit). + public int Count(int targetId, DateTime now, double windowSec) + { + if (!_hits.TryGetValue(targetId, out var list)) return 0; + Prune(list, now, windowSec); + return list.Count; + } + + /// Starts the count again (after the bot acted on it). + public void ResetHits(int targetId) => _hits.Remove(targetId); + + public int Approaches(int targetId) => _approaches.TryGetValue(targetId, out int n) ? n : 0; + + public void NoteApproach(int targetId) + { + if (_approaches.Count >= MaxTracked && !_approaches.ContainsKey(targetId)) _approaches.Clear(); + _approaches[targetId] = Approaches(targetId) + 1; + } + + /// The object is gone (deleted): a respawn reusing the id starts clean. + public void Forget(int targetId) + { + _hits.Remove(targetId); + _approaches.Remove(targetId); + } + + public void Clear() + { + _hits.Clear(); + _approaches.Clear(); + } + + private static void Prune(List list, DateTime now, double windowSec) + { + double window = Math.Max(1.0, windowSec); + list.RemoveAll(t => (now - t).TotalSeconds > window); + } +} + +/// +/// Where a spell projectile stopped, against where the target is. A projectile that reaches +/// the target stops at its surface; one that hits the environment stops short of it, toward +/// the caster. Both conditions must hold, so a large monster (its surface a few metres from its +/// centre) isn't read as a wall. The caller also requires that no hit, resist or evade line +/// arrived for the cast: that is the final word for a large monster or an odd stop. +/// +public static class ProjectileImpactJudge +{ + /// A stop farther than this from the target's centre didn't touch it. + public const double MissRadiusMeters = 4.0; + /// A stop at least this much nearer to the caster than the target is "short". + public const double ShortByMeters = 2.0; + /// A projectile that flew less than this never really left (or was never ours). + public const double MinTravelMeters = 1.0; + + /// True when the projectile stopped short of the target and away from it. + public static bool StoppedShort(double impactToTarget, double casterToImpact, double casterToTarget) + { + if (!double.IsFinite(impactToTarget) || !double.IsFinite(casterToImpact) || !double.IsFinite(casterToTarget)) + return false; + return impactToTarget > MissRadiusMeters && casterToImpact + ShortByMeters < casterToTarget; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs index 7522361..79ffedc 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs @@ -309,6 +309,9 @@ public class FellowshipTracker : IDisposable return IsReadablePointer(fel) ? fel : IntPtr.Zero; } + /// Drops the refresh throttle: the next read re-walks the client's member table (RynthOracle's Refresh button). + public void Invalidate() => _lastRefresh = DateTime.MinValue; + private void RefreshIfNeeded() { if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) return; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/KiteModes.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/KiteModes.cs new file mode 100644 index 0000000..680e734 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/KiteModes.cs @@ -0,0 +1,79 @@ +using System; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +// ============================================================================ +// Per-monster kite / pull-away (2026-10-16): MonsterRule.Kite. +// +// Default the DEFAULT line's choice; on the DEFAULT line, Off (fight in place) +// Off engage and kill where the mob stands +// PullAway after a brief tag, run away until the mob has been pulled +// KitePullMeters from its lock-spot origin, then kill it alone +// +// Resolution matches AttackPowerModes: a rule's own value wins; "Default" falls +// through to the DEFAULT row; blank/unknown is Default (→ Off via the DEFAULT row). +// ============================================================================ + +/// Names and resolution of . +public static class KiteModes +{ + public const string Default = "Default"; + public const string Off = "Off"; + public const string PullAway = "PullAway"; + + /// Every choice, in the order the editors list them. + public static readonly string[] All = { Default, Off, PullAway }; + + /// Combo labels (plugin Advanced + engine Monsters/Damage panels). + public static readonly string[] DisplayNames = { "Default", "Off", "Pull away" }; + + /// A saved value as one of ; blank or unknown is Default. + public static string Normalize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return Default; + string v = value.Trim(); + foreach (string m in All) + if (m.Equals(v, StringComparison.OrdinalIgnoreCase)) return m; + // Hand-typed / UI spellings: "Pull away", "pull-away", "Kite". + string squeezed = v.Replace(" ", "").Replace("-", "").Replace("_", ""); + if (squeezed.Equals("PullAway", StringComparison.OrdinalIgnoreCase) + || squeezed.Equals("Kite", StringComparison.OrdinalIgnoreCase) + || squeezed.Equals("Pull", StringComparison.OrdinalIgnoreCase)) + return PullAway; + if (squeezed.Equals("None", StringComparison.OrdinalIgnoreCase) + || squeezed.Equals("Disabled", StringComparison.OrdinalIgnoreCase)) + return Off; + return Default; + } + + /// + /// The mode that applies to a monster: its own rule's, else the DEFAULT line's. + /// On the DEFAULT line, Default resolves to Off (safe: no pull until the player opts in). + /// + public static string Effective(MonsterRule? rule, MonsterRule? defaultRule) + { + string own = Normalize(rule?.Kite); + if (own != Default) return own; + // The DEFAULT row itself: Default means Off. + if (rule != null && defaultRule != null + && ReferenceEquals(rule, defaultRule)) + return Off; + if (rule != null && string.Equals(rule.Name, "Default", StringComparison.OrdinalIgnoreCase)) + return Off; + string fromDefault = Normalize(defaultRule?.Kite); + return fromDefault == Default ? Off : fromDefault; + } + + /// True when combat should pull this monster before finishing it. + public static bool WantsPullAway(MonsterRule? rule, MonsterRule? defaultRule) + => Effective(rule, defaultRule) == PullAway; + + /// Label for logs and tooltips. + public static string Name(string? value) => Normalize(value) switch + { + PullAway => "Pull away", + Off => "Off", + _ => "Default", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs index adadd13..12274b4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs @@ -54,6 +54,17 @@ public class MissileCraftingManager private const int EQUIP_DELAY_MS = 500; private const int ERROR_BACKOFF_MS = 60000; + // An ammo wield the server ignores (ammo that doesn't fit the launcher really in hand) came + // round again every AMMO_CHECK_INTERVAL_MS, and each try stopped nav while it waited for the + // answer: Silentkelpie stood still ~3.5 s of every 5 on 2026-10-15. The same item sent more + // than MAX_EQUIP_REPEATS times inside EQUIP_REPEAT_WINDOW_MS backs off instead. + private const int EQUIP_REPEAT_WINDOW_MS = 30000; + private const int MAX_EQUIP_REPEATS = 2; + private const int EQUIP_IGNORED_BACKOFF_MS = 120000; + private int _lastEquipSentId; + private DateTime _lastEquipSentAt = DateTime.MinValue; + private int _equipRepeats; + private int _headBundleId = 0; private int _shaftBundleId = 0; private AmmoRecipe? _currentRecipe = null; @@ -145,13 +156,15 @@ public class MissileCraftingManager _lastAmmoCheck = DateTime.Now; var inv = GetInventory(forceRefresh: true); - if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category)) + if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category, out WorldObject? launcher)) return; _lastWeaponCategory = category; if (HasWieldedAmmo(inv, category)) return; + _host.Log($"[RynthAi] MissileCraft: no {GetCategoryLabel(category)} wielded with launcher " + + $"0x{launcher!.Id:X8} '{launcher.Name}' (slot {launcher.WieldedLocation}); evaluating"); ChatLog($"No wielded {GetCategoryLabel(category)}s. Evaluating..."); SetState(CraftState.Evaluating); } @@ -350,6 +363,18 @@ public class MissileCraftingManager if (targetId != 0) { + if (!NoteEquipSent(targetId)) + { + string name = inv.FirstOrDefault(i => i.Id == targetId)?.Name ?? $"0x{targetId:X8}"; + string why = $"The server didn't wield {name} after {MAX_EQUIP_REPEATS} tries; " + + $"leaving the ammo alone for {EQUIP_IGNORED_BACKOFF_MS / 60000} minutes"; + _host.Log($"[RynthAi] MissileCraft: {why} (0x{targetId:X8})"); + Reset(why); + _equipRepeats = 0; + _lastAmmoCheck = DateTime.Now.AddMilliseconds(EQUIP_IGNORED_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS); + return; + } + _host.UseFor((uint)targetId, "Crafting", "missile crafting: wield the new ammo"); ChatLog($"Equipped ammo (id=0x{targetId:X8})"); Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}"); @@ -382,9 +407,9 @@ public class MissileCraftingManager private List GetInventory(bool forceRefresh = false) => _objectCache?.GetDirectInventory(forceRefresh).ToList() ?? new(); - private WeaponCategory ResolveWeaponCategory(IEnumerable inventory) + private WeaponCategory ResolveWeaponCategory(List inventory) { - if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category)) + if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category, out _)) { _lastWeaponCategory = category; return category; @@ -393,24 +418,29 @@ public class MissileCraftingManager return _lastWeaponCategory; } - private bool TryGetWieldedMissileCategory(IEnumerable inventory, out WeaponCategory category) + private bool TryGetWieldedMissileCategory(List inventory, out WeaponCategory category, + out WorldObject? launcher) { - foreach (var item in inventory) + foreach (var item in WornCandidates(inventory)) { - if (!IsPlayerWielded(item) || !LooksLikeMissileWeapon(item)) + // AC files ammo as a missile weapon: wielded quarrels must not pass for the launcher + // (no "crossbow" in the name reads as a bow, and arrows went on at the crossbow). + if (WorldObjectCache.IsAmmo(item) || !IsPlayerWielded(item) || !LooksLikeMissileWeapon(item)) continue; category = GetWeaponCategory(item.Name); + launcher = item; return true; } category = WeaponCategory.Bow; + launcher = null; return false; } - private bool HasWieldedAmmo(IEnumerable inventory, WeaponCategory category) + private bool HasWieldedAmmo(List inventory, WeaponCategory category) { - foreach (var item in inventory) + foreach (var item in WornCandidates(inventory)) { if (!IsPlayerWielded(item)) continue; @@ -422,16 +452,62 @@ public class MissileCraftingManager return false; } + /// + /// The direct scan plus the cache-known items it left out. The scan merges worn gear only when + /// its slot reads above 0, and the slot reads 0 for gear wielded after login (a launcher combat + /// swapped in, and its ammo), so the launcher really in hand was missing from the scan alone. + /// + private IEnumerable WornCandidates(List inventory) + { + foreach (var item in inventory) + yield return item; + + if (_objectCache == null) + yield break; + + var listed = new HashSet(inventory.Select(i => i.Id)); + foreach (var item in _objectCache.GetInventory()) + if (listed.Add(item.Id)) + yield return item; + } + private bool IsPlayerWielded(WorldObject item) { - if (item.WieldedLocation <= 0) + // Found inside a pack by the direct scan: AC's container lists never hold worn gear. A + // launcher put away after a swap keeps its old wielder and slot in the client's object + // description, so the slot alone said a stowed bow was in hand while a crossbow was, and + // arrows were wielded at it every 5 s (Silentkelpie, 2026-10-15). + if (item.DirectContainerId != 0) return false; uint playerId = _host.GetPlayerId(); if (playerId == 0) return false; - return item.Wielder == 0 || item.Wielder == unchecked((int)playerId); + if (item.WieldedLocation > 0) + return item.Wielder == 0 || item.Wielder == unchecked((int)playerId); + + // The slot reads 0 for gear wielded after login; the wielder still names the player. + return _host.HasGetObjectWielderInfo + && _host.TryGetObjectWielderInfo(unchecked((uint)item.Id), out uint wielder, out _) + && wielder == playerId; + } + + /// + /// Counts an ammo wield about to go out; false once the same item was already sent + /// times inside . + /// + private bool NoteEquipSent(int targetId) + { + DateTime now = DateTime.Now; + if (targetId == _lastEquipSentId && (now - _lastEquipSentAt).TotalMilliseconds < EQUIP_REPEAT_WINDOW_MS) + _equipRepeats++; + else + _equipRepeats = 1; + + _lastEquipSentId = targetId; + _lastEquipSentAt = now; + return _equipRepeats <= MAX_EQUIP_REPEATS; } private static bool LooksLikeMissileWeapon(WorldObject item) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs index 779dc16..87ff8ed 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs @@ -22,7 +22,8 @@ namespace RynthCore.Plugin.RynthAi; /// Behaviour (per user spec): /// * Summon only when mobs are near — at least PetMinMonsters scanned, /// attackable monsters within CustomPetRange — and no pet is currently -/// active. Re-summon when the pet despawns mid-fight. +/// active. Re-summon when the pet despawns mid-fight (lifespan / death), after +/// the essence's retail ~45 s use cooldown (Summoning wiki / ACE PetDevice). /// * Auto-refill an empty essence from an Encapsulated Spirit in inventory /// (gated on PetAutoRefill). /// @@ -30,6 +31,12 @@ namespace RynthCore.Plugin.RynthAi; /// guarded, one in-flight action at a time. Entirely plugin-side; the only AC /// actions issued are Host.UseObject (summon) and Host.UseObjectOn /// (refill), both selection-free. +/// +/// Stuck/fail (Kelpie 2026-10-16): a Use that the server refused (cooldown, incline, +/// busy) never drops Structure and never spawns a pet. The old path still assumed a +/// pet for 10 s and parked the essence only 30 s — short of the 45 s item cooldown — +/// so the next try timed out again. Failed summons no longer assume a pet; every +/// Use parks the essence for . /// internal sealed class PetManager { @@ -55,6 +62,7 @@ internal sealed class PetManager // pet is active for at least this long, so we don't re-issue before the new // pet's CreateObject lands in the cache. Name-detection takes over once it does. private long _assumePetActiveUntil; + private bool _petSeenSinceSummon; // the pet has shown up in the cache during this assume window // Devices that just failed (skill too low, timed out, empty with no spirit) // get parked so we advance to the next configured essence instead of looping. @@ -76,8 +84,14 @@ internal sealed class PetManager private const long ThinkIntervalMs = 1000; private const long ActionTimeoutMs = 8000; + /// Hold after a confirmed summon until the pet lands in the landscape cache (kept at the base's 10 s). private const long AssumeActiveAfterSummonMs = 10_000; - private const long DeviceFailCooldownMs = 30_000; + /// + /// Retail / ACE PetDevice use cooldown (~45 s). Applies after every Use we fire — success + /// or fail — so we do not re-Use while the server still refuses the essence. + /// + private const long DeviceUseCooldownMs = 45_000; + private const long DeviceFailCooldownMs = 30_000; // a refill that timed out (a summon is parked from IssueSummon) 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 @@ -140,7 +154,7 @@ internal sealed class PetManager { _summonElement = PetChoice.ElementOf(_host, unchecked((uint)_activeDeviceId), _objectCache[_activeDeviceId]?.Name ?? ""); - _assumePetActiveUntil = now + AssumeActiveAfterSummonMs; + AssumePetFor(now, AssumeActiveAfterSummonMs); GoIdle(); } } @@ -158,13 +172,27 @@ internal sealed class PetManager // decrement that never lands), and waiting on it would wedge the subsystem. if (_state != PetState.Idle && now - _actionIssuedAt > ActionTimeoutMs) { - RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down."); - if (_activeDeviceId != 0) - _deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs; - // A summon that we simply couldn't confirm very likely DID work — assume - // a pet for a bit so we don't immediately re-issue into "already active". - if (_state == PetState.Summoning) - _assumePetActiveUntil = now + AssumeActiveAfterSummonMs; + bool summonConfirmed = _state == PetState.Summoning + && (SummonLanded() || IsPetActive()); + // Host.Log so FakeHost / in-game logs see it; RynthLog for the Pets category file. + string timeoutMsg = + $"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8})" + + (summonConfirmed + ? "; summon confirmed late." + : "; no charge drop / no pet — treating as failed Use."); + _host.Log(timeoutMsg); + RynthLog.Write(LogCat.Pets, timeoutMsg); + // Do NOT restart DeviceUseCooldownMs here — IssueSummon already parked the essence + // from the Use instant. Re-arming from timeout would wait ~53 s and leave gaps + // after a refused Use (Kelpie stuck/fail). + // Only assume a pet when the Use clearly landed; a failed Use must not block + // resummon after the cooldown (false assume + short park left gaps). + if (_state != PetState.Summoning && _activeDeviceId != 0) + _deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs; // refill timeout: park as before + if (summonConfirmed) + AssumePetFor(now, AssumeActiveAfterSummonMs); + else if (_state == PetState.Summoning) + _assumePetActiveUntil = 0; Reset(); return; } @@ -186,7 +214,7 @@ internal sealed class PetManager // " is already active" — a pet is up but our detection lagged. Back off. if (text.Contains("is already active", StringComparison.OrdinalIgnoreCase)) { - _assumePetActiveUntil = NowMs + AssumeActiveAfterSummonMs; + AssumePetFor(NowMs, AssumeActiveAfterSummonMs); GoIdle(); return; } @@ -196,10 +224,15 @@ internal sealed class PetManager { _host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill."); _serverSaidFullUntil.Remove(_activeDeviceId); // really empty: the read is right again - // The server-side pyreal refill didn't happen (charm off / no pyreals): - // park the essence so the empty-summon path can't spin on it. - if (AllowSummonOnEmpty?.Invoke() == true && _activeDeviceId != 0) - _deviceCooldownUntil[_activeDeviceId] = NowMs + DeviceNoSpiritCooldownMs; + // Empty Use does not burn the retail 45 s spawn cooldown the way a real summon + // does; drop the Use park so the next think can refill (or re-try pyreal path). + if (_activeDeviceId != 0) + { + if (AllowSummonOnEmpty?.Invoke() == true) + _deviceCooldownUntil[_activeDeviceId] = NowMs + DeviceNoSpiritCooldownMs; + else + _deviceCooldownUntil.Remove(_activeDeviceId); + } GoIdle(); return; } @@ -223,15 +256,32 @@ internal sealed class PetManager // ── Decision ─────────────────────────────────────────────────────────────── + /// Treat a pet as out until + (it may not be in the cache yet). + private void AssumePetFor(long now, long ms) + { + _assumePetActiveUntil = now + ms; + _petSeenSinceSummon = false; + } + private void TryBeginAction(long now) { // A pet is already up (just summoned, or detected in the world) — done. - if (now < _assumePetActiveUntil) return; - if (IsPetActive()) + // If the assume window is still open but the pet is gone (despawn / death), clear it + // so we can wait on the essence cooldown and resummon. + bool petOut = IsPetActive(); + if (now < _assumePetActiveUntil) + { + if (petOut) { _petSeenSinceSummon = true; return; } + // The pet came and went (died / lifespan ended): don't wait out the window. A pet that has not + // landed in the cache yet keeps the window, or a second essence would be summoned beside it. + if (!_petSeenSinceSummon) return; + _assumePetActiveUntil = 0; + } + if (petOut) { // A cosmetic pet in the slot steps aside for the fight; wait for the dismiss to land. if (YieldPetForCombat != null && MonstersNearby() && YieldPetForCombat()) - _assumePetActiveUntil = now + 3000; + AssumePetFor(now, 3000); return; } if (HoldSummons?.Invoke() == true) return; @@ -298,15 +348,18 @@ internal sealed class PetManager private void IssueSummon(int deviceId, int charges) { // Don't fire the essence-use while a cast gesture is animating — AC - // refuses item use mid-gesture, which would burn the 8s timeout and a - // 30s device park for nothing. No state change; caller retries next tick. + // refuses item use mid-gesture, which would burn the 8s timeout and the + // 45 s essence cooldown for nothing. No state change; caller retries next tick. if (!_host.CanCastNow) return; + long now = NowMs; _state = PetState.Summoning; _activeDeviceId = deviceId; _activeSpiritId = 0; _preActionCharges = charges; - _actionIssuedAt = NowMs; - RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges})."); + _actionIssuedAt = now; + // Server starts the PetDevice cooldown on Use, whether the pet spawns or not. + _deviceCooldownUntil[deviceId] = now + DeviceUseCooldownMs; + RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}); essence cooldown {DeviceUseCooldownMs / 1000}s."); _host.UseFor(unchecked((uint)deviceId), "Pet", "summon a pet from the essence"); } @@ -455,9 +508,12 @@ internal sealed class PetManager foreach (var wo in _objectCache.GetLandscape()) { if (wo == null) continue; + // Corpses keep the pet's name briefly; don't treat them as a live summon. + if (wo.ObjectClass == AcObjectClass.Corpse) continue; string n = wo.Name; - if (!string.IsNullOrEmpty(n) && n.StartsWith(prefix, StringComparison.Ordinal)) - return true; + if (string.IsNullOrEmpty(n) || !n.StartsWith(prefix, StringComparison.Ordinal)) continue; + if (n.Contains("Corpse", StringComparison.OrdinalIgnoreCase)) continue; + return true; } return false; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponElementTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponElementTracker.cs index 8328df7..9ba1d91 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponElementTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponElementTracker.cs @@ -74,12 +74,14 @@ internal sealed class WeaponElementTracker if (id == 0 || IsIdentified(id)) continue; int n = _requests.TryGetValue(id, out int c) ? c : 0; if (n >= MaxRequestsPerItem) continue; + bool taken = false; + try { taken = _host.RequestId(unchecked((uint)id)); } catch { } + _lastRequestAt = now; // paces a retry as it paces a request + if (!taken) return 0; // the engine refused (a death or a portal): not counted, asked again after the gap _requests[id] = n + 1; _inFlightId = id; _inFlightAt = now; - _lastRequestAt = now; RequestsSent++; - try { _host.RequestId(unchecked((uint)id)); } catch { } return id; } return 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WieldRequirements.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WieldRequirements.cs index 8ca77c6..ed6a67c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WieldRequirements.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WieldRequirements.cs @@ -66,7 +66,7 @@ internal static class WieldRequirements private static AcSkillType? SkillOf(uint stype) { if (stype == 0) return null; - foreach (AcSkillType k in Enum.GetValues(typeof(AcSkillType))) + foreach (AcSkillType k in Enum.GetValues()) if (CharacterSkills.AcSkillTypeToSTypeSkill(k) == stype) return k; return null; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs index 578e4b3..beddca4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs @@ -406,6 +406,7 @@ internal static unsafe class CombatHookInterface _table = null; if (t != null) NativeMemory.Free(t); CombatHook.Reset(); + CombatHook.LastUseDone = null; // the lambda captured the host: don't keep a shut-down instance's host alive } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 1faf2ed..3b424b8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -48,6 +48,8 @@ public sealed partial class RynthAiPlugin private int _corpseIdAcceptedThisTick; private long _corpseIdBudgetAt; // when the budget last started over (a scan tick, or CorpseIdRefusedRetryMs without one) private const long CorpseIdReaskMs = 3000; // no appraisal data this long after an accepted request: ask once more + private const int CorpseIdMaxReasks = 3; // ...at most this many times per corpse (each accepted ask raises the client's busy count and holds opens) + private readonly Dictionary _corpseIdAskCount = new(); // accepted requests per corpse, the first included private int _busyCount; private long _busyCountLastIncrementAt; private long _busyCountBecamePositiveAt; // when count first went 0→positive @@ -399,6 +401,7 @@ public sealed partial class RynthAiPlugin _corpseIdRequested.Clear(); _corpseIdAskedAt.Clear(); _corpseIdRefusedAt.Clear(); + _corpseIdAskCount.Clear(); } if (_corpseSkipLogged.Count > 200) _corpseSkipLogged.Clear(); @@ -1017,8 +1020,11 @@ public sealed partial class RynthAiPlugin /// requests, so a refused or dropped one is asked again. A refused one is retried every /// CorpseIdRefusedRetryMs; an accepted one with no data is asked again every CorpseIdReaskMs, and only for /// the corpse the bot is targeting or has open (any other corpse in range gets one accepted request, not a - /// stream). At most CorpseIdPerTick requests are accepted per scan tick, so a refusal window ending with - /// many uncached corpses in range does not burst. No give-up cap. + /// stream), at most CorpseIdMaxReasks times, and only while the loot mode needs the killer name (My Kills + /// Only, Fellowship Kills). All Corpses still gets the one first request (the radar colours own kills from + /// it) but never a stream of them; Recover My Corpse keeps its own 5 s ask (RequestOwnCorpseId). At most + /// CorpseIdPerTick requests are accepted per scan tick, so a refusal window ending with many uncached + /// corpses in range does not burst. /// private void TryRequestCorpseId(WorldObject corpse, string longDesc) { @@ -1026,14 +1032,17 @@ public sealed partial class RynthAiPlugin long idNow = ActionPacer.NowMs(); if (idNow - _corpseIdBudgetAt >= CorpseIdRefusedRetryMs) { _corpseIdAcceptedThisTick = 0; _corpseIdBudgetAt = idNow; } // evaluations outside a scan must not exhaust it for good bool candidate = corpse.Id == _targetCorpseId || (_openedContainerId != 0 && corpse.Id == _openedContainerId); + int asks = _corpseIdAskCount.TryGetValue(corpse.Id, out int askCount) ? askCount : 0; bool due = !_corpseIdRequested.Contains(corpse.Id) - || (candidate && _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs); + || (candidate && asks <= CorpseIdMaxReasks && CorpseNameNeeded() + && _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs); if (!due || _corpseIdAcceptedThisTick >= CorpseIdPerTick) return; if (_corpseIdRefusedAt.TryGetValue(corpse.Id, out long refusedAt) && idNow - refusedAt < CorpseIdRefusedRetryMs) return; if (Host.RequestId(unchecked((uint)corpse.Id))) { _corpseIdRequested.Add(corpse.Id); _corpseIdAskedAt[corpse.Id] = idNow; + _corpseIdAskCount[corpse.Id] = asks + 1; _corpseIdRefusedAt.Remove(corpse.Id); _corpseIdAcceptedThisTick++; } @@ -1043,6 +1052,9 @@ public sealed partial class RynthAiPlugin } } + /// The loot mode reads the killer name (My Kills Only, Fellowship Kills); All Corpses does not. + private bool CorpseNameNeeded() => (_dashboard?.Settings?.LootOwnership ?? 0) < 2; + private CorpseLootDecision EvaluateCorpseLootDecision(WorldObject? corpse) { var settings = _dashboard?.Settings; @@ -1915,6 +1927,10 @@ public sealed partial class RynthAiPlugin } private bool _pickupHeldLogged; + private long _pickupHoldTickAt; // CorpseNowMs of the previous held call; 0 = no hold running + + /// A gap between two held calls longer than this was not one continuous hold (the corpse clock is not paid back for it). + internal const long PickupHoldMaxGapMs = 500; /// /// True while the server owes an answer to a cast or use (ActionPacer): ACE refuses a pickup @@ -1928,6 +1944,7 @@ public sealed partial class RynthAiPlugin if (!ActionPacer.Outstanding(Host, out var pending) || pending == null) { _pickupHeldLogged = false; + _pickupHoldTickAt = 0; return false; } if (!_pickupHeldLogged) @@ -1935,9 +1952,32 @@ public sealed partial class RynthAiPlugin _pickupHeldLogged = true; LootDiag($"[RynthAi] Corpse loot: pickup waits - the server still owes an answer to {ActionPacer.Describe(pending.Kind, pending.Label)} ({pending.Who})."); } + PauseCorpseClockWhileHeld(); return true; } + /// + /// The corpse's timeout clock does not run while a pickup is held for the server's answer to a + /// cast or use, as it does not for the buff / salvage-panel holds (FreezeCorpseTimeout). The hold + /// is bounded by the pacer: an action unanswered past its limit (ActionPacer.CastMaxMs for a + /// cast) stops being outstanding. FreezeCorpseTimeout itself cannot be used here: the + /// open-container branch of TickCorpseOpening resets its frozen age every tick, so this adds the + /// time since the previous held call to the claim time instead. Without it a corpse held for + /// 12 s timed out the moment the cast was answered, and AbandonCurrentCorpse gave the opened + /// corpse the 30-minute completed mark, which skipped its loot. + /// + private void PauseCorpseClockWhileHeld() + { + long now = CorpseNowMs; + long last = _pickupHoldTickAt; + _pickupHoldTickAt = now; + if (last == 0 || _targetCorpseId == 0 || _corpseTargetSince == 0) + return; + long gap = now - last; + if (gap > 0 && gap <= PickupHoldMaxGapMs) + _corpseTargetSince += gap; + } + private void TickPendingCorpsePickup(LegacyUiSettings settings) { if (_objectCache == null || _openedContainerId == 0 || _currentLootItemId == 0) @@ -3396,6 +3436,7 @@ public sealed partial class RynthAiPlugin _corpseIdRequested.Remove(sid); _corpseIdAskedAt.Remove(sid); _corpseIdRefusedAt.Remove(sid); + _corpseIdAskCount.Remove(sid); _corpseSkipLogged.Remove(sid); _corpseWaitingSince.Remove(sid); @@ -3552,16 +3593,42 @@ public sealed partial class RynthAiPlugin /// A held-back close is sent anyway when no other corpse has been opened this long. internal const long DeferredCloseMaxMs = 3000; - /// Another corpse to loot is in range (the finished one is already marked completed). + /// + /// Another corpse to loot is in range (the finished one is already marked completed) and the + /// looter can go to it now: . A corpse that combat, a full pack, a + /// refusing server or a buff / mana drain hold keeps from being claimed would leave the finished + /// one open for nothing (metas and Lua read the open container meanwhile). + /// private bool OtherCorpseToLoot(int doneCorpseId) { var settings = _dashboard?.Settings; if (settings == null || _objectCache == null) return false; double maxMeters = GetCorpseApproachRangeMaxMeters(settings); if (maxMeters <= 0.25) return false; + if (!CanClaimNextCorpse(settings, maxMeters)) return false; return TryFindNearestCorpse(maxMeters, out WorldObject? next, out _) && next != null && next.Id != doneCorpseId; } + /// + /// The holds TickCorpseOpening applies before it claims or opens a corpse, as one answer for + /// "would the next corpse be claimed now": looting blocked by a full pack (your own corpse + /// excepted), the use-refusal back-off, buffing, a mana drain, and combat's priority (the open + /// container no longer shields a claim once the finished corpse is released). What the activity + /// arbiter hands out later is not known here; the deferred close is sent after DeferredCloseMaxMs, + /// or as soon as one of these holds starts (TickDeferredClose). Distance is no reason to close + /// early: a far corpse is used at once and the server walks the character to it. + /// + private bool CanClaimNextCorpse(LegacyUiSettings settings, double maxMeters) + { + if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters)) return false; + if (_useRefusals.HoldsOpens(CorpseNowMs)) return false; + if (string.Equals(settings.BotAction, "Buffing", StringComparison.OrdinalIgnoreCase)) return false; + if (_manaStoneManager?.HoldsLootForDrain() == true) return false; + if (settings.EnableCombat && _combatManager?.HasTargets == true && !settings.BoostLootPriority && !_lootStarveTurn) + return false; + return true; + } + /// Holds the close of a finished corpse back. Only when the engine can close it later and /// reports which container the client has open (so the hold can see the server close it). private bool DeferClose(int corpseId) @@ -3591,10 +3658,13 @@ public sealed partial class RynthAiPlugin return; } bool stopped = !settings.IsMacroRunning || !settings.EnableLooting || settings.BoostNavPriority; - if (!stopped && CorpseNowMs - _closeDeferredAt < DeferredCloseMaxMs) + // A hold that began after the close was deferred (a fight, a full pack) ends the wait too. + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); + bool blocked = !stopped && maxMeters > 0.25 && !CanClaimNextCorpse(settings, maxMeters); + if (!stopped && !blocked && CorpseNowMs - _closeDeferredAt < DeferredCloseMaxMs) return; _closeDeferredFor = 0; - CloseCorpseContainer(id, stopped ? "completed; looting stopped" : "completed; no other corpse opened"); + CloseCorpseContainer(id, stopped ? "completed; looting stopped" : blocked ? "completed; the next corpse can't be claimed now" : "completed; no other corpse opened"); } private void CloseCorpseContainer(int corpseId, string why) diff --git a/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs index 410e01e..9d9165a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs @@ -44,6 +44,7 @@ internal static unsafe class HubInterface t->SessionStats = &SessionStats; t->SessionReset = &SessionReset; t->SessionStatsMore = &SessionStatsMore; + t->VaultedDungeonsEnabled = &VaultedDungeonsEnabled; t->Version = RynthAiHubApiV1.InterfaceVersion; _table = t; } @@ -250,6 +251,14 @@ internal static unsafe class HubInterface catch { return 0; } } + /// RynthAi's Vaulted Dungeons setting: RynthILT's keeper runs only while it is on (off by default). + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int VaultedDungeonsEnabled() + { + try { return Plugin?.VaultedDungeonsEnabledForIlt == true ? 1 : 0; } + catch { return 0; } + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void SessionReset() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/CombatHudTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/CombatHudTracker.cs index 05820bd..f795db9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/CombatHudTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/CombatHudTracker.cs @@ -204,9 +204,10 @@ internal sealed class CombatHudTracker if (_appraiseAttempts >= AppraiseMaxAttempts || !_host.HasRequestId) return; if (_lastAppraiseAt != 0 && now - _lastAppraiseAt < AppraiseRetryMs) return; + // Counted only when the engine took it (it refuses around a death or a portal). + if (!_host.RequestId(uid)) return; _appraiseAttempts++; _lastAppraiseAt = now; - _host.RequestId(uid); } /// Polls the pet's health, then hands the server's health stream back to the fight target. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHeader.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHeader.cs new file mode 100644 index 0000000..cb85bd7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHeader.cs @@ -0,0 +1,27 @@ +// MiniRemoteHeader.cs - the Mini Remote's [V/H] [Options] [gear] header row: what a click does, and the +// button widths. Pure, so the host tests check both offline. +// +// Options opens RynthAi Settings (Advanced Settings) through RynthCore's "/rc ui open Settings" when the +// host has a chat parser. The Mini Remote's own popup (sections, layout, slot size) opens from the small +// gear button next to it, from a right-click on Options, and from a left-click on Options when there is +// no chat parser to run the command. +namespace RynthCore.Plugin.RynthAi.Huds; + +internal static class MiniRemoteHeader +{ + /// [V/H]: one letter, so it doesn't need the width of the word buttons. + public const float LayoutButtonWidth = 56f; + public const float OptionsButtonWidth = 80f; + /// The gear button right of Options: square-ish and small. + public const float GearButtonWidth = 28f; + + /// + /// The engine command a left-click on Options runs, or null when the host can't run chat commands + /// (then the click opens the Mini Remote popup instead). + /// + public static string? OptionsLeftClickCommand(bool hasChatParser) => hasChatParser ? MovedTabs.Settings : null; + + /// Total width of the header row for the given spacing between its three buttons. + public static float RowWidth(float itemSpacing) => + LayoutButtonWidth + OptionsButtonWidth + GearButtonWidth + 2f * itemSpacing; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs index c4658cb..0bc27e4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs @@ -12,7 +12,9 @@ // Quest Timers and Fellowship, Skills, Inventory, Item Count, Inventory HUDs: windows every server // has), then "Server: ", i.e. the installed server plugins' windows for the world you're on, // which RynthCore sends (ServerMenuModel), or a link to RynthCore's Options > Diagnostics (where a -// server is forced) when none matches. The Options button holds the Mini Remote's own settings. +// server is forced) when none matches. The Options button opens RynthAi Settings (/rc ui open +// Settings); the small gear next to it, or a right-click on Options, holds the Mini Remote's own +// settings (sections, layout, slot size), and so does a click on Options when there is no chat parser. // The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal). // // Remote sections (each can be hidden from the Options menu): @@ -59,8 +61,7 @@ internal sealed class MiniRemoteHud /// Pixels per Ctrl+wheel notch over the slot grid. private const float SlotSizeStep = 2f; /// Narrowest horizontal-layout column (fits the stat lines and the translate row). - private const float MinColumnWidth = 190f; - private const float HeaderButtonWidth = 80f; + internal const float MinColumnWidth = 190f; private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f); private static readonly Vector4 ColReady = new(0.40f, 0.95f, 0.45f, 1f); @@ -82,6 +83,8 @@ internal sealed class MiniRemoteHud private bool _onRemoteTab = true; // The Options button was clicked this frame (the popup opens at window level). private bool _openOptions; + // The header's Options button was right-clicked this frame: its popup opens, not the remote's menu. + private bool _headerRightClick; /// One tab after Remote: a universal one (drawn here) or RynthILT's. private readonly record struct TabEntry(string Id, string Label, Vector2 Size, bool Ilt); @@ -125,7 +128,7 @@ internal sealed class MiniRemoteHud // Right-click on the remote opens the Character / server menu, unless a slot's own menu is // open (the ILT tabs have their own right-click menus). - if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) + if (_onRemoteTab && _slotMenuIndex < 0 && !_headerRightClick && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(MenuPopup); RenderOptions(s, embedded: false); RenderMenu(s); @@ -152,7 +155,7 @@ internal sealed class MiniRemoteHud // Without tabs (RynthCore's sections show them instead) the remote alone. float width = RenderBody(s, _hud.Remote(), allowTabs: tabs && !InDrawer); - if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) + if (_onRemoteTab && _slotMenuIndex < 0 && !_headerRightClick && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(MenuPopup); RenderOptions(s, embedded: true); RenderMenu(s); @@ -179,6 +182,7 @@ internal sealed class MiniRemoteHud private float RenderBody(HudState s, MiniRemoteController? remote, bool allowTabs) { _onRemoteTab = true; + _headerRightClick = false; _tabs.Clear(); if (allowTabs && remote != null) { @@ -311,17 +315,54 @@ internal sealed class MiniRemoteHud // ── Layout ────────────────────────────────────────────────────────────── - /// [V/H] and [Options] buttons. Fixed widths so the auto-resizing window can't grow from them. + /// + /// [V/H], [Options] and a small gear. Fixed widths (MiniRemoteHeader, sized to fit MinColumnWidth) + /// so the auto-resizing window can't grow from them. + /// private void RenderHeaderRow(HudState s) { - if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(HeaderButtonWidth, 0))) + if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(MiniRemoteHeader.LayoutButtonWidth, 0))) s.MiniRemoteHorizontal = !s.MiniRemoteHorizontal; if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns."); ImGui.SameLine(); - // Opened by RenderOptions: this row sits inside the Remote tab, whose ID the popup must not get. - if (ImGui.Button("Options##mropts", new Vector2(HeaderButtonWidth, 0))) _openOptions = true; - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Mini Remote settings: sections, layout, slot size.\nRight-click the remote for the Character and server windows."); + // Left-click: RynthAi Settings (the engine's "Settings" panel); without a chat parser, and on a + // right-click, the Mini Remote popup (RenderOptions: this row sits inside the Remote tab, whose + // ID the popup must not get, so the popup opens at window level through _openOptions). + if (ImGui.Button("Options##mropts", new Vector2(MiniRemoteHeader.OptionsButtonWidth, 0))) + { + string? command = MiniRemoteHeader.OptionsLeftClickCommand(_hud.Host.HasInvokeChatParser); + if (command != null) _hud.RunEngineCommand(command); + else _openOptions = true; + } + if (ImGui.IsItemHovered()) + { + _headerRightClick = true; // the remote's right-click menu stays closed over this button + if (ImGui.IsMouseClicked(ImGuiMouseButton.Right)) _openOptions = true; + SafeImGui.SetTooltip(_hud.Host.HasInvokeChatParser + ? "Open RynthAi Settings (Advanced Settings).\nRight-click: Mini Remote sections, layout, slot size." + : "Mini Remote settings: sections, layout, slot size."); + } + ImGui.SameLine(); + if (ImGui.Button("##mrgear", new Vector2(MiniRemoteHeader.GearButtonWidth, 0))) _openOptions = true; + DrawGear(ImGui.GetItemRectMin(), ImGui.GetItemRectMax()); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Mini Remote sections, layout, slot size"); + } + + /// A small gear (ring and eight teeth) centred in the button's rectangle, in the text colour. + private static void DrawGear(Vector2 min, Vector2 max) + { + var draw = ImGui.GetWindowDrawList(); + uint col = ImGui.GetColorU32(ImGuiCol.Text); + Vector2 c = (min + max) * 0.5f; + float r = MathF.Min(max.X - min.X, max.Y - min.Y) * 0.22f; + draw.AddCircle(c, r, col, 12, 1.6f); + for (int i = 0; i < 8; i++) + { + float a = i * MathF.PI / 4f; + var dir = new Vector2(MathF.Cos(a), MathF.Sin(a)); + draw.AddLine(c + dir * (r + 0.5f), c + dir * (r + 3f), col, 2f); + } } private void RenderVertical(HudState s, MiniRemoteController? remote) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs index aac6f91..c4cde5b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs @@ -21,6 +21,12 @@ internal static class MovedTabs /// RynthCore Options > Diagnostics (the server picker; RynthCore 2026.10.5.54+). public const string Diagnostics = "/rc diagnostics"; + /// + /// RynthAi Settings (Advanced Settings): RynthCore's "Settings" panel (SettingsFace.Title), opened + /// by name through "/rc ui open <Panel>" (RynthCoreChatCommands, the generic panel verb). + /// + public const string Settings = "/rc ui open Settings"; + /// /// The chat command that opens where tab lives now, or null when it is /// still a Mini Remote tab (or not a tab at all). Case and padding don't matter. @@ -36,6 +42,7 @@ internal static class MovedTabs { OracleCharacter => "RynthOracle's Character tab", Diagnostics => "RynthCore Options > Diagnostics", + Settings => "RynthAi Settings (Advanced Settings)", _ => command, }; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs index 827b1ca..efc2a13 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs @@ -71,6 +71,10 @@ internal static class SectionsManifest ["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."), ["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."), ["games"] = ("games", "Games", 100, "ILT games (RynthILT)."), + // Listed only while RynthILT shows the tab: the Vaulted Dungeons master switch (RynthAi + // Settings > Navigation) is on, on an ILT world. + ["vaulted"] = ("nav", "Vaulted Dungeons", 220, + "Keep the character in one Vaulted Dungeon (RynthILT; Settings > Navigation > Vaulted Dungeons)."), }; /// The surface name of a tab's view ("section:gear"). diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 72df8d4..5964149 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -15,6 +15,30 @@ internal sealed class LegacyAdvancedSettingsUi // Server Features list being edited (committed on Enter / focus loss); null = show the saved list. private static readonly string[] AttackHeights = { "Low", "Medium", "High" }; + + /// + /// The environment-impact throttle's shared numbers (one set for missiles and magic), drawn + /// under each response combo. keeps the two copies' ImGui ids apart. + /// + private void DrawEnvironmentThrottleKnobs(string id) + { + ImGui.Indent(); + ImGui.SetNextItemWidth(120); + ImGui.SliderInt($"Hits to trip##envlimit{id}", ref _settings.EnvironmentImpactLimit, 1, 10); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Environment hits on one target, within the window, before combat reacts.\nShared by missiles and magic."); + ImGui.SetNextItemWidth(120); + ImGui.SliderInt($"Window (s)##envwin{id}", ref _settings.EnvironmentImpactWindowSec, 5, 120); + ImGui.SetNextItemWidth(120); + ImGui.SliderInt($"Move closer by (m)##envstep{id}", ref _settings.EnvironmentApproachMeters, 1, 30); + ImGui.SetNextItemWidth(120); + ImGui.SliderInt($"Closest (m)##envmin{id}", ref _settings.EnvironmentMinDistance, 1, 30); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Never moves nearer than this. Already this close, a new target is picked instead."); + ImGui.SetNextItemWidth(120); + ImGui.SliderInt($"Skip target (s)##envskip{id}", ref _settings.EnvironmentSkipSec, 5, 300); + ImGui.Unindent(); + } private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" }; private const string NavResumeNearestTip = "On: starting the macro, loading a Circular or Linear route, and carrying on after a fight, loot, buff or door\n" + @@ -436,9 +460,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Spacing(); ImGui.Text("Give Queue"); ImGui.SetNextItemWidth(150); - ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 50, 2000); + ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 0, 2000); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Minimum delay between each item sent by /ra givea commands.\nLower = faster but may drop items if the server can't keep up."); + ImGui.SetTooltip("Minimum gap between two gives sent by /ra givea commands.\n0 = send the next give the moment the server answers the last (fastest).\nThe queue always waits for the server's answer first."); break; case "Recharge": @@ -532,6 +556,45 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SetNextItemWidth(120); ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, AttackHeights, AttackHeights.Length); + ImGui.Spacing(); + ImGui.Text("Variable Power (monster rules)"); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("A monster rule's Power column picks per monster: Default (these settings),\n" + + "High (100%), Reckless (80%, needs Recklessness trained), Variable (a new\n" + + "random power each attack in this range), or Reckless + Variable (random,\n" + + "kept inside the Recklessness band 20-80%)."); + ImGui.SetNextItemWidth(150); + ImGui.SliderInt("Variable Min %", ref _settings.VariablePowerMin, 0, 100); + ImGui.SetNextItemWidth(150); + ImGui.SliderInt("Variable Max %", ref _settings.VariablePowerMax, 0, 100); + + ImGui.Spacing(); + ImGui.Text("Missiles Hitting the Environment"); + ImGui.SetNextItemWidth(220); + ImGui.Combo("Missile Response", ref _settings.MissileEnvironmentResponse, + EnvironmentImpactPlanner.ResponseNames, EnvironmentImpactPlanner.ResponseNames.Length); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("When arrows or bolts keep hitting walls or objects instead of the target\n" + + "(\"Your missile attack hit the environment.\"), stop shooting and:\n" + + " Move closer - run toward the target for a clearer shot\n" + + " New target - skip this one for a while and fight another\n" + + " Move closer, then new target - one approach, then switch\n" + + "The only monster in reach is never skipped."); + DrawEnvironmentThrottleKnobs("missile"); + + ImGui.Spacing(); + ImGui.Text("Pull Away (Kite)"); + ImGui.SetNextItemWidth(150); + ImGui.SliderInt("Pull Distance (m)", ref _settings.KitePullMeters, 3, 100); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("When a monster rule's Kite is Pull away (or Default follows the\n" + + "DEFAULT row set to Pull away), tag the mob then run until it has\n" + + "been dragged this many metres from where it stood, then kill it.\n" + + "Set per mob on the Monsters / Damage panels."); + ImGui.Checkbox("Tag Before Fleeing", ref _settings.KiteTagFirst); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Land a hit before running so aggro sticks. Off = flee as soon as locked."); + ImGui.Spacing(); ImGui.Text("Weapon Swaps"); ImGui.SetNextItemWidth(150); @@ -600,7 +663,8 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SetTooltip( "At or under Emergency Heal At with heals failing: break the\n" + "stuck cast with a jump and heal again; if that fails too,\n" + - "recall to the lifestone."); + "recall to the lifestone. Off by default; only a character that\n" + + "can heal (a heal spell, kit or potion) is ever recalled."); ImGui.SetNextItemWidth(180); ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000); @@ -629,6 +693,20 @@ internal sealed class LegacyAdvancedSettingsUi "The character turns to face the target first. 0 = no walls."); ImGui.InputInt("Min Wall Targets", ref _settings.MinWallTargets); + ImGui.Spacing(); + ImGui.Text("Spells Hitting the Environment"); + ImGui.SetNextItemWidth(220); + ImGui.Combo("Magic Response", ref _settings.MagicEnvironmentResponse, + EnvironmentImpactPlanner.ResponseNames, EnvironmentImpactPlanner.ResponseNames.Length); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("When bolts, streaks, arcs or blasts keep stopping short of the target\n" + + "(a wall, a pillar, the ceiling) with no hit or resist, stop casting and:\n" + + " Move closer - run toward the target for a clearer line\n" + + " New target - skip this one for a while and fight another\n" + + " Move closer, then new target - one approach, then switch\n" + + "Rings and walls aren't judged. The only monster in reach is never skipped."); + DrawEnvironmentThrottleKnobs("magic"); + ImGui.Spacing(); ImGui.Separator(); ImGui.Text("Spell Difficulty (Min Buffed Skill)"); @@ -663,6 +741,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SetTooltip("Drop a locked target only past this distance (hysteresis).\n0 or <= Monster Range = auto (Monster Range + 3)."); ImGui.SetNextItemWidth(120); ImGui.InputInt("Ring Range", ref _settings.RingRange); + ImGui.Checkbox("Evade Handler Ring", ref _settings.HandlerRingEvade); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Empyrean Handler: when it channels its lethal ring and you are within 12 yards (or Ring Range if larger),\nback-jump away and re-engage. Acts only while the macro is running with combat on."); ImGui.SetNextItemWidth(120); ImGui.InputInt("Approach Range", ref _settings.ApproachRange); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index e3ff1bf..662b0f3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -69,8 +69,9 @@ internal sealed partial class LegacyDashboardRenderer // 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 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"); + // internal + settable only so the host tests can point LoadSettings at a scratch folder. + internal static string ProfilesBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "SettingsProfiles"); + internal static 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); @@ -386,27 +387,43 @@ internal sealed partial class LegacyDashboardRenderer // new character kept the previous character's weapons and consumables, // and autosave then wrote them into its Default.json. bool freshProfile = !File.Exists(_settingsFilePath); + bool holdUnreadable = false; if (freshProfile) { CopySettings(new LegacyUiSettings(), _settings); _lastSavedJson = string.Empty; } + else if (TryReadProfile(_settingsFilePath, out LegacyUiSettings? loaded, out string loadedJson, out string readError)) + { + CopySettings(loaded!, _settings); + _lastSavedJson = loadedJson; + } + else if (TryReadProfile(_settingsFilePath + BackupSuffix, out LegacyUiSettings? fromBak, out string bakJson, out _)) + { + // The profile didn't read (cut off by a client that died mid-save, say): the copy + // kept by the last good save is used. The broken file is set aside and the backup put + // back as the profile, so the next save doesn't turn the broken file into the new .bak. + CopySettings(fromBak!, _settings); + _lastSavedJson = bakJson; + KeepUnreadableProfile(_settingsFilePath); + try { File.Copy(_settingsFilePath + BackupSuffix, _settingsFilePath, overwrite: true); } + catch (Exception ex) { _host.Log($"[RynthAi] Settings: putting the backup back as {_settingsFilePath} failed: {ex.Message}"); } + _host.Log($"[RynthAi] Settings: {_settingsFilePath} didn't read ({readError}); loaded the backup instead."); + _host.WriteToChat($"[RynthAi] Your settings file didn't read ({readError}); restored the backup copy.", 1); + } else { - try - { - string json = File.ReadAllText(_settingsFilePath); - var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); - if (loaded != null) - { - CopySettings(loaded, _settings); - _lastSavedJson = json; - } - } - catch { } + // Neither reads. Before, the defaults kept here were autosaved over the profile at once, + // so one bad read reset the character for good. Now a copy is set aside and nothing is + // written until a setting is actually changed (the baseline is re-taken below). + CopySettings(new LegacyUiSettings(), _settings); + KeepUnreadableProfile(_settingsFilePath); + holdUnreadable = true; + _host.Log($"[RynthAi] Settings: {_settingsFilePath} didn't read ({readError}) and there's no good backup; using defaults without saving over it."); + _host.WriteToChat($"[RynthAi] Your settings file didn't read ({readError}). A copy was kept next to it (.unreadable); defaults are in use until you change something.", 1); } _packSetup = freshProfile ? PackSetup.FillNew - : _settings.ProfileItemsChecked ? PackSetup.None : PackSetup.CheckExisting; + : holdUnreadable || _settings.ProfileItemsChecked ? PackSetup.None : PackSetup.CheckExisting; _packSetupStart = 0; _packLastCount = -1; @@ -461,6 +478,15 @@ internal sealed partial class LegacyDashboardRenderer // combat system has no fallback weapon/damage selection for unmatched mobs. _settings.EnsureDefaultRule(); SetupMonsterWatcher(); + + if (holdUnreadable) + { + // The defaults now in memory (and the monster rules just loaded) are not a change: take + // them as the saved state, so the autosave leaves the unreadable file alone until the + // player changes something. + try { CaptureTransientUiState(); _lastSavedJson = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings); } + catch { _lastSavedJson = string.Empty; } + } } /// @@ -505,9 +531,58 @@ internal sealed partial class LegacyDashboardRenderer DataWriteGuard.TrySave("the settings profile", path, () => { Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllText(path, json); + // Written beside it and swapped in, the previous file kept as .bak: File.WriteAllText + // empties the profile first, so a client closed or killed mid-save (relaunching for a + // DXVK change, the launcher's stuck-client kill) left a cut-off file that then loaded + // as defaults. + string tmp = path + "." + Environment.ProcessId + ".tmp"; + try + { + File.WriteAllText(tmp, json); + if (File.Exists(path)) File.Replace(tmp, path, path + BackupSuffix, ignoreMetadataErrors: true); + else File.Move(tmp, path); + } + finally + { + try { if (File.Exists(tmp)) File.Delete(tmp); } catch { } + } }, out reason, callerShows); + /// The last good profile kept by each save (profile path + this). + internal const string BackupSuffix = ".bak"; + + /// Reads and parses a settings profile; false (with the reason) when it's missing or doesn't parse. + private static bool TryReadProfile(string path, out LegacyUiSettings? settings, out string json, out string error) + { + settings = null; json = string.Empty; error = ""; + try + { + if (!File.Exists(path)) { error = "missing"; return false; } + json = File.ReadAllText(path); + if (string.IsNullOrWhiteSpace(json)) { error = "the file is empty"; return false; } + settings = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); + if (settings == null) { error = "the file holds no settings"; return false; } + return true; + } + catch (Exception ex) + { + error = ex.GetType().Name + ": " + ex.Message; + return false; + } + } + + /// Copies a profile that didn't read to "<name>.unreadable-<time>" so its contents can be recovered. + private void KeepUnreadableProfile(string path) + { + try + { + if (!File.Exists(path)) return; + string copy = path + ".unreadable-" + DateTime.Now.ToString("yyyyMMdd-HHmmss"); + File.Copy(path, copy, overwrite: false); + } + catch (Exception ex) { _host.Log($"[RynthAi] Settings: keeping a copy of {path} failed: {ex.Message}"); } + } + private static bool WriteSettingsFile(string path, string json) => WriteSettingsFile(path, json, out _); /// After a failed autosave, when CheckAndSave may try again (not every tick). @@ -983,12 +1058,46 @@ internal sealed partial class LegacyDashboardRenderer incoming.Insert(0, existingDefault ?? new MonsterRule { Name = "Default" }); } + // An engine without the Power column (before 2026-10-12) sends no AttackPower, which + // would reset every rule to Default: keep each rule's own (same name and expression). + if (json.IndexOf("\"AttackPower\"", StringComparison.OrdinalIgnoreCase) < 0) + CarryAttackPower(_settings.MonsterRules, incoming); + // Same for kite (2026-10-16): an older Monsters panel omits Kite and would wipe PullAway. + if (json.IndexOf("\"Kite\"", StringComparison.OrdinalIgnoreCase) < 0) + CarryKite(_settings.MonsterRules, incoming); + _settings.MonsterRules = incoming; SaveMonstersFile(); } catch { } } + /// Copies AttackPower from onto the matching rules of + /// (same Name and MatchExpression, case-insensitive). + internal static void CarryAttackPower(List current, List incoming) + { + foreach (var r in incoming) + { + var old = current.FirstOrDefault(o => + string.Equals(o.Name, r.Name, StringComparison.OrdinalIgnoreCase) + && string.Equals(o.MatchExpression ?? "", r.MatchExpression ?? "", StringComparison.OrdinalIgnoreCase)); + if (old != null) r.AttackPower = old.AttackPower; + } + } + + /// Copies Kite from onto the matching rules of + /// (same Name and MatchExpression, case-insensitive). + internal static void CarryKite(List current, List incoming) + { + foreach (var r in incoming) + { + var old = current.FirstOrDefault(o => + string.Equals(o.Name, r.Name, StringComparison.OrdinalIgnoreCase) + && string.Equals(o.MatchExpression ?? "", r.MatchExpression ?? "", StringComparison.OrdinalIgnoreCase)); + if (old != null) r.Kite = old.Kite; + } + } + // ── Settings bridge (engine-side Avalonia SettingsPanel) ───────────────── public string BuildSettingsJson() @@ -1070,10 +1179,21 @@ internal sealed partial class LegacyDashboardRenderer UseNativeAttack = s.UseNativeAttack, SummonPets = s.SummonPets, PetMinMonsters = s.PetMinMonsters, - // Spell Combat + VariablePowerMin = s.VariablePowerMin, + VariablePowerMax = s.VariablePowerMax, + MissileEnvironmentResponse = s.MissileEnvironmentResponse, + MagicEnvironmentResponse = s.MagicEnvironmentResponse, + EnvironmentImpactLimit = s.EnvironmentImpactLimit, + EnvironmentImpactWindowSec = s.EnvironmentImpactWindowSec, + EnvironmentApproachMeters = s.EnvironmentApproachMeters, + EnvironmentMinDistance = s.EnvironmentMinDistance, + EnvironmentSkipSec = s.EnvironmentSkipSec, + KitePullMeters = s.KitePullMeters, + KiteTagFirst = s.KiteTagFirst, WeaponSwapSettleMs = s.WeaponSwapSettleMs, WeaponSwapMinHealthPct = s.WeaponSwapMinHealthPct, WeaponSwapMinGainPct = s.WeaponSwapMinGainPct, + // Spell Combat SpellCastIntervalMs = s.SpellCastIntervalMs, AttackSpellIntervalMs = s.AttackSpellIntervalMs, CastDispelSelf = s.CastDispelSelf, @@ -1101,6 +1221,7 @@ internal sealed partial class LegacyDashboardRenderer CorpseApproachRangeMin = s.CorpseApproachRangeMin, // Navigation BoostNavPriority = s.BoostNavPriority, + EnableVaultedDungeons = s.EnableVaultedDungeons, FollowNavMin = s.FollowNavMin, NavRingThickness = s.NavRingThickness, NavLineThickness = s.NavLineThickness, @@ -1110,6 +1231,8 @@ internal sealed partial class LegacyDashboardRenderer NavLabelMode = NavLabelModes.Clamp(s.NavLabelMode), NavGuideLine = s.NavGuideLine, NavResumeNearest = s.NavResumeNearest, + TrackBreadcrumbs = s.NavOverlay.TrackBreadcrumbs, + ShowRouteOverlay = s.NavOverlay.ShowRouteMarkers, OpenDoors = s.OpenDoors, OpenDoorRange = s.OpenDoorRange, OpenDoorsOnPathOnly = s.OpenDoorsOnPathOnly, @@ -1311,10 +1434,22 @@ internal sealed partial class LegacyDashboardRenderer s.UseNativeAttack = p.UseNativeAttack; s.SummonPets = p.SummonPets; s.PetMinMonsters = p.PetMinMonsters; - // Spell Combat + // Absent (an engine without these controls) = unchanged. + if (p.VariablePowerMin is int vpMin) s.VariablePowerMin = vpMin; + if (p.VariablePowerMax is int vpMax) s.VariablePowerMax = vpMax; + if (p.MissileEnvironmentResponse is int envMis) s.MissileEnvironmentResponse = envMis; + if (p.MagicEnvironmentResponse is int envMag) s.MagicEnvironmentResponse = envMag; + if (p.EnvironmentImpactLimit is int envLimit) s.EnvironmentImpactLimit = envLimit; + if (p.EnvironmentImpactWindowSec is int envWin) s.EnvironmentImpactWindowSec = envWin; + if (p.EnvironmentApproachMeters is int envStep) s.EnvironmentApproachMeters = envStep; + if (p.EnvironmentMinDistance is int envMinDist) s.EnvironmentMinDistance = envMinDist; + if (p.EnvironmentSkipSec is int envSkip) s.EnvironmentSkipSec = envSkip; + if (p.KitePullMeters is int kitePull) s.KitePullMeters = Math.Clamp(kitePull, 3, 100); + if (p.KiteTagFirst is bool kiteTag) s.KiteTagFirst = kiteTag; if (p.WeaponSwapSettleMs is int wsSettle) s.WeaponSwapSettleMs = Math.Clamp(wsSettle, 0, 3000); if (p.WeaponSwapMinHealthPct is int wsHealth) s.WeaponSwapMinHealthPct = Math.Clamp(wsHealth, 0, 100); if (p.WeaponSwapMinGainPct is int wsGain) s.WeaponSwapMinGainPct = Math.Clamp(wsGain, 0, 200); + // Spell Combat s.SpellCastIntervalMs = p.SpellCastIntervalMs; if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged s.CastDispelSelf = p.CastDispelSelf; @@ -1342,6 +1477,7 @@ internal sealed partial class LegacyDashboardRenderer s.CorpseApproachRangeMin = p.CorpseApproachRangeMin; // Navigation s.BoostNavPriority = p.BoostNavPriority; + if (p.EnableVaultedDungeons is bool vaulted) s.EnableVaultedDungeons = vaulted; // absent = unchanged s.FollowNavMin = p.FollowNavMin; s.NavRingThickness = p.NavRingThickness; s.NavLineThickness = p.NavLineThickness; @@ -1351,6 +1487,8 @@ internal sealed partial class LegacyDashboardRenderer if (p.NavLabelMode >= 0) s.NavLabelMode = NavLabelModes.Clamp(p.NavLabelMode); if (p.NavGuideLine is bool guideLine) s.NavGuideLine = guideLine; if (p.NavResumeNearest is bool resumeNearest) s.NavResumeNearest = resumeNearest; // absent = unchanged + if (p.TrackBreadcrumbs is bool crumbs) s.NavOverlay.TrackBreadcrumbs = crumbs; // absent = unchanged + if (p.ShowRouteOverlay is bool routeOverlay) s.NavOverlay.ShowRouteMarkers = routeOverlay; s.OpenDoors = p.OpenDoors; s.OpenDoorRange = p.OpenDoorRange; if (p.OpenDoorsOnPathOnly is bool doorsOnPath) s.OpenDoorsOnPathOnly = doorsOnPath; // absent = unchanged @@ -1640,18 +1778,30 @@ internal sealed partial class LegacyDashboardRenderer // Load from new profile file if it exists if (File.Exists(_settingsFilePath)) { - try + if (TryReadProfile(_settingsFilePath, out LegacyUiSettings? loaded, out string json, out string readError)) { - string json = File.ReadAllText(_settingsFilePath); - var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); - if (loaded != null) + CopySettings(loaded!, _settings); + _settings.SelectedProfile = newProfile; + _lastSavedJson = json; + } + else + { + // Same as at login: the profile that didn't read is set aside (and the backup used + // when there is one) instead of being overwritten by the profile we just left. + KeepUnreadableProfile(_settingsFilePath); + if (TryReadProfile(_settingsFilePath + BackupSuffix, out LegacyUiSettings? fromBak, out string bakJson, out _)) { - CopySettings(loaded, _settings); + CopySettings(fromBak!, _settings); _settings.SelectedProfile = newProfile; - _lastSavedJson = json; + _lastSavedJson = bakJson; + try { File.Copy(_settingsFilePath + BackupSuffix, _settingsFilePath, overwrite: true); } catch { } + _host.WriteToChat($"[RynthAi] Profile '{newProfile}' didn't read ({readError}); restored its backup copy.", 1); + } + else + { + _host.WriteToChat($"[RynthAi] Profile '{newProfile}' didn't read ({readError}); a copy was kept next to it (.unreadable). Your current settings are in use under that name.", 1); } } - catch { } } else { @@ -1816,6 +1966,7 @@ internal sealed partial class LegacyDashboardRenderer dst.TargetSelection = Math.Clamp(tmp.TargetSelection, 0, 3); dst.TargetLock = tmp.TargetLock; dst.RingRange = tmp.RingRange; + dst.HandlerRingEvade = tmp.HandlerRingEvade; // a profile saved before this setting loads it as on dst.ApproachRange = tmp.ApproachRange; dst.MinRingTargets = tmp.MinRingTargets; dst.BlastRange = tmp.BlastRange; @@ -1838,6 +1989,7 @@ internal sealed partial class LegacyDashboardRenderer dst.CorpseApproachRangeMax = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMax, 10.0); dst.CorpseApproachRangeMin = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMin, 2.0); dst.BoostNavPriority = tmp.BoostNavPriority; + dst.EnableVaultedDungeons = tmp.EnableVaultedDungeons; dst.BoostLootPriority = tmp.BoostLootPriority; dst.OpenDoors = tmp.OpenDoors; dst.OpenDoorRange = tmp.OpenDoorRange; @@ -1867,6 +2019,17 @@ internal sealed partial class LegacyDashboardRenderer dst.MeleeAttackPower = tmp.MeleeAttackPower; dst.MissileAttackPower = tmp.MissileAttackPower; dst.UseRecklessness = tmp.UseRecklessness; + dst.VariablePowerMin = tmp.VariablePowerMin; + dst.VariablePowerMax = tmp.VariablePowerMax; + dst.MissileEnvironmentResponse = tmp.MissileEnvironmentResponse; + dst.MagicEnvironmentResponse = tmp.MagicEnvironmentResponse; + dst.EnvironmentImpactLimit = tmp.EnvironmentImpactLimit; + dst.EnvironmentImpactWindowSec = tmp.EnvironmentImpactWindowSec; + dst.EnvironmentApproachMeters = tmp.EnvironmentApproachMeters; + dst.EnvironmentMinDistance = tmp.EnvironmentMinDistance; + dst.EnvironmentSkipSec = tmp.EnvironmentSkipSec; + dst.KitePullMeters = Math.Clamp(tmp.KitePullMeters, 3, 100); + dst.KiteTagFirst = tmp.KiteTagFirst; dst.WeaponSwapSettleMs = Math.Clamp(tmp.WeaponSwapSettleMs, 0, 3000); dst.WeaponSwapMinHealthPct = Math.Clamp(tmp.WeaponSwapMinHealthPct, 0, 100); dst.WeaponSwapMinGainPct = Math.Clamp(tmp.WeaponSwapMinGainPct, 0, 200); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index c0c75ca..bdf6572 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -207,6 +207,10 @@ public sealed class LegacyUiSettings // setting loads it as on. public bool TargetLock = true; public int RingRange = 5; + // Empyrean Handler lethal ring (CombatManager.HandleChatForRingEvade): when the Handler channels the + // ring and the character is inside its danger radius, back-jump away and re-engage. Only acts while + // the macro is running with combat on. On by default because it is gated that way. + public bool HandlerRingEvade = true; public int ApproachRange = 4; public int MinRingTargets = 4; // Blast like a ring: with BlastRange > 0, a rule with Blast on casts a blast only when @@ -252,6 +256,13 @@ public sealed class LegacyUiSettings public double CorpseApproachRangeMin = 2.0; public bool BoostNavPriority; + /// + /// Options > Navigation > Vaulted Dungeons: the MASTER switch of RynthILT's Vaulted Dungeons + /// keeper (Infinite Leaftide / ACECustom only). Off by default. RynthILT reads it through + /// "RynthAi.Hub" VaultedDungeonsEnabled; while it is off the keeper does nothing (no recalls, + /// no /rc quit, no tab). This is the one place the switch lives. + /// + public bool EnableVaultedDungeons; public bool BoostLootPriority; public bool OpenDoors; public float OpenDoorRange = 5.0f; @@ -400,7 +411,7 @@ public sealed class LegacyUiSettings /// public List MonsterNameBlacklist { get; set; } = new(); - public int GiveQueueIntervalMs = 150; + public int GiveQueueIntervalMs = 0; /// /// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield"). @@ -433,7 +444,7 @@ public sealed class LegacyUiSettings /// breaker runs and the heal is tried again; when that fails too, recall to the lifestone. /// Off: the breaker still runs, no recall. /// - public bool HpFailsafeRecall = true; + public bool HpFailsafeRecall = false; /// /// Minimum delay between offensive (war/void) COMBAT spell casts, in ms. @@ -470,6 +481,41 @@ public sealed class LegacyUiSettings public bool UseNativeAttack = false; public bool UseRecklessness; /// + /// The range a monster rule's "Variable" attack power picks from, in percent of the bar + /// (a new value every swing or shot). "Reckless + Variable" also stays inside the + /// Recklessness band (20-80%). See AttackPowerPlanner. + /// + public int VariablePowerMin = 50; + public int VariablePowerMax = 100; + + // ── Environment hits (2026-10-12, Combat/EnvironmentImpact.cs) ───────────── + /// + /// What missile combat does once a target has taken EnvironmentImpactLimit "Your missile + /// attack hit the environment." within EnvironmentImpactWindowSec: an EnvironmentResponse + /// (0 Off, 1 Move closer, 2 New target, 3 Move closer then new target). Off by default. + /// + public int MissileEnvironmentResponse; + /// The same for war/void casts whose projectiles stop short of the target. Off by default. + public int MagicEnvironmentResponse; + /// Environment hits on one target, within the window, that trip the response. + public int EnvironmentImpactLimit = 2; + /// The window (seconds) the hits are counted in. + public int EnvironmentImpactWindowSec = 20; + /// How far (metres) each "move closer" goes toward the target. + public int EnvironmentApproachMeters = 6; + /// Never approaches nearer than this (metres); already this close, a new target is picked. + public int EnvironmentMinDistance = 3; + /// How long (seconds) a target left for its environment hits is skipped. + public int EnvironmentSkipSec = 30; + /// + /// Pull-away kite (2026-10-16, Combat/KiteModes.cs): how far (metres) to drag a PullAway + /// monster from its lock-spot origin before stopping to kill it. Per-mob on/off is + /// MonsterRule.Kite (Default follows the DEFAULT row). + /// + public int KitePullMeters = 20; + /// Land a hit before fleeing so aggro sticks (Off = run immediately). + public bool KiteTagFirst = true; + /// /// Combat and buffing only ever wield weapons from the Items list. With this on (the /// default), a character whose Items list has no wand at all may still buff and cast with a /// caster from its pack (by object class, never by name). Any listed wand turns it off. @@ -819,6 +865,13 @@ public sealed class MonsterRule /// Debuffs the player typed in (Damage panel), comma separated: a spell's base /// name ("Corrosion Vulnerability Other") casts its best known tier; a full name casts as is. public string CustomDebuffs { get; set; } = ""; + /// Melee/missile attack power against the monsters this rule covers: one of + /// AttackPowerModes.All. "Default" = the DEFAULT line's choice (on the DEFAULT line: the global + /// Melee/Missile Power settings). Rules saved before 2026-10-12 load as Default. + public string AttackPower { get; set; } = AttackPowerModes.Default; + /// Combat pull-away for this rule: one of KiteModes.All. "Default" = the DEFAULT + /// line's choice (on the DEFAULT line: Off). Rules saved before 2026-10-16 load as Default. + public string Kite { get; set; } = "Default"; } public sealed class BuffRule @@ -1061,7 +1114,20 @@ public sealed class SettingsBridgePayload public bool UseNativeAttack { get; set; } public bool SummonPets { get; set; } public int PetMinMonsters { get; set; } - + // Variable attack power and the environment-impact throttle (2026-10-12). Null = sent by an + // engine without these controls, which leaves the plugin's own values alone. + public int? VariablePowerMin { get; set; } + public int? VariablePowerMax { get; set; } + public int? MissileEnvironmentResponse { get; set; } + public int? MagicEnvironmentResponse { get; set; } + public int? EnvironmentImpactLimit { get; set; } + public int? EnvironmentImpactWindowSec { get; set; } + public int? EnvironmentApproachMeters { get; set; } + public int? EnvironmentMinDistance { get; set; } + public int? EnvironmentSkipSec { get; set; } + // Pull-away kite (2026-10-16). Null = sender without these controls; leave plugin values alone. + public int? KitePullMeters { get; set; } + public bool? KiteTagFirst { get; set; } // Weapon swaps (only when the sender includes them). public int? WeaponSwapSettleMs { get; set; } public int? WeaponSwapMinHealthPct { get; set; } @@ -1101,6 +1167,11 @@ public sealed class SettingsBridgePayload // Navigation public bool BoostNavPriority { get; set; } + /// + /// Options > Navigation > Vaulted Dungeons: the keeper's master switch (off by default). Nullable: + /// an engine that predates the row omits it, and absent = unchanged (never switches it off or on). + /// + public bool? EnableVaultedDungeons { get; set; } public float FollowNavMin { get; set; } public float NavRingThickness { get; set; } public float NavLineThickness { get; set; } @@ -1111,6 +1182,10 @@ public sealed class SettingsBridgePayload public int NavLabelMode { get; set; } = -1; public bool? NavGuideLine { get; set; } public bool? NavResumeNearest { get; set; } + // NavOverlay.TrackBreadcrumbs / ShowRouteMarkers: the Nav panel's "Breadcrumbs" and "Route + // overlay" switches, also on Settings > Navigation. Null (an older engine) = unchanged. + public bool? TrackBreadcrumbs { get; set; } + public bool? ShowRouteOverlay { get; set; } public bool OpenDoors { get; set; } public float OpenDoorRange { get; set; } public bool? OpenDoorsOnPathOnly { get; set; } // absent (an older profile or plugin) = unchanged diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs index c8d57a1..9c778c9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs @@ -12,9 +12,11 @@ namespace RynthCore.Plugin.RynthAi.Loot; /// AutoCram moves non-equipped loose items out of the player's main pack into /// sub-packs so the main pack stays empty for new loot pickups. /// -/// AutoStack merges two partial stacks of the same item (arrows, components, -/// salvage, pyreals, etc.) by dropping the smaller one onto the larger one's -/// slot — the server auto-merges stackable same-type items at the same slot. +/// AutoStack merges two partial stacks of the same weenie (arrows, components, +/// pyreals, etc.) by dropping the smaller one onto the larger one's slot — the +/// server merges only same-WCID stackables. Groups by WCID (not display name). A +/// pair whose total is over MaxStackSize is still tried: the server fills the +/// target and leaves the rest in the source, which is progress, not a failure. /// public sealed class InventoryManager { @@ -33,7 +35,7 @@ public sealed class InventoryManager // engine return is enqueue-accepted, not moved-confirmed (AcMainThreadQueue // gesture-defers a move up to ~250 ticks ≈ 4-8s), so success and failure are // indistinguishable at the call site. We confirm on a LATER snapshot. - private sealed class Pending { public DateTime EnqueuedAt; public int FromContainer; } + private sealed class Pending { public DateTime EnqueuedAt; public int FromContainer; public int TargetCount; public int SourceCount; } private sealed class Backoff { public DateTime NextRetry; public int Attempts; public DateTime LastTouched; } private readonly Dictionary _cramPending = new(); // item id -> in-flight move private readonly Dictionary _cramBackoff = new(); // item id -> confirmed-fail backoff @@ -259,10 +261,12 @@ public sealed class InventoryManager if (inPlayerScope) playerItems.Add(item); } - // Group by name, keep only stackable items with >1 in the same group. + // Group by weenie class id (WCID), not display name. Same-name stacks that are + // different weenies (e.g. Coalesced Mana 42517 vs 42518) cannot merge — the server + // answers "not compatible for stacking" and AutoStack used to retry forever. var groupList = playerItems .Where(x => GetMaxStackSize(x) > 1) - .GroupBy(x => x.Name) + .GroupBy(StackGroupKey) .Where(g => g.Count() > 1) .ToList(); @@ -308,7 +312,9 @@ public sealed class InventoryManager if (_stackPending.TryGetValue(key, out var sp)) { bool sourceGone = !inv.Any(x => x.Id == parts[si].Item.Id); - if (sourceGone) + // Past the max the server fills the target and the source survives smaller: + // that is a merge too, not a failure. + if (sourceGone || MergeProgressed(sp.TargetCount, sp.SourceCount, parts[ti].Count, parts[si].Count)) { _stackPending.Remove(key); _stackBackoff.Remove(key); @@ -350,7 +356,7 @@ public sealed class InventoryManager // Enqueue accepted — record PENDING, confirm on a later snapshot. Do NOT // add the pair-key on success (the old bug that poisoned good merges and // starved multi-partial consolidation). - _stackPending[pairKey] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId }; + _stackPending[pairKey] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId, TargetCount = target.Count, SourceCount = source.Count }; return true; // one action per tick } @@ -400,7 +406,24 @@ public sealed class InventoryManager foreach (var k in dead) map.Remove(k); } - // ── Stack-size lookup ───────────────────────────────────────────────── + // ── Stack-size / group-key lookup ───────────────────────────────────── + + /// + /// AutoStack group key: the WCID when known (Decal Type / TryGetObjectWcid), else the name. + /// Name-only is a cold-start fallback; once a WCID is known, same-name stacks of different + /// weenies stay in separate groups. + /// + internal static string StackGroupKey(int wcid, string? name) => wcid > 0 ? "w:" + wcid : "n:" + (name ?? ""); + + private static string StackGroupKey(WorldObject item) + => StackGroupKey(item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0), item.Name); + + /// + /// True when a merge we sent moved something: the target grew or the source shrank since it was + /// enqueued. Counts are read from the same snapshot, so a refused merge changes neither. + /// + internal static bool MergeProgressed(int targetBefore, int sourceBefore, int targetNow, int sourceNow) + => targetBefore > 0 && sourceBefore > 0 && (targetNow > targetBefore || sourceNow < sourceBefore); private static int GetMaxStackSize(WorldObject item) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs index 6196513..8f84088 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs @@ -184,7 +184,9 @@ internal sealed class LootEditorBridge d.ItemId = id; var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2); d.IncludeT11 = req.IncludeT11; - LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like, req.IncludeT11); + d.AttributesSupported = true; + // The checklist shows every attribute whatever the match, so the item is always read in full. + LootItemFacts? facts = Items.Facts(id, true, req.IncludeT11 || req.Choices != null); 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; @@ -211,9 +213,11 @@ internal sealed class LootEditorBridge KeepCount = req.KeepCount < 0 ? null : req.KeepCount, RuleName = req.RuleName, IncludeT11 = req.IncludeT11, + Choices = req.Choices, }; LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error); if (draft == null) return Refuse(d, error); + foreach (LootItemAttribute row in draft.Attributes) d.Attributes.Add(row.ToWire()); d.Match = (int)draft.Match; d.Action = (int)draft.Action; d.KeepCount = draft.KeepCount; diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index f11f5e9..d538a04 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -962,9 +962,9 @@ internal sealed class ManaStoneManager if (!_host.HasRequestId) return false; if (_host.HasHasAppraisalData && _host.HasAppraisalData(unchecked((uint)id))) return false; if (_stoneIdRequestedAt.TryGetValue(id, out long at) && now - at < StoneIdRetryMs) return false; + if (!_host.RequestId(unchecked((uint)id))) return false; // refused (a death or a portal): asked again next pass, not in 5 minutes _stoneIdRequestedAt[id] = now; _host.Log($"[RynthAi] ManaStone: identifying stone 0x{(uint)id:X8} (its charge can't be read)."); - _host.RequestId(unchecked((uint)id)); return true; } @@ -1078,8 +1078,7 @@ internal sealed class ManaStoneManager if (!requestedThisPass && _host.HasRequestId && (!_manaIdRequestedAt.TryGetValue(item.Id, out long at) || nowMs - at > 300_000)) { - _manaIdRequestedAt[item.Id] = nowMs; - _host.RequestId(unchecked((uint)item.Id)); + if (_host.RequestId(unchecked((uint)item.Id))) _manaIdRequestedAt[item.Id] = nowMs; // a refused one is asked again next pass requestedThisPass = true; } continue; @@ -1101,9 +1100,11 @@ internal sealed class ManaStoneManager && nowMs - _lastGearRefreshAt >= GearRefreshSpacingMs && (!_gearReadRefreshedAt.TryGetValue(item.Id, out long readAt) || nowMs - readAt >= GearRefreshMs)) { - _gearReadRefreshedAt[item.Id] = nowMs; - _lastGearRefreshAt = nowMs; - _host.RequestId(unchecked((uint)item.Id)); + if (_host.RequestId(unchecked((uint)item.Id))) // a refused one is asked again next pass + { + _gearReadRefreshedAt[item.Id] = nowMs; + _lastGearRefreshAt = nowMs; + } requestedThisPass = true; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index be993b9..f622425 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3631,6 +3631,20 @@ internal sealed class ExpressionEngine ["CastDispelSelf"] = (() => B(s.CastDispelSelf), v => s.CastDispelSelf = ToDouble(v) != 0), ["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0), ["UseRecklessness"] = (() => B(s.UseRecklessness), v => s.UseRecklessness = ToDouble(v) != 0), + // The range a monster rule's Variable attack power picks from (percent of the bar). + ["VariablePowerMin"] = (() => I(s.VariablePowerMin), v => { if (int.TryParse(v, out int i)) s.VariablePowerMin = Math.Clamp(i, 0, 100); }), + ["VariablePowerMax"] = (() => I(s.VariablePowerMax), v => { if (int.TryParse(v, out int i)) s.VariablePowerMax = Math.Clamp(i, 0, 100); }), + // Environment hits: 0 Off, 1 Move closer, 2 New target, 3 Move closer then new target. + ["MissileEnvironmentResponse"] = (() => I(s.MissileEnvironmentResponse), v => { if (int.TryParse(v, out int i)) s.MissileEnvironmentResponse = Math.Clamp(i, 0, 3); }), + ["MagicEnvironmentResponse"] = (() => I(s.MagicEnvironmentResponse), v => { if (int.TryParse(v, out int i)) s.MagicEnvironmentResponse = Math.Clamp(i, 0, 3); }), + ["EnvironmentImpactLimit"] = (() => I(s.EnvironmentImpactLimit), v => { if (int.TryParse(v, out int i)) s.EnvironmentImpactLimit = Math.Clamp(i, 1, 10); }), + ["EnvironmentImpactWindowSec"] = (() => I(s.EnvironmentImpactWindowSec), v => { if (int.TryParse(v, out int i)) s.EnvironmentImpactWindowSec = Math.Clamp(i, 5, 120); }), + ["EnvironmentApproachMeters"] = (() => I(s.EnvironmentApproachMeters), v => { if (int.TryParse(v, out int i)) s.EnvironmentApproachMeters = Math.Clamp(i, 1, 30); }), + ["EnvironmentMinDistance"] = (() => I(s.EnvironmentMinDistance), v => { if (int.TryParse(v, out int i)) s.EnvironmentMinDistance = Math.Clamp(i, 1, 30); }), + ["EnvironmentSkipSec"] = (() => I(s.EnvironmentSkipSec), v => { if (int.TryParse(v, out int i)) s.EnvironmentSkipSec = Math.Clamp(i, 5, 300); }), + // Pull-away kite (Combat/KiteModes.cs). + ["KitePullMeters"] = (() => I(s.KitePullMeters), v => { if (int.TryParse(v, out int i)) s.KitePullMeters = Math.Clamp(i, 3, 100); }), + ["KiteTagFirst"] = (() => B(s.KiteTagFirst), v => s.KiteTagFirst = ToDouble(v) != 0), ["WeaponSwapSettleMs"] = (() => I(s.WeaponSwapSettleMs), v => { if (int.TryParse(v, out int i)) s.WeaponSwapSettleMs = Math.Clamp(i, 0, 3000); }), ["WeaponSwapMinHealthPct"] = (() => I(s.WeaponSwapMinHealthPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinHealthPct = Math.Clamp(i, 0, 100); }), ["WeaponSwapMinGainPct"] = (() => I(s.WeaponSwapMinGainPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinGainPct = Math.Clamp(i, 0, 200); }), diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs index 3aa80c7..0d218f0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs @@ -119,6 +119,12 @@ public sealed class PetTabState public bool KeepCosmeticOut; /// Seconds to wait before re-summoning the cosmetic pet after it despawns. public int CosmeticRespawnSeconds = 15; + + // Auto siphon-lens capture (ACECustom MonsterCapture; Mini Remote > Pets). + /// When on, use the selected siphon lens on a nearby creature once it is weak enough. + public bool AutoCaptureEnabled; + /// Index into (Flawed to Asheron). + public int CaptureLensIndex; } /// A user's choice of summon type for one essence (matched by name, case-insensitive). @@ -250,6 +256,7 @@ internal sealed class MiniRemoteStore s.Pet.RosterKind = Math.Clamp(s.Pet.RosterKind, 0, 2); s.Pet.RosterSort = Math.Clamp(s.Pet.RosterSort, 0, 6); s.Pet.CosmeticRespawnSeconds = Math.Clamp(s.Pet.CosmeticRespawnSeconds, 5, 600); + s.Pet.CaptureLensIndex = Math.Clamp(s.Pet.CaptureLensIndex, 0, PetCaptureRules.Lenses.Length - 1); s.Quests ??= new QuestsTabState(); s.Quests.QuestFilter ??= string.Empty; s.Quests.QuestFavorites ??= new(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetCaptureRules.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetCaptureRules.cs new file mode 100644 index 0000000..3b3e1e9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetCaptureRules.cs @@ -0,0 +1,164 @@ +// PetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host). +// +// Copied from ACECustom Source/ACE.Server/Entity/MonsterCapture.cs so the client can tell when +// a creature is weak enough to siphon before using a lens. Keep these numbers in lockstep with +// the server: CaptureMaxHealthFraction / CaptureMaxHealthPoints / CaptureRangeM and the lens +// WCID table in PetGuideController. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.MiniRemote; + +/// One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated). +public readonly struct PetCaptureLens +{ + public PetCaptureLens(string name, uint wcid, bool bypassesHealthGate) + { + Name = name; + Wcid = wcid; + BypassesHealthGate = bypassesHealthGate; + } + + public string Name { get; } + public uint Wcid { get; } + /// Asheron's (and Debug) lenses skip the 20% / 20 HP gate. + public bool BypassesHealthGate { get; } +} + +/// +/// When a siphon lens can be used, matching ACECustom MonsterCapture.UseCaptureCrystal. +/// A creature is weak enough when its health fraction is ≤ 20% OR its current HP is under 20 +/// (whichever comes first). Asheron's Lens skips that check. +/// +public static class PetCaptureRules +{ + /// A lens targets the nearest attackable creature within this many meters. + public const float CaptureRangeM = 5.0f; + + /// Siphon once at or below this fraction of max health… + public const float CaptureMaxHealthFraction = 0.20f; + + /// …or below this many hit points (the gate is OR with the fraction). + public const int CaptureMaxHealthPoints = 20; + + /// + /// Lenses the player can pick for auto-capture. Order is the combo index. + /// Resonance needs a prior failed capture (server-side); Asheron's bypasses the health gate. + /// + public static readonly PetCaptureLens[] Lenses = + { + new("Flawed Siphon Lens", 78780001, bypassesHealthGate: false), + new("Pristine Siphon Lens", 78780002, bypassesHealthGate: false), + new("Perfect Siphon Lens", 78780003, bypassesHealthGate: false), + new("Resonance Lens", 78780010, bypassesHealthGate: false), + new("Asheron's Lens", 78780012, bypassesHealthGate: true), + }; + + /// Combo labels for the Pets tab (same order as ). + public static readonly string[] LensNames = + { + "Flawed", "Pristine", "Perfect", "Resonance", "Asheron's", + }; + + public static PetCaptureLens LensAt(int index) + { + int i = Math.Clamp(index, 0, Lenses.Length - 1); + return Lenses[i]; + } + + /// + /// True when ACECustom would accept a siphon on this creature for a normal (non-bypass) lens. + /// Pass current/max when known; when only a 0–1 ratio is known, pass ratio as current and 1 as max + /// (then only the fraction half of the gate can fire). + /// + public static bool IsWeakEnough(uint currentHp, uint maxHp) + { + if (currentHp == 0) return false; // dead — server refuses + if (maxHp == 0) return false; + float pct = (float)currentHp / maxHp; + // Server: refuse when pct > 0.20 AND current >= 20. Allowed otherwise. + return pct <= CaptureMaxHealthFraction || currentHp < CaptureMaxHealthPoints; + } + + /// Same gate from a 0–1 health ratio only (no absolute HP). Dead / unknown = false. + public static bool IsWeakEnoughRatio(float healthRatio) + { + if (healthRatio <= 0f || healthRatio > 1f) return false; + return healthRatio <= CaptureMaxHealthFraction; + } + + /// True when this lens may be used given the creature's vitals (bypass lenses always, if alive). + public static bool CanAttempt(PetCaptureLens lens, uint currentHp, uint maxHp) + { + if (currentHp == 0) return false; + if (lens.BypassesHealthGate) return maxHp == 0 || currentHp > 0; + return IsWeakEnough(currentHp, maxHp); + } + + /// Distance gate: ACECustom CaptureRangeM. + public static bool InRange(double distanceM) => distanceM >= 0 && distanceM <= CaptureRangeM; +} + +/// +/// A brake on the auto-capture loop. The Pets tab fires a lens every couple of seconds and only stops +/// on reply strings it guesses at, so an unrecognized reply (or a creature the server never lets go of) +/// would burn lenses without end. This caps consecutive tries per target and, as a backstop, consecutive +/// tries over all targets; both reset on a recognized success. Pure: the tests drive it. +/// +public sealed class PetCaptureThrottle +{ + /// Lens uses on one creature, with no success in between, before it is left alone. + public const int MaxTriesPerTarget = 5; + + /// How long a creature that used up its tries is left alone (ms). + public const long TargetBlockMs = 120_000; + + /// Lens uses over all creatures with no success before auto-capture switches itself off. + public const int MaxTriesWithoutSuccess = 15; + + private readonly Dictionary _tries = new(); + private readonly Dictionary _blockedUntil = new(); + private int _sinceSuccess; + + /// Consecutive lens uses with no recognized success (all targets). + public int TriesWithoutSuccess => _sinceSuccess; + + /// True when the backstop was hit: the caller should switch auto-capture off. + public bool Exhausted => _sinceSuccess >= MaxTriesWithoutSuccess; + + /// False while this target is blocked (it used its tries) or the backstop is hit. + public bool MayAttempt(int targetId, long nowMs) + { + if (Exhausted) return false; + if (_blockedUntil.TryGetValue(targetId, out long until)) + { + if (nowMs < until) return false; + _blockedUntil.Remove(targetId); // block served: a fresh set of tries + _tries.Remove(targetId); + } + return true; + } + + /// Seconds left on this target's block, 0 when it is not blocked. + public long BlockedSecondsLeft(int targetId, long nowMs) + => _blockedUntil.TryGetValue(targetId, out long until) && nowMs < until ? (until - nowMs + 999) / 1000 : 0; + + /// Count a lens use on this target; blocks it once it reaches . + public void RecordAttempt(int targetId, long nowMs) + { + _sinceSuccess++; + int n = _tries.TryGetValue(targetId, out int t) ? t + 1 : 1; + _tries[targetId] = n; + if (n >= MaxTriesPerTarget) _blockedUntil[targetId] = nowMs + TargetBlockMs; + } + + /// A recognized success reply: everything starts over. + public void RecordSuccess() => Reset(); + + public void Reset() + { + _tries.Clear(); + _blockedUntil.Clear(); + _sinceSuccess = 0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs index da328a7..3052e60 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs @@ -23,6 +23,9 @@ // player bools the server stamps. Feeds PetManager.AllowSummonOnEmpty. // * Healing pet (UB HealingBuddy subset): summons a heal pet when HP drops, dismisses it // after the heal lands, holds PetManager's combat summons while it is out. +// * Auto siphon capture (ACECustom MonsterCapture): when enabled, uses the chosen lens on the +// nearest attackable creature within 5 m once it is <=20% health or under 20 HP (Asheron's +// Lens skips the health gate). Resonance still needs a prior failed capture on the server. // * /pets and /shinies logs: RynthILT's (RynthILT.Hub section "pets-logs", ILT only). // * Breeding sub-tab (Infinite Leaftide only): the tab becomes Roster | Breeding when RynthILT // offers it (an ILT world whose server hasn't reported pet breeding off). Its whole body is @@ -57,6 +60,17 @@ internal sealed class PetsTab private long _lastHealThink; private string _healStatus = "idle"; + // Auto siphon-lens capture (ACECustom MonsterCapture). + private long _lastCaptureThink; + private long _captureCooldownUntil; + private volatile string _captureStatus = "off"; + private const long CaptureThinkMs = 250; + private const long CaptureCooldownMs = 2500; + private const long CaptureFailBackoffMs = 8000; + // Hard cap on lens uses: the loop stops on reply strings we only guess at, so it is also bounded + // per creature and over all creatures (PetCaptureThrottle). + private readonly PetCaptureThrottle _captureThrottle = new(); + // Roster snapshot (rebuilt on the pump thread, read by the render thread). private volatile PetStats[] _pets = Array.Empty(); private long _lastPetScan; @@ -289,6 +303,11 @@ internal sealed class PetsTab _lastHealThink = nowMs; TickHealing(nowMs); } + if (nowMs - _lastCaptureThink >= CaptureThinkMs) + { + _lastCaptureThink = nowMs; + TickCapture(nowMs); + } if (nowMs - _lastPresenceThink >= 1000) { _lastPresenceThink = nowMs; @@ -334,9 +353,51 @@ internal sealed class PetsTab EndHealCycle(MiniRemoteContext.NowMs, "heal landed"); } } + + // ACECustom MonsterCapture replies — back off after a refuse so we don't burn lenses. + if (S.AutoCaptureEnabled && text.Length > 0) + { + long now = MiniRemoteContext.NowMs; + if (PetCaptureLines.IsSuccess(text)) + { + _captureStatus = "captured"; + _captureThrottle.RecordSuccess(); + _captureCooldownUntil = now + CaptureCooldownMs; + } + else if (ContainsAny(text, + "too strong", + "blind rage", + "cannot be siphoned", + "cannot be captured", + "No creatures nearby", + "already dead", + "already being captured", + "hasn't failed a capture", + "echo has faded", + "Failed to consume")) + { + _captureStatus = "refused: " + Truncate(text, 48); + _captureCooldownUntil = now + CaptureFailBackoffMs; + } + else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades")) + { + _captureStatus = "failed (creature may enrage)"; + _captureCooldownUntil = now + CaptureFailBackoffMs; + } + } return false; } + private static bool ContainsAny(string text, params string[] parts) + { + foreach (string p in parts) + if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true; + return false; + } + + private static string Truncate(string s, int max) + => s.Length <= max ? s : s[..(max - 3)] + "..."; + public void OnLogout() { _heal = HealState.Idle; @@ -345,6 +406,9 @@ internal sealed class PetsTab _lastSummonEssenceId = 0; _cosmeticOutEssenceId = 0; _cosmeticNextAt = 0; + _captureCooldownUntil = 0; + _captureStatus = "off"; + _captureThrottle.Reset(); } // ── Healing pet ───────────────────────────────────────────────────────── @@ -415,6 +479,154 @@ internal sealed class PetsTab // ── Active pet ────────────────────────────────────────────────────────── + // ── Auto siphon capture (ACECustom MonsterCapture) ─────────────────────── + + /// + /// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature + /// within 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it). + /// The server picks the nearest creature itself — we only fire when that nearest candidate is + /// already weak enough, so a full-health neighbour closer than the wounded target won't waste a lens. + /// + private void TickCapture(long now) + { + if (!S.AutoCaptureEnabled) + { + _captureStatus = "off"; + return; + } + if (_ctx.Ilt.Loaded && _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture)) + { + _captureStatus = "monster capture disabled on this server"; + return; + } + if (now < _captureCooldownUntil) + { + long left = (_captureCooldownUntil - now + 999) / 1000; + if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal)) + _captureStatus = $"waiting {left}s"; + return; + } + if (_ctx.Inventory.IsBusy) { _captureStatus = "busy"; return; } + + var lens = PetCaptureRules.LensAt(S.CaptureLensIndex); + var lensItem = _ctx.Inventory.FindByWcid(lens.Wcid); + if (lensItem == null) + { + _captureStatus = $"no {lens.Name} carried"; + return; + } + + if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp)) + { + _captureStatus = "no attackable creature within 5 m"; + return; + } + + if (!PetCaptureRules.InRange(distM)) + { + _captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)"; + return; + } + + if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp)) + { + float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f; + _captureStatus = pct >= 0 + ? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)" + : $"{target!.Name}: health unknown"; + return; + } + + if (!_captureThrottle.MayAttempt(target!.Id, now)) + { + _captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s"; + return; + } + + if (!_ctx.Inventory.Use(lensItem)) + { + _captureStatus = "UseObject refused"; + return; + } + _captureThrottle.RecordAttempt(target.Id, now); + if (_captureThrottle.Exhausted) + { + // Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them. + S.AutoCaptureEnabled = false; + RynthLog.Write(LogCat.Pets, + $"[Pets] auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off"); + } + + float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f; + _captureStatus = $"using {lens.Name} on {target!.Name} ({shown:0}% / {curHp} HP)"; + _captureCooldownUntil = now + CaptureCooldownMs; + RynthLog.Write(LogCat.Pets, + $"[Pets] auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}"); + } + + /// + /// Nearest attackable landscape creature within capture range, with vitals from the host when + /// available else the cache health ratio (fraction-only gate). + /// + private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp) + { + best = null; + bestDist = double.MaxValue; + curHp = maxHp = 0; + var cache = _ctx.Inventory.Cache; + if (cache == null) return false; + uint playerId = _ctx.Inventory.PlayerId; + if (playerId == 0) return false; + int pid = unchecked((int)playerId); + string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty; + + foreach (var wo in cache.GetLandscape()) + { + if (wo == null || wo.Id == pid) continue; + if (wo.ObjectClass != AcObjectClass.Monster) continue; + if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue; + // Skip corpses / non-attackable when the host can tell. + if (_ctx.Host.HasObjectIsAttackable && !_ctx.Host.ObjectIsAttackable(unchecked((uint)wo.Id))) + continue; + + double d = cache.Distance(pid, wo.Id); + if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue; + + if (!TryReadCreatureVitals(wo.Id, cache, out uint c, out uint m)) + continue; + if (c == 0) continue; // dead + + best = wo; + bestDist = d; + curHp = c; + maxHp = m; + } + return best != null; + } + + /// + /// Absolute vitals via TryGetTargetVitals when bound; else cache health ratio as a 0–1000 scale + /// so only the fraction half of ACECustom's gate can fire. + /// + private bool TryReadCreatureVitals(int id, WorldObjectCache cache, out uint cur, out uint max) + { + cur = max = 0; + if (_ctx.Host.HasGetTargetVitals + && _ctx.Host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _) + && mh > 0) + { + cur = h; + max = mh; + return true; + } + float ratio = cache.GetHealthRatio(id); + if (ratio < 0f) return false; + // Synthetic scale: ratio 0.20 → 200/1000 so IsWeakEnough's fraction half matches. + max = 1000; + cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000); + return true; + } + /// The live "<Me>'s …" creature (server pet naming), or null. private WorldObject? FindOwnPet() { @@ -764,12 +976,49 @@ internal sealed class PetsTab { ImGui.Separator(); RenderCharms(); + ImGui.Separator(); + RenderCapture(); } ImGui.Separator(); RenderHealing(); _ctx.Ilt.RenderSection(RynthIltHub.SectionPetLogs); } + /// ACECustom siphon-lens auto-capture (ILT only): enable + which lens to use. + private void RenderCapture() + { + ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Monster capture"); + bool captureOff = _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture); + ImGui.BeginDisabled(captureOff); + bool en = S.AutoCaptureEnabled; + if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en)) + { + S.AutoCaptureEnabled = en; + _captureThrottle.Reset(); + } + if (ImGui.IsItemHovered()) + { + SafeImGui.SetTooltip( + "Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" + + "at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" + + "the health gate. Resonance Lens still needs a prior failed capture on the server.\n" + + "Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" + + "or 15 lens uses in a row with no capture."); + } + ImGui.SameLine(); + ImGui.SetNextItemWidth(120); + int lens = Math.Clamp(S.CaptureLensIndex, 0, PetCaptureRules.LensNames.Length - 1); + if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length)) + S.CaptureLensIndex = lens; + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack."); + ImGui.EndDisabled(); + if (captureOff) + SafeImGui.TextDisabled("Monster capture is disabled on this server."); + else + SafeImGui.TextDisabled("Status: " + _captureStatus); + } + /// Type / Sort combos, action buttons, the active-summon line and per-type options. private void RenderRosterHeader(LegacyUiSettings settings) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index 1944548..af4ef00 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -1785,7 +1785,12 @@ internal sealed class NavigationEngine return false; } - _host.UseFor((uint)bestId, "Nav", $"portal/NPC waypoint '{target}'"); + // A use the engine did not send (UseObject said no) is not a use: false lets the caller ask again. + if (!_host.UseFor((uint)bestId, "Nav", $"portal/NPC waypoint '{target}'")) + { + _host.Log($"Nav: UseObject portal '{target}' (0x{bestId:X8}) was not sent - will retry"); + return false; + } // Publish the resolved object so the marker renderer can draw a ring + // line to the portal's real position (the waypoint coord is a placeholder). _settings.ActivePortalObjId = (uint)bestId; diff --git a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs index 94e20c2..9d10fca 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs @@ -243,6 +243,8 @@ public static class VirindiTankProfileImporter dst.OffhandId = src.OffhandId; dst.PreferredAmmoItemId = src.PreferredAmmoItemId; dst.PetDamage = src.PetDamage; + dst.AttackPower = src.AttackPower; + dst.Kite = src.Kite; } private static MonsterRule CloneMonsterRule(MonsterRule row) => @@ -268,6 +270,8 @@ public static class VirindiTankProfileImporter OffhandId = row.OffhandId, PreferredAmmoItemId = row.PreferredAmmoItemId, PetDamage = row.PetDamage, + AttackPower = row.AttackPower, + Kite = row.Kite, PreferredDamage = row.PreferredDamage, }; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 0bcec58..72b5a33 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -2246,11 +2246,7 @@ public sealed partial class RynthAiPlugin case "cancel": HandleCancelForceBuff(); break; case "skipped": if (_buffManager == null) { ChatLine("[RynthAi] Buff manager not ready."); break; } - _buffManager.BuildDynamicBuffList(); // refresh the skip list - string summary = _buffManager.FilterSkipSummary(); - ChatLine(summary.Length == 0 - ? "[RynthAi] Buff filter: nothing is being skipped." - : $"[RynthAi] Buff filter skips: {summary}"); + _buffManager.RequestSkipReport(); // chat commands run on AC's thread; the pump builds the list and answers break; default: ChatLine("[RynthAi] /ra buff force - recast every buff now, whatever time is left"); @@ -2602,10 +2598,7 @@ public sealed partial class RynthAiPlugin if (allItems) { foreach (var item in matches) - { - int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1)); - EnqueueGive((uint)item.Id, (uint)target.Id, stackSize); - } + EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack, whatever it reads at send time ChatLine($"[RynthAi] Queued {matches.Count} stack(s) matching '{itemPart}' → {target.Name}"); } else if (countGiven) @@ -2626,8 +2619,8 @@ public sealed partial class RynthAiPlugin } if (gives.Count == 1) { - GiveItem((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount, - Math.Max(1, gives[0].Item.Values(LongValueKey.StackCount, 1))); + // Through the queue: an NPC that takes one item per give needs the repeat-until-met loop. + EnqueueGive((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount); ChatLine($"[RynthAi] Giving {gives[0].Amount} x '{gives[0].Item.Name}' to {target.Name}"); } else @@ -2707,8 +2700,7 @@ public sealed partial class RynthAiPlugin if (IsGiveProfileExempt(item)) continue; var (action, _) = Loot.LootEvaluator.Classify(nativeProfile, item, null); if (action != RynthCore.Loot.LootAction.Keep) continue; - int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1)); - EnqueueGive((uint)item.Id, (uint)target.Id, stackSize); + EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack queued++; } } @@ -2723,8 +2715,7 @@ public sealed partial class RynthAiPlugin foreach (var rule in vtProfile.Rules) if (VTankLootEvaluator.Match(rule, item, lootCtx)) { matched = rule; break; } if (matched == null || (matched.Action != VTankLootAction.Keep && matched.Action != VTankLootAction.KeepUpTo)) continue; - int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1)); - EnqueueGive((uint)item.Id, (uint)target.Id, stackSize); + EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack queued++; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs index 12145cd..17caff1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -159,6 +159,8 @@ public sealed partial class RynthAiPlugin internal MiniRemote.MiniRemoteController? MiniRemoteForIlt => _miniRemote; internal WorldObjectCache? ObjectCacheForIlt => _objectCache; internal RynthCore.Plugin.Shared.SessionStatsTracker? SessionStatsForIlt => _sessionStats; + /// The Vaulted Dungeons master switch (Settings > Navigation); false before login. + internal bool VaultedDungeonsEnabledForIlt => _dashboard?.Settings.EnableVaultedDungeons == true; /// Item Info window, created once settings exist. private void EnsureItemInfoUi() diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs index 02a1ea4..db5f9d2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs @@ -58,6 +58,19 @@ public sealed partial class RynthAiPlugin /// private bool _wasPortalingForPacer; + private bool _wasMacroForPacer; + + /// + /// The macro is switched on (off to on, whoever did it): a UseDone that arrived while it was off, a + /// player's own refused action, is not news. Without this the pacer's observer took it for a fresh + /// 'too busy' answer at the first check and held every start for the probe wait (~1.5 s). + /// + private void NoteMacroForPacer(bool running) + { + if (running && !_wasMacroForPacer) RynthCore.Plugin.Shared.ActionPacer.NoteMacroStart(); + _wasMacroForPacer = running; + } + /// Portal space starts: the server dropped what was open (no breaker on a teleport's gap). private void NotePortalForPacer() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 090ac26..afd8590 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -133,13 +133,54 @@ 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 int _giveInFlightStack, _giveInFlightTries; private long _giveInFlightAt; private const long GiveConfirmMs = 3000; private const int GiveMaxTries = 2; + // Items still to hand over from the in-flight give (a whole stack = its size; each shrink lowers it). + private int _giveInFlightRemaining; + // The in-flight request is a genuine "give all" (amount 0 from the caller): the only kind that may go out as a plain, + // whole-object give when the stack count cannot be read. A re-send of it stays "all". + private bool _giveInFlightAll; + // True once the in-flight give has been sent more than once (a busy re-send or a no-answer re-send): + // an "Item not found!" then means an earlier send already landed. + private bool _giveInFlightResent; + private string _giveInFlightName = string.Empty; + private long _giveLastSendAt = long.MinValue; + // A busy refusal re-sends the same give after this long (up to GiveBusyGiveUpMs in total). + private const long GiveBusyRetryMs = 300; + private long _giveBusyRetryAt; // 0 = not waiting on a busy re-send + // Continuous busy waiting on one give: since when, how many busy answers, when the player was last told. + private long _giveBusySince, _giveBusyNoticeAt; + private int _giveBusyCount; + private const long GiveBusyNoticeMs = 10000; + // Busy waiting on one give is given up after this long in total: the item is skipped and counted. + private const long GiveBusyGiveUpMs = 60000; + // A stackable item whose stack count will not read: which item, since when. After GiveReadFailMs the + // give goes out anyway (an explicit amount, or a plain give for amount 1) so the queue always advances. + private uint _giveReadFailId; + private long _giveReadFailSince; + private const long GiveReadFailMs = 2000; + // Consecutive ticks the in-flight item read as unreadable (no cache entry, Container 0); 2 = gone. + private int _giveGoneStreak; + private int _giveUnclassified; // unclassified chat lines logged for this give (max 5) + // Chat verdict on the in-flight give, set by OnChatWindowText and read on the tick. + private enum GiveChat { None, Busy, Permanent, ItemNotFound } + private int _giveChatVerdict; // a GiveChat, handed from OnChatWindowText to the tick with Interlocked + private string _giveChatLine = string.Empty; + private bool _giveSawAcceptLine; + // A stack that shrank but is still carried goes again before anything else in the queue. + private (uint itemId, uint targetId, int remaining)? _giveRedo; + // Run summary (reset when the queue empties). + private bool _giveRunActive; + private long _giveRunStartAt, _giveRunLastAnswerAt; + private int _giveRunItems; + private readonly List _giveRunSkips = new(); + // Test seam: a fake millisecond clock. + private Func? _giveClock; + private long GiveNow() => _giveClock?.Invoke() ?? Environment.TickCount64; private RynthCore.Loot.LootProfile? _nativeLootProfile; private string _nativeLootProfilePath = string.Empty; private DateTime _nativeLootProfileTime = DateTime.MinValue; @@ -261,6 +302,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase RynthCore.Plugin.Shared.UseAudit.WorldUseHold = null; RynthCore.Plugin.Shared.ActionPacer.Enabled = false; RynthCore.Plugin.Shared.ActionPacer.Forget("shutdown"); + CombatHook.LastUseDone = null; // captured this instance's host (set again at Init) // 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 @@ -450,6 +492,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _playerId = 0; _loginComplete = false; _pendingGives.Clear(); + ResetGiveState(); // A /ub delay armed before logout must not fire into the next character's session. _delayedCommands.Clear(); ClearPropertyDump(); @@ -699,6 +742,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve _combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells _combatManager.SetStaleBusyCallback(OnCombatBusyStale); + // Empyrean Handler lethal-ring: face the Handler, run-back jump (Jumper "xs"), re-engage. + // Read _jumper at call time — it is constructed later in this session setup. + _combatManager.RequestBackJump = (faceHeading, ms) => _jumper != null && _jumper.Start("xs", faceHeading, ms); + _combatManager.JumpBusy = () => _jumper?.IsBusy == true; _buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count if (_buffManager != null) _buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id); @@ -1015,7 +1062,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { ["TargetFPSFocused"] = (10, 240), ["TargetFPSBackground"] = (5, 60), ["BlacklistAttempts"] = (1, 20), ["BlacklistTimeoutSec"] = (5, 120), ["BlacklistCastSettleMs"] = (500, 5000), - ["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000), + ["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (0, 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), ["RestamTo"] = (0, 100), ["GetManaAt"] = (0, 100), @@ -1023,6 +1070,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100), ["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100), ["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2), + ["VariablePowerMin"] = (0, 100), ["VariablePowerMax"] = (0, 100), + ["MissileEnvironmentResponse"] = (0, 3), ["MagicEnvironmentResponse"] = (0, 3), + ["EnvironmentImpactLimit"] = (1, 10), ["EnvironmentImpactWindowSec"] = (5, 120), + ["EnvironmentApproachMeters"] = (1, 30), ["EnvironmentMinDistance"] = (1, 30), ["EnvironmentSkipSec"] = (5, 300), + ["KitePullMeters"] = (3, 100), ["WeaponSwapSettleMs"] = (0, 3000), ["WeaponSwapMinHealthPct"] = (0, 100), ["WeaponSwapMinGainPct"] = (0, 200), ["PetMinMonsters"] = (1, 20), ["SpellCastIntervalMs"] = (100, 1500), ["StuckCastBreakMs"] = (0, 60000), ["RecoveryRetryMs"] = (200, 5000), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100), @@ -1126,9 +1178,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase int id = unchecked((int)e.Id); if (Host.HasRequestId && idRequests < 3 && (!Host.HasHasAppraisalData || !Host.HasAppraisalData(e.Id)) - && _equipIdRequested.Add(e.Id)) + && !_equipIdRequested.Contains(e.Id)) { - Host.RequestId(e.Id); // appraisal 0xC9 lands in the engine cache; read it next pass + // Remembered only when the engine took it: it refuses around a death or a portal, and a refused + // request marked as done would never be asked again. Appraisal 0xC9 lands in the engine cache; + // read it next pass. + if (Host.RequestId(e.Id)) _equipIdRequested.Add(e.Id); idRequests++; } var a = new EquipAppraisal { Name = e.Name, Id = e.Id, Slot = e.Slot }; @@ -1652,7 +1707,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase RynthCore.Plugin.Shared.ActionPacer.NoteFrame(); // Stuck Cast Break, once per tick: the breaker runs for every subsystem's casts. if (_dashboard?.Settings is { } paceSettings) + { RynthCore.Plugin.Shared.ActionPacer.StuckCastMs = Math.Max(0, paceSettings.StuckCastBreakMs); + NoteMacroForPacer(paceSettings.IsMacroRunning); + } NotePortalForPacer(); if (HoldForDeath()) return; @@ -2305,6 +2363,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase else _dashboard?.PushChatLine(text, chatType); OnChatLocalFeatures(text, chatType, ref eat); try { NoteHotspotChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Hazard chat check failed: {ex.Message}"); } + try { NoteGiveChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Give chat check failed: {ex.Message}"); } _buffManager?.OnChatWindowText(text, chatType); _manaStoneManager?.OnChatWindowText(text); _salvageManager?.OnChatWindowText(text); @@ -2312,6 +2371,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager?.TraceCastChat(text, chatType); _combatManager?.HandleChatForDebuffs(text); _combatManager?.HandleChatForDamage(text, chatType); + _combatManager?.HandleChatForRingEvade(text, chatType); _missileCraftingManager?.HandleChat(text); _scrollLearner?.OnChat(text); _metaManager?.HandleChat(text, chatType); @@ -2354,7 +2414,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { try { _combatManager?.OnObjectCreated(objectId); } catch { } _sessionStats?.OnCreateObject(objectId); - try { _objectCache?.OnCreateObject(objectId); } + try + { + _objectCache?.OnCreateObject(objectId); + _combatManager?.OnEnvironmentObjectCreated(objectId); // spell projectiles for the environment-impact throttle + } catch (Exception ex) { Host.Log($"[RynthAi] OnCreateObject EXCEPTION on id=0x{objectId:X8}: {ex.GetType().Name}: {ex.Message}"); @@ -3397,75 +3461,353 @@ public sealed partial class RynthAiPlugin : RynthPluginBase internal void CancelGiveQueue() { - int count = _pendingGives.Count; + var redo = _giveRedo; + int count = _pendingGives.Count + (redo.HasValue ? 1 : 0); _pendingGives.Clear(); - _giveInFlightId = 0; + ResetGiveState(); ChatLine(count > 0 ? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)." : "[RynthAi] Give queue is already empty."); } + /// Drops the in-flight give, the redo slot and the run summary (cancel, logout). + private void ResetGiveState() + { + _giveInFlightId = 0; + _giveRedo = null; + _giveBusyRetryAt = 0; + _giveBusySince = 0; + _giveBusyCount = 0; + _giveGoneStreak = 0; + _giveReadFailId = 0; + Interlocked.Exchange(ref _giveChatVerdict, 0); + _giveRunActive = false; + _giveRunItems = 0; + _giveRunSkips.Clear(); + } + /// - /// 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. + /// Classifies a chat line as an answer to the in-flight give. Lowercase substrings: the client + /// renders WeenieError text from its own string table, so only the server's custom strings + /// ("Item not found!", "Target not found!", "Give amount not valid!") are exact. + /// + private static GiveChat ClassifyGiveChat(string text) + { + string t = text.ToLowerInvariant(); + // Busy class first: " is too busy to accept gifts" must not read as "not accepting gifts". + if (t.Contains("too busy") || t.Contains("is busy right now")) return GiveChat.Busy; + if (t.Contains("item not found")) return GiveChat.ItemNotFound; + if (t.Contains("give amount not valid") || t.Contains("target not found") + || t.Contains("doesn't want") || t.Contains("does not want") + || t.Contains("not accepting gifts") || t.Contains("cowers from you")) + return GiveChat.Permanent; + return GiveChat.None; + } + + /// + /// Speech, tells and emotes are other players' words, never the server's answer to a give. The text + /// shape is the real guard. Chat type 17 is the client's Spellcasting type (spell words, ours and + /// other casters': "chat type=17 ... says, "Zojak Ves""), which is never an answer either, so it is + /// skipped too; system notices such as "You give ..." arrive as 0. + /// + private static bool IsGiveChatSpeech(string text, int chatType) + { + if (chatType == 17) return true; + string t = text.ToLowerInvariant(); + return t.Contains(" says, \"") || t.Contains(" tells you, \"") || t.Contains(" asks, \"") + || t.Contains(" exclaims, \"") || t.Contains(" yells, \"") || t.Contains(" whispers, \"") + || t.StartsWith("you say, ", StringComparison.Ordinal) || t.StartsWith("you tell ", StringComparison.Ordinal) + || t.StartsWith("you whisper", StringComparison.Ordinal) || t.StartsWith("you exclaim", StringComparison.Ordinal) + || t.StartsWith("you yell", StringComparison.Ordinal) || t.StartsWith("you ask", StringComparison.Ordinal); + } + + /// + /// OnChatWindowText: only records the verdict; every send happens in DrainGiveQueue. The engine + /// dispatches chat from ProcessPendingActions and the plugin tick from TickAll, back to back in + /// one driver (EntryPoint.cs:1120-1122, ImGui/EngineFrameController.cs:461-467 in RynthCore-autoid), + /// so this is one thread in practice; the verdict still goes through Interlocked. + /// + private void NoteGiveChat(string text, int chatType = 0) + { + if (_giveInFlightId == 0) return; + if (IsGiveChatSpeech(text, chatType)) return; + if (text.StartsWith("You give ", StringComparison.Ordinal)) { _giveSawAcceptLine = true; return; } + var kind = ClassifyGiveChat(text); + if (kind == GiveChat.None) + { + // Types 1 (RynthAi's own lines), 7 (magic) and 17 (spell words) are never worth a slot. + if (_giveUnclassified < 10 && chatType != 1 && chatType != 7 && !text.StartsWith("[", StringComparison.Ordinal)) + { + _giveUnclassified++; + Host.Log($"[Give] unclassified chat: type={chatType} '{text}'"); + } + return; + } + // The first verdict noted for this give stands until the tick takes it. + if (Interlocked.CompareExchange(ref _giveChatVerdict, (int)kind, 0) == 0) _giveChatLine = text; + } + + /// + /// One give at a time, answered before the next goes out (ACE cancels a move chain when a second + /// give arrives, and answers extras "too busy"). An answer is the item leaving the pack or its + /// stack shrinking: an NPC with a Give emote takes ONE item per give, so a shrunk stack goes + /// again at once, in the same tick. Busy refusals re-send after GiveBusyRetryMs, for up to GiveBusyGiveUpMs in total; + /// permanent refusals skip the stack. No answer at all in GiveConfirmMs re-sends, up to + /// GiveMaxTries, then skips. GiveQueueIntervalMs is only a minimum gap between two sends. /// private void DrainGiveQueue() { - long now = Environment.TickCount64; + long now = GiveNow(); 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 (!ResolveGiveInFlight(now)) return; } - if (_pendingGives.Count == 0) return; - int intervalMs = _dashboard?.Settings.GiveQueueIntervalMs ?? 150; - if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return; + var redo = _giveRedo; + if (!redo.HasValue && _pendingGives.Count == 0) + { + FinishGiveRun(now); + return; + } + int intervalMs = Math.Max(0, _dashboard?.Settings.GiveQueueIntervalMs ?? 0); + if (intervalMs > 0 && _giveLastSendAt != long.MinValue && now - _giveLastSendAt < intervalMs) return; - var (itemId, targetId, stackSize) = _pendingGives.Dequeue(); - // The queued amount is what to hand over; GiveItem gives the whole object when it is - // the whole stack (amount 0) and uses AC's real give action, which an NPC accepts. - 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; + uint itemId, targetId; + int amount; + if (redo.HasValue) + { + (itemId, targetId, amount) = redo.Value; + _giveRedo = null; + } + else + (itemId, targetId, amount) = _pendingGives.Dequeue(); + if (!_giveRunActive) + { + _giveRunActive = true; + _giveRunStartAt = now; + _giveRunLastAnswerAt = now; + _giveRunItems = 0; + _giveRunSkips.Clear(); + } + if (!SendGive(itemId, targetId, amount, 1, resent: false, now)) + _giveRedo = (itemId, targetId, amount); // unreadable stack: first in line again next tick } - /// The in-flight give went through: the item left the inventory, or part of its stack did. - private bool GiveLanded() + /// + /// Settles the in-flight give. Returns true when it is done (landed or skipped) and the tick may + /// send the next give now; false when the tick must stop (still waiting, or a re-send just went out). + /// + private bool ResolveGiveInFlight(long now) { - 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; + long sinceSend = now - _giveInFlightAt; + string tag = $"0x{_giveInFlightId:X8} '{_giveInFlightName}'"; + + // 1. Progress: the item left the pack, or its stack shrank. A failed read is "no information": + // the stack count reads -1 (never a clamped 1, which looked like a shrink of 99), and an + // unreadable object (no cache entry, Container 0) must read the same on two ticks in a row. + var wo = _objectCache?[unchecked((int)_giveInFlightId)]; + // Where it is: in the pack (the player, or a pack the player carries), with the give target (gone), + // or somewhere we cannot place. A container that is neither the player nor the target and whose own + // container reads 0 is unreadable, not gone. + int cont = wo?.Container ?? 0; + bool readable = wo != null && cont != 0; + bool carried = false; + if (readable) + { + int playerInt = unchecked((int)_playerId); + if (cont == playerInt) carried = true; + else if (cont != unchecked((int)_giveInFlightTarget)) + { + int outer = _objectCache?.GetContainerId(cont) ?? 0; + if (outer == 0) readable = false; + else carried = outer == playerInt; + } + } + int stackNow = wo != null ? wo.Values(LongValueKey.StackCount, -1) : -1; + bool gone; + if (readable && !carried) { gone = true; _giveGoneStreak = 0; } + else if (readable) { gone = false; _giveGoneStreak = 0; } + else + { + _giveGoneStreak++; + gone = _giveGoneStreak >= 2; + } + if (gone) + { + int given = Math.Max(1, Math.Min(_giveInFlightRemaining, _giveInFlightStack)); + Host.Log($"[RynthAi] Give answer: gone {tag} +{given} item(s) after {sinceSend} ms (accept line seen: {_giveSawAcceptLine})"); + CompleteGiveStack(given, now); + return true; + } + if (carried && stackNow >= 0 && stackNow < _giveInFlightStack) + { + int delta = _giveInFlightStack - stackNow; + int remaining = _giveInFlightRemaining - delta; + Host.Log($"[RynthAi] Give answer: shrink {tag} {_giveInFlightStack}->{stackNow} after {sinceSend} ms (accept line seen: {_giveSawAcceptLine})"); + _giveRunItems += delta; + _giveRunLastAnswerAt = now; + uint shrunkId = _giveInFlightId; + _giveInFlightId = 0; + _giveBusyRetryAt = 0; + _giveBusySince = 0; + if (remaining > 0) + _giveRedo = (shrunkId, _giveInFlightTarget, remaining); + return true; + } + + // 2. A chat verdict. + var chat = (GiveChat)Interlocked.Exchange(ref _giveChatVerdict, 0); + if (chat == GiveChat.ItemNotFound) + { + // "Item not found" after a re-send means the earlier send landed, but only if the pack agrees: + // gone (or unreadable) counts as given; still carried with the same stack is a plain skip. + if (_giveInFlightResent && !carried) + { + int given = Math.Max(1, _giveInFlightRemaining); + Host.Log($"[RynthAi] Give answer: item-not-found after a re-send, item gone, counted as given {tag} +{given} item(s) after {sinceSend} ms"); + CompleteGiveStack(given, now); + return true; + } + Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms"); + SkipGiveStack("item not found", tag, now); + return true; + } + if (chat == GiveChat.Permanent) + { + Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms"); + SkipGiveStack("refused", tag, now); + return true; + } + if (chat == GiveChat.Busy) + { + _giveBusyCount++; + if (_giveBusySince == 0) { _giveBusySince = now; _giveBusyNoticeAt = now; } + if (now - _giveBusySince >= GiveBusyGiveUpMs) + { + // A target that stays busy (a player in a trade) would otherwise be re-sent, and answer + // "too busy" in the player's chat, every GiveBusyRetryMs for ever. + Host.Log($"[RynthAi] Give answer: busy #{_giveBusyCount} {tag} for {now - _giveBusySince} ms; giving up"); + string? busyWho = _objectCache?[unchecked((int)_giveInFlightTarget)]?.Name; + ChatLine($"[RynthAi] Give: {(string.IsNullOrEmpty(busyWho) ? "the target" : busyWho)} stayed busy for {(now - _giveBusySince) / 1000} s - skipping 0x{_giveInFlightId:X8}."); + SkipGiveStack("busy too long", tag, now); + return true; + } + if (_giveBusyCount == 1 || _giveBusyCount % 10 == 0) + Host.Log($"[RynthAi] Give answer: busy #{_giveBusyCount} {tag} '{_giveChatLine}' after {sinceSend} ms; re-sending in {GiveBusyRetryMs} ms"); + if (now - _giveBusyNoticeAt >= GiveBusyNoticeMs) + { + _giveBusyNoticeAt = now; + string? who = _objectCache?[unchecked((int)_giveInFlightTarget)]?.Name; + ChatLine($"[RynthAi] Give: {(string.IsNullOrEmpty(who) ? "the target" : who)} is busy - still retrying (/ra givea stop to cancel)."); + } + _giveBusyRetryAt = now + GiveBusyRetryMs; + } + if (_giveBusyRetryAt != 0) + { + if (now < _giveBusyRetryAt) return false; + _giveBusyRetryAt = 0; + if (!SendGive(_giveInFlightId, _giveInFlightTarget, _giveInFlightAll ? 0 : _giveInFlightRemaining, _giveInFlightTries, resent: true, now)) + _giveBusyRetryAt = now; // unreadable stack: try again next tick + return false; + } + + // 3. No answer at all. + if (sinceSend < GiveConfirmMs) return false; + if (_giveInFlightTries < GiveMaxTries) + { + Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; re-sending"); + if (!SendGive(_giveInFlightId, _giveInFlightTarget, _giveInFlightAll ? 0 : _giveInFlightRemaining, _giveInFlightTries + 1, resent: true, now)) + { + _giveInFlightTries++; // this was a try even though nothing went out: GiveMaxTries stays a cap on sends + _giveBusyRetryAt = now; // unreadable stack: try again next tick + } + return false; + } + Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; giving up"); + ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it."); + SkipGiveStack("no answer", tag, now); + return true; + } + + private void CompleteGiveStack(int items, long now) + { + _giveRunItems += items; + _giveRunLastAnswerAt = now; + _giveInFlightId = 0; + _giveReadFailId = 0; + _giveBusyRetryAt = 0; + _giveBusySince = 0; + } + + private void SkipGiveStack(string why, string tag, long now) + { + _giveRunSkips.Add($"{tag}: {why}"); + Host.Log($"[RynthAi] Give skip: {tag} ({why})"); + _giveRunLastAnswerAt = now; + _giveInFlightId = 0; + _giveReadFailId = 0; + _giveBusyRetryAt = 0; + _giveBusySince = 0; + } + + /// + /// Sends one give and records it as the in-flight one. is the items still to hand over; + /// 0 (or less) is a genuine "give all", the only request that may go out as a whole-object give when the stack + /// count cannot be read. An explicit amount, 1 included, always goes out as that explicit amount. + /// + private bool SendGive(uint itemId, uint targetId, int amount, int tries, bool resent, long now) + { + WorldObject? wo = _objectCache?[unchecked((int)itemId)]; + int read = wo != null ? wo.Values(LongValueKey.StackCount, -1) : -1; + // A failed read on a stackable item (MaxStackSize above 1) is no information: nothing is sent this + // tick, and the caller tries again next tick. A read that keeps failing for GiveReadFailMs must not + // hold the queue for ever: then the give goes out anyway, as the explicit amount asked for (1 included: + // a "give 1" of a stack that is really 99 must not hand over all 99) or, for a genuine give-all, as a + // plain give, and says so in the log. + bool all = amount <= 0; + if (read < 0 && wo != null && wo.Values(LongValueKey.MaxStackSize, -1) > 1) + { + if (_giveReadFailId != itemId) { _giveReadFailId = itemId; _giveReadFailSince = now; } + if (now - _giveReadFailSince < GiveReadFailMs) return false; + Host.Log($"[RynthAi] Give: stack count of 0x{itemId:X8} '{wo.Name}' unreadable for {now - _giveReadFailSince} ms; sending anyway ({(all ? "plain give" : $"amount {amount}")})"); + } + else _giveReadFailId = 0; + // Here a negative read means a non-stackable item, an unknown one, or a stackable whose count stayed + // unreadable: record max(1, amount) as its stack. An explicit amount is sent as that explicit amount + // (an explicit 1 is what the engine sends for a single item anyway); only a give-all goes out whole. + int whole = read >= 0 ? Math.Max(1, read) : Math.Max(1, amount); + string name = wo?.Name ?? string.Empty; + _giveInFlightId = itemId; + _giveInFlightTarget = targetId; + _giveInFlightRemaining = read < 0 ? Math.Max(1, amount) : (amount <= 0 || amount > whole ? whole : amount); + _giveInFlightStack = whole; + _giveInFlightAll = all; + _giveInFlightTries = tries; + _giveInFlightResent = resent; + _giveInFlightName = name; + _giveInFlightAt = now; + _giveLastSendAt = now; + Interlocked.Exchange(ref _giveChatVerdict, 0); + _giveSawAcceptLine = false; + _giveGoneStreak = 0; + if (!resent) { _giveBusyCount = 0; _giveBusySince = 0; _giveUnclassified = 0; } + GiveItem(itemId, targetId, amount, read >= 0 ? whole : (all ? 0 : amount + 1)); // amount + 1: GiveItem must not fold an explicit amount into a whole give + Host.Log($"[RynthAi] Give send: 0x{itemId:X8} '{name}' stack={(read >= 0 ? whole.ToString() : "?")} amount={amount} try={tries}{(resent ? " (re-send)" : string.Empty)}"); + return true; + } + + private void FinishGiveRun(long now) + { + if (!_giveRunActive) return; + _giveRunActive = false; + long elapsed = Math.Max(0, _giveRunLastAnswerAt - _giveRunStartAt); + string avg = _giveRunItems > 0 ? $"{elapsed / _giveRunItems} ms" : "n/a"; + string why = _giveRunSkips.Count == 0 ? string.Empty : $" ({string.Join("; ", _giveRunSkips)})"; + string line = $"[RynthAi] Give queue complete: {_giveRunItems} item(s) given, {_giveRunSkips.Count} stack(s) skipped{why}, {elapsed / 1000.0:0.0}s total, {avg} per give."; + Host.Log(line); + ChatLine(line); + _giveRunItems = 0; + _giveRunSkips.Clear(); } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index 2eeaf02..50036ba 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -60,6 +60,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeManager.cs index ebc0f43..8ab5312 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeManager.cs @@ -636,7 +636,7 @@ internal sealed class AutoTradeManager { _idState.TryGetValue(id, out var st); if (st.Attempts > 0 && now - st.LastAt < IdResendMs) continue; - _host.RequestId(id); + if (!_host.RequestId(id)) break; // refused (a death or a portal): not an attempt, asked again next tick _idState[id] = (st.Attempts + 1, now); _lastIdSentAt = now; break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs index b023789..152e4b4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs @@ -564,7 +564,7 @@ internal sealed class AutoVendorManager { _idState.TryGetValue(id, out var st); if (st.Attempts > 0 && now - st.LastAt < IdResendMs) continue; - _host.RequestId(id); + if (!_host.RequestId(id)) break; // refused (a death or a portal): not an attempt, asked again next tick _idState[id] = (st.Attempts + 1, now); _lastIdSentAt = now; break; diff --git a/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs b/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs index 7f6b492..4521a58 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs @@ -75,7 +75,7 @@ internal sealed class ChatBuffer if (string.IsNullOrEmpty(text)) return; string channel = ChatClassifier.IsItemInfo(text) ? ChatClassifier.Items : ChatClassifier.IsRynthOutput(text) ? ChatClassifier.Rynth - : ChatClassifier.ChannelFor(chatType); + : ChatClassifier.ChannelFor(text, chatType); string? sender = ChatClassifier.SenderFor(text, chatType); string ts = DateTime.Now.ToString("HH:mm:ss"); diff --git a/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs b/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs index 02cc6a0..b150bfc 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs @@ -34,17 +34,46 @@ internal static class ChatClassifier // ── Channel classification ───────────────────────────────────────────── - internal static string ChannelFor(int chatType) => (uint)chatType switch + /// + /// Channel tab for a line. Prefer the text's [General]/[Trade]/… tag when present — + /// ILT (and some ACE builds) deliver those as type 0x1C / 28 instead of 0x08/0x09, which + /// used to dump Trade/General into Other and leave the Channels tab empty. + /// + internal static string ChannelFor(string? text, int chatType) + { + if (IsChannelTagged(text)) return Channels; + return ChannelForType(chatType); + } + + /// Legacy type-only map (tests / callers without the line text). + internal static string ChannelFor(int chatType) => ChannelForType(chatType); + + internal static string ChannelForType(int chatType) => (uint)chatType switch { 0x02 or 0x03 or 0x04 or 0x0A or 0x0B or 0x0C or 0x12 or 0x13 => Chat, - 0x08 or 0x09 => Channels, + 0x08 or 0x09 or 0x1C => Channels, 0x00 or 0x05 or 0x0D or 0x14 or 0x17 or 0x18 or 0x19 or 0x1F => System, 0x06 or 0x07 or 0x11 or 0x15 or 0x16 => Combat, _ => Other, }; + /// True when the line opens with a retail/ILT channel tag ([Trade], [General], …). + internal static bool IsChannelTagged(string? text) + { + if (string.IsNullOrEmpty(text) || text[0] != '[') return false; + return text.StartsWith("[General]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Trade]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[LFG]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Roleplay]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Society]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Celestial Hand]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Eldrytch Web]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Radiant Blood]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Admin]", StringComparison.OrdinalIgnoreCase); + } + internal static uint ColorFor(string channel) => channel switch { Chat => 0xFFE0E0E0, diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj index 5082e4a..8b1faa3 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj @@ -9,7 +9,7 @@ DreamWeave play.acdreamweave.com DreamWeave|Dream Weave - DreamWeave only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + DreamWeave only: the server card (rules, server features, player commands, links, account setup) in the Mini Remote. diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs index 83422c8..e17a30b 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs @@ -1,4 +1,7 @@ // ServerData.cs - What is known about DreamWeave (RynthDreamWeave). Identity (id, hosts, world names) is in the csproj. +// The features and commands come from the server's public source (ACE-DreamWeave: its README and the +// player-level chat commands under Source/ACE.Server/Command/Handlers). Stock ACE commands and the +// stage-test-shard grants (/myxp, /mylum, ...) are left out. namespace RynthCore.Plugin.ServerPack; internal static class ServerData @@ -17,9 +20,57 @@ internal static class ServerData "Lore driven, built on end-of-retail Throne of Destiny.", "New class abilities and a new crafting system.", "Its wiki is kept up to date.", + "Class abilities: trainers sell ability tokens for class ability points (/abilities, /cavoucher).", + "Equipment and weapon mods on armor, clothing and jewelry (/mods).", + "Facets: several builds per character, including a PK facet (/facet).", + "In-game bank for pyreals, luminance, legendary keys, promissory and trade notes (/bank).", + "Account vault (mule) with its own vendor, shared with characters you choose (/mule).", + "Player market: browse, list and buy items (/market).", + "Realms and ephemeral instances (/realm, /exitinst).", + "Drift Network: a hall of linked drift-doors, recalled to with /dn (/tn for the retail Town Network).", + "Threads dungeons (/dd) and treasure-map dig sites (/digsite, /rrtm).", + "PvP arenas (1v1, 2v2, Tugak Brawl free-for-all) and battlegrounds on templates, with ratings (/arena).", + "Leaderboards for DPS, defense, waves, speed, level, bank, stamps, threads and PvP (/top).", + "XP, luminance and custom augmentations (/aug).", + "Experience bonuses: gear, augmentations, alt-character catch-up and offline (/bonus).", + "Fast tick opt-in: faster spell release, fast-chug and melee stick-to-target (/fasttick).", + "Web character sheet you can publish (/charsheet).", + }, + Commands = new[] + { + new ServerCommand("/bank", "deposit, withdraw, transfer and check banked currency (/b d deposits everything)"), + new ServerCommand("/mule", "summon your account vault's vendor, or manage who can use it"), + new ServerCommand("/market", "browse, list and buy items on the market"), + new ServerCommand("/abilities", "manage your class abilities"), + new ServerCommand("/cavoucher", "buy a class ability token for ability points, or refund an unused one"), + new ServerCommand("/facet", "show your facets; /facet switches build, /facet pk the PK facet"), + new ServerCommand("/mods", "summarize the equipment mods on what you wear"), + new ServerCommand("/aug", "augmentation list: /aug xp, /aug lum or /aug custom"), + new ServerCommand("/dn", "recall to the Drift Network (moving too far interrupts it)"), + new ServerCommand("/tn", "recall to the retail Town Network"), + new ServerCommand("/realm", "which realm and instance you are in"), + new ServerCommand("/exitinst", "leave the current ephemeral instance"), + new ServerCommand("/dd", "Threads dungeon status"), + new ServerCommand("/digsite", "status of the dig site you are at; /digsite bail ends one you dug"), + new ServerCommand("/rrtm", "reroll a treasure map's dig site to the one nearest you"), + new ServerCommand("/arena", "PvP arena: /arena join 1v1|2v2|tugak|bg, templates, status, rating, top"), + new ServerCommand("/top", "leaderboards: dps, defense, wave, speed, level, bank, stamp, thread, 1v1, 2v2, tugak, bg"), + new ServerCommand("/xp", "your experience progress"), + new ServerCommand("/quests", "your quest stamp progress"), + new ServerCommand("/bonus", "every experience bonus you have and the total (/altbonus, /offlinebonus)"), + new ServerCommand("/lph", "luminance per hour since login, or since /lph start"), + new ServerCommand("/pickupspeed", "your pick-up speed bonus, including permanent quest bonuses"), + new ServerCommand("/fasttick", "fast tick on, off, default or status"), + new ServerCommand("/dotdamage", "show or hide your damage-over-time tick messages"), + new ServerCommand("/summondamage", "show or hide a chat line for each hit your pets land"), + new ServerCommand("/summonattackontarget", "pets switch to the monster you last hit (on or off)"), + new ServerCommand("/relaria", "Aun Relaria repeat-kill aura visual: /relaria aura on|off"), + new ServerCommand("/charsheet", "publish a web character sheet (off, rotate)"), + new ServerCommand("/fi", "resend nearby monsters and NPCs (invisible creatures), once a minute"), }, Discord = "https://discord.gg/p2h3yca4BD", Wiki = "https://wiki.acdreamweave.com", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13; features and commands from " + + "github.com/Awful-Waffle-Rofl/ACE-DreamWeave (4aa7de6), checked 2026-10-14", }; } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs index 54b3076..1275f5e 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs @@ -17,6 +17,11 @@ // refresh doesn't, so it has its own (client-side) spacing. // Balance lines are parsed whenever they appear (player-typed /bank too) but only EATEN // when the Hub asked. Transfers always need a confirmation (UB had none). +// Backstop (SilentKelpie's PR 12, narrowed): the capture queue eats a quiet refresh's reply, but if +// it misses, balance-dump lines arriving within QuietBalanceWindowMs of a quiet refresh are eaten +// here. Only the dump itself (header and "Label: N" lines): other [BANK] lines (errors, bound-coin +// notes), Transferred / Received lines, and balance reads nobody here asked for (a macro's or another +// plugin's /bank, outside the window) are left alone. using System; using System.Collections.Generic; using System.Linq; @@ -57,6 +62,10 @@ internal sealed class IltBanking : IIltFeature private long _moveUntil; /// How long after a deposit / withdrawal reply the moved amounts are not income (covers the balance re-read). private const long MoveWindowMs = 12_000; + /// Until this tick, a balance dump that reaches chat is the reply to a quiet Hub refresh (0 = no quiet refresh out). + private long _quietBalanceUntil; + /// How long after a quiet refresh is queued its leaked dump lines are still eaten here. + internal const long QuietBalanceWindowMs = 15_000; // Render-thread form state. private string _amountText = string.Empty; @@ -124,6 +133,7 @@ internal sealed class IltBanking : IIltFeature long now = IltHubContext.NowMs; if (now - _lastBalanceAt < BalanceSpacingMs) return; _lastBalanceAt = now; + _quietBalanceUntil = quiet ? now + QuietBalanceWindowMs : 0; _ctx.Capture.Enqueue(new IltChatRequest { Command = "/bank", @@ -293,8 +303,9 @@ internal sealed class IltBanking : IIltFeature { if (text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)) { - ParseBalanceLine(text); - return false; // eating is decided by the capture queue + bool dump = ParseBalanceLine(text); + // Eating is decided by the capture queue; this only backs it up for a quiet refresh's dump. + return EatLeakedDump(dump, IltHubContext.NowMs, _quietBalanceUntil); } // A deposit or withdrawal reply (ours or a typed /b): the next balance and pack changes are moves. if (text.StartsWith("Deposited ", StringComparison.Ordinal) || text.StartsWith("Withdrew ", StringComparison.Ordinal)) @@ -310,27 +321,67 @@ internal sealed class IltBanking : IIltFeature // ── Parsing ───────────────────────────────────────────────────────────── - private void ParseBalanceLine(string text) + /// + /// True when a quiet refresh's dump line that reached chat should be eaten here: it is a balance + /// line (see ) and a quiet refresh was queued within the window. + /// + internal static bool EatLeakedDump(bool isBalanceLine, long nowMs, long quietUntilMs) + => isBalanceLine && quietUntilMs != 0 && nowMs < quietUntilMs; + + /// The balance key a dump label belongs to ("Weakly Enlightened Coins" -> WeaklyEnlightenedCoins), or null. + internal static string? BalanceKeyFor(string label) { + // Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins". + if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) return "PrestigeCoins"; + if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) return "WeaklyEnlightenedCoins"; + if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) return "EnlightenedCoins"; + if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) return "MythicalKeys"; + if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) return "LegendaryKeys"; + if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) return "Luminance"; + if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) return "Pyreals"; + return null; + } + + /// + /// True when a "[BANK] ..." line is part of the /bank balance dump: the "Your balances are:" header + /// or a "Label: N" line for a known currency. Errors, the bound-coin note and the like are not. + /// + internal static bool IsBalanceDumpLine(string text) + { + if (!text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)) return false; + string body = text.Substring("[BANK]".Length).Trim(); + if (body.StartsWith("Your balances", StringComparison.OrdinalIgnoreCase)) return true; + int colon = body.IndexOf(':'); + if (colon <= 0) return false; + if (body.Substring(colon + 1).Trim().Length == 0) return true; // a header ending in a colon + return BalanceKeyFor(body.Substring(0, colon).Trim()) != null; + } + + /// Reads a "[BANK] ..." line into the balances. Returns . + private bool ParseBalanceLine(string text) + { + if (!IsBalanceDumpLine(text)) return false; string body = text.Substring("[BANK]".Length).Trim(); int colon = body.IndexOf(':'); - if (colon <= 0) return; + if (colon <= 0 || body.Substring(colon + 1).Trim().Length == 0) return true; // a header: nothing to read string label = body.Substring(0, colon).Trim(); long value = IltParse.ParseLeadingLong(body.Substring(colon + 1)); - if (body.Substring(colon + 1).Trim().Length == 0) return; // header "Your balances are:" - // Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins". - if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) Apply("PrestigeCoins", ref Bank.PrestigeCoins, value); - else if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value); - else if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value); - else if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) Apply("MythicalKeys", ref Bank.MythicalKeys, value); - else if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) Apply("LegendaryKeys", ref Bank.LegendaryKeys, value); - else if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) Apply("Luminance", ref Bank.Luminance, value); - else if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) Apply("Pyreals", ref Bank.Pyreals, value); - else return; + switch (BalanceKeyFor(label)) + { + case "PrestigeCoins": Apply("PrestigeCoins", ref Bank.PrestigeCoins, value); break; + case "WeaklyEnlightenedCoins": Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value); break; + case "EnlightenedCoins": Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value); break; + case "MythicalKeys": Apply("MythicalKeys", ref Bank.MythicalKeys, value); break; + case "LegendaryKeys": Apply("LegendaryKeys", ref Bank.LegendaryKeys, value); break; + case "Luminance": Apply("Luminance", ref Bank.Luminance, value); break; + case "Pyreals": Apply("Pyreals", ref Bank.Pyreals, value); break; + default: return false; + } Bank.LastUpdated = DateTime.Now; _ctx.Options.Set(IltFeature.Bank, IltTri.On); + return true; } private void Apply(string key, ref long field, long value) diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs index 31f3b48..c3190ca 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs @@ -1,19 +1,34 @@ // IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab). // Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. // -// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time: +// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time. The rules follow ub-IT +// (Leaftide AetheriaChunkGuard / IsValidCorruptedWep / CorruptedChunkGuard): // Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged -// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), no kept -// C / CD / CDR rating (gear ints 372 / 374 / 375; on by default), and max level -// (int 319, up to 10 on ILT) under the configured cap (Coalesced always qualifies). -// Corrupted — "Corrupted" melee/missile weapons with no tinks (171), no imbue (179), -// not equipped, not never-chunk, cleave (292) <= 1. -// Peace mode only unless ChunkInCombat; waits for the result line (10 s max). +// never-chunk (bool 9030), not tinkered (171) or imbued (179), never levelled +// (ItemTotalXp quad 4 == 0), no kept C / CD / CDR rating (gear ints 372 / 374 / 375; +// on by default; only a rating at or above the "rating level" keeps, a lower one +// chunks), and max level (int 319, up to 10 on ILT) under the configured cap. +// A levelled Coalesced piece gets the cap too; an unlevelled one (319 = 0 after +// appraisal, normal for Coalesced) is chunkable, as in ub-IT. RynthILT used to keep +// every unlevelled Coalesced piece forever. +// Corrupted — "Corrupted" melee/missile weapons, not equipped, not never-chunk, no tinks (171), +// no imbue (179), loot-gen workmanship (105) > 0, and cleave (292) <= 1, or <= 2 on a +// two-handed weapon that is not a thrust weapon (RynthILT used to cap every weapon +// at 1, so no two-handed corrupted weapon was ever chunked). Optional keep rules +// (Crushing Blow, Biting Strike, Armor Cleaving, slayer, multi-strike, elemental +// bonus, any spell, max damage, spell ids) are all off by default. +// Peace mode only unless ChunkInCombat. With ChunkInCombat on, a busy client in combat mode no +// longer blocks the hammer (a swinging bot is always busy); peace mode still waits for idle. +// Waits for the result line (10 s max); a target that leaves the pack first counts as chunked +// (ILT does not always send a known line). Each item's skip reason is logged when it changes +// and tallied in the status line. // The tool is the "Lugian Aetheria Hammer" only. The Lugian Hammer weapons (Flaming, Acid, ...) // are loot and chunk nothing: the server answers with no result line, so every item timed out // into the skip list and the status sat on "nothing eligible" (SilentKelpie, 2026-10-15). -// Clap: "/clap all" converts aetheria chunks + trinkets into coins server-side. Needs the -// AutoCraftingEnabled stamp; 30 min ± 2 min interval, first attempt ~1 min after enable. +// Clap: "/clap all" converts aetheria + trinkets into coins server-side: red (Coalesced level 1-3, +// chunks, powder) with Empyrean Trinkets, blue with Falatacot Trinkets. Auto-clap sends it only +// when a pair is carried. Needs the AutoCraftingEnabled stamp; 30 min ± 2 min interval, first +// attempt ~1 min after enable. using System; using System.Collections.Generic; using System.Linq; @@ -53,6 +68,10 @@ internal sealed class IltChunkClap : IIltFeature private bool _manualPass; private volatile string _chunkStatus = "idle"; private int _chunked; + // Last skip reason per item, so each reason is logged once instead of every pass. + private readonly Dictionary _lastSkip = new(); + // Skip reasons of the current pass (reason -> items), shown in the status line. + private readonly Dictionary _passSkips = new(); // Clap state private long _nextClapAt; @@ -74,59 +93,264 @@ internal sealed class IltChunkClap : IIltFeature private WorldObject? FindHammer() => _ctx.Inventory.Items().FirstOrDefault(wo => IsChunkHammer(wo.Name) && !_ctx.Inventory.IsEquipped(wo)); - /// True/false when decidable; null when appraisal is still needed. - private bool? IsChunkableAetheria(WorldObject wo) + /// Item kinds the hammer works on (the name and class gate, before any appraisal). + internal enum ChunkKind { None, Aetheria, Corrupted } + + /// + /// Which chunk rules an item falls under, by class and name only. Aetheria chunks and powder + /// are clap material, not hammer targets. Pure: the tests drive it. + /// + internal static ChunkKind KindOf(AcObjectClass cls, string name) + { + if (cls == AcObjectClass.Gem) + { + if (name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase)) return ChunkKind.Aetheria; + if (name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase) + && !name.Contains("Chunk", StringComparison.OrdinalIgnoreCase) + && !name.Contains("Powder", StringComparison.OrdinalIgnoreCase)) + return ChunkKind.Aetheria; + return ChunkKind.None; + } + if (cls is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon + && name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase)) + return ChunkKind.Corrupted; + return ChunkKind.None; + } + + /// An aetheria piece's chunk facts, read after appraisal. + internal readonly record struct AetheriaFacts( + bool Coalesced, int MaxLevel, bool NeverChunk, long ItemXp, int Tinkers, int Imbue, + int Crit, int CritDamage, int CritDamageResist, string? Unreadable = null); + + /// + /// Why an aetheria piece is kept, or null when it may be chunked (ub-IT AetheriaChunkGuard plus + /// RynthILT's C / CD / CDR keep switches). Pure: the tests drive it. + /// + /// is set when the item's properties could not be read (the + /// host lacks a reader or the appraisal never arrived). A property that failed to read looks + /// exactly like one the item lacks (level 0, no XP, no tinks), so such a piece is kept: an + /// "unlevelled" Coalesced piece is only chunked when its level was truly read as none. + /// + /// + internal static string? AetheriaSkip(IltGearState g, in AetheriaFacts f) + { + if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})"; + if (f.NeverChunk) return "never-chunk flag"; + if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued"; + if (f.ItemXp != 0) return "has item XP"; + if (KeptForRatings(g, f.Crit, f.CritDamage, f.CritDamageResist)) return "kept for its C / CD / CDR rating"; + if (!UnderChunkCap(f.MaxLevel, g.ChunkAetheriaUnderLevel, f.Coalesced)) + return f.MaxLevel > 0 ? "level at or above the cap" : "no level read"; + return null; + } + + /// Why an aetheria item is kept (null = chunk it); "appraising" while its data is missing. + private string? AetheriaSkip(WorldObject wo) { - if (wo.ObjectClass != AcObjectClass.Gem) return false; - bool coalesced = wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase); - if (!coalesced && (!wo.Name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase) || wo.Name.Contains("Chunk", StringComparison.OrdinalIgnoreCase))) - return false; var inv = _ctx.Inventory; - if (inv.IsEquipped(wo)) return false; - if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; } - if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false; - if (inv.Quad(wo, IltInventory.QuadItemTotalXp) != 0) return false; - if (KeptForRatings(G, inv.Int(wo, IltInventory.IntGearCrit), inv.Int(wo, IltInventory.IntGearCritDamage), - inv.Int(wo, IltInventory.IntGearCritDamageResist))) - return false; - return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < ClampUnderLevel(G.ChunkAetheriaUnderLevel); + if (inv.IsEquipped(wo)) return "equipped"; + if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; } + string? gap = inv.ReadGap(wo, quads: true); + var f = new AetheriaFacts( + Coalesced: wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase), + MaxLevel: inv.Int(wo, IltInventory.IntItemMaxLevel), + NeverChunk: inv.Bool(wo, IltInventory.BoolNeverChunk), + ItemXp: inv.Quad(wo, IltInventory.QuadItemTotalXp), + Tinkers: inv.Int(wo, IltInventory.IntNumTimesTinkered), + Imbue: inv.Int(wo, IltInventory.IntImbuedEffect), + Crit: inv.Int(wo, IltInventory.IntGearCrit), + CritDamage: inv.Int(wo, IltInventory.IntGearCritDamage), + CritDamageResist: inv.Int(wo, IltInventory.IntGearCritDamageResist), + Unreadable: gap); + return AetheriaSkip(G, f); } /// The chunk cap in range: 1 (chunk nothing by level) to one past the ILT maximum (every level). internal static int ClampUnderLevel(int under) => Math.Clamp(under, 1, IltInventory.AetheriaMaxLevel + 1); /// - /// True when an aetheria's C / CD / CDR rating is one the settings keep (any rating above 0 with - /// its keep switch on). Pure: the tests drive it. + /// True when an aetheria's max level (int 319) is under the cap. A levelled Coalesced piece + /// (ACECustom rolls 1-10; level 6+ can carry a rating) gets the same cap. Level 0 after + /// appraisal: an unlevelled Coalesced piece is chunkable (ub-IT: "ItemMaxLevel 0 after assess + /// is normal"); any other aetheria with no level is never chunked. Pure: the tests drive it. + /// + internal static bool UnderChunkCap(int maxLevel, int under, bool coalesced = false) + => maxLevel > 0 ? maxLevel < ClampUnderLevel(under) : coalesced && maxLevel == 0; + + /// Highest rating level the keep threshold accepts. + internal const int MaxRatingLevel = 50; + + /// The rating keep threshold in range: 1 (any rating keeps) to . + internal static int ClampRatingLevel(int level) => Math.Clamp(level, 1, MaxRatingLevel); + + /// + /// True when an aetheria's C / CD / CDR rating is one the settings keep: its keep switch is on and + /// the rating is at or above the rating level (). + /// A rating below that level does not protect the piece, so e.g. a C 1 Coalesced Aetheria chunks + /// with the level at 2 while a C 2 one is kept. Pure: the tests drive it. /// internal static bool KeptForRatings(IltGearState g, int crit, int critDamage, int critDamageResist) - => (g.KeepAetheriaWithCrit && crit > 0) - || (g.KeepAetheriaWithCritDamage && critDamage > 0) - || (g.KeepAetheriaWithCritDamageResist && critDamageResist > 0); - - private bool? IsChunkableCorrupted(WorldObject wo) { - if (wo.ObjectClass is not (AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon)) return false; - if (!wo.Name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase)) return false; - var inv = _ctx.Inventory; - if (inv.IsEquipped(wo)) return false; - if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; } - if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false; - if (inv.Int(wo, IltInventory.IntNumTimesTinkered) != 0 || inv.Int(wo, IltInventory.IntImbuedEffect) != 0) return false; - return inv.Int(wo, IltInventory.IntCleaving) <= 1; + int min = ClampRatingLevel(g.KeepAetheriaRatingAtLeast); + return (g.KeepAetheriaWithCrit && crit >= min) + || (g.KeepAetheriaWithCritDamage && critDamage >= min) + || (g.KeepAetheriaWithCritDamageResist && critDamageResist >= min); } - private WorldObject? NextChunkTarget() + private const string Appraising = "appraising"; + private const int SkillTwoHandedCombat = 41; + private const int WeaponTypeTwoHanded = 11; + private const int AttackTypeThrust = 2; + + /// A corrupted weapon's chunk facts, read after appraisal. + internal sealed record CorruptedFacts { - foreach (var wo in _ctx.Inventory.Items()) + public bool NeverChunk { get; init; } + public int Tinkers { get; init; } + public int Imbue { get; init; } + public int Workmanship { get; init; } + public int AttackType { get; init; } + public int Cleaving { get; init; } + public int WieldSkill { get; init; } + public int WeaponType { get; init; } + public double CritFrequency { get; init; } + public double CritMultiplier { get; init; } + public double IgnoreArmor { get; init; } + public int Slayer { get; init; } + public int ElementalBonus { get; init; } + public int MaxDamage { get; init; } + public IReadOnlyList Spells { get; init; } = Array.Empty(); + /// What could not be read (null = everything the rules need was); see AetheriaFacts.Unreadable. + public string? Unreadable { get; init; } + } + + /// + /// The most cleave a chunkable corrupted weapon may have (ub-IT IsValidCorruptedWep): 2 on a + /// two-handed weapon that is not a thrust weapon, 1 on everything else. Pure: the tests drive it. + /// + internal static int MaxChunkCleave(int wieldSkill, int weaponType, int attackType) + => (wieldSkill == SkillTwoHandedCombat || weaponType == WeaponTypeTwoHanded) && attackType != AttackTypeThrust ? 2 : 1; + + /// + /// Why a corrupted weapon is kept, or null when it may be chunked: ub-IT's hard rules, then its + /// IdleActs keep rules from the settings. Pure: the tests drive it. + /// + internal static string? CorruptedSkip(IltGearState g, CorruptedFacts f) + { + // A property that failed to read looks like one the weapon lacks (0), which would chunk it. + if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})"; + + // Hard rules (always on). + if (f.NeverChunk) return "never-chunk flag"; + if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued"; + if (f.Workmanship <= 0) return "no workmanship"; + if (f.Cleaving > MaxChunkCleave(f.WieldSkill, f.WeaponType, f.AttackType)) return "cleave over the limit"; + + // Keep rules (each off by default). + if (g.KeepCorruptedCrushingBlow && f.CritFrequency > 0) return "kept: Crushing Blow"; + if (g.KeepCorruptedBitingStrike && f.CritMultiplier > 0) return "kept: Biting Strike"; + if (g.KeepCorruptedArmorCleaving && f.IgnoreArmor > 0) return "kept: Armor Cleaving"; + if (g.KeepCorruptedAnySlayer && f.Slayer > 0) return "kept: slayer"; + if (g.KeepCorruptedMultiStrike && f.AttackType is 160 or 166 or 486) return "kept: multi-strike"; + if (g.KeepCorruptedElementalBonus && f.ElementalBonus > 0) return "kept: elemental bonus"; + if (g.KeepCorruptedMaxDamageAtLeast > 0 && f.MaxDamage >= g.KeepCorruptedMaxDamageAtLeast) return "kept: max damage"; + if (f.Spells.Count > 0) { - if (_skip.Contains(wo.Id)) continue; - if ((G.AutoChunkAetheria || _manualPass) && IsChunkableAetheria(wo) == true) return wo; - if ((G.AutoChunkCorrupted || _manualPass) && IsChunkableCorrupted(wo) == true) return wo; + if (g.KeepCorruptedAnySpell) return "kept: has a spell"; + var deny = ParseSpellIds(g.KeepCorruptedSpellIds); + if (deny.Count > 0 && f.Spells.Any(deny.Contains)) return "kept: listed spell"; } return null; } + /// Positive spell ids from a comma / semicolon / whitespace separated list. Pure: the tests drive it. + internal static HashSet ParseSpellIds(string? csv) + { + var ids = new HashSet(); + if (string.IsNullOrWhiteSpace(csv)) return ids; + foreach (var part in csv.Split(new[] { ',', ';', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) + if (int.TryParse(part, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int id) && id > 0) + ids.Add(id); + return ids; + } + + /// Why a corrupted weapon is kept (null = chunk it); "appraising" while its data is missing. + private string? CorruptedSkip(WorldObject wo) + { + var inv = _ctx.Inventory; + if (inv.IsEquipped(wo)) return "equipped"; + if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; } + bool needDoubles = G.KeepCorruptedCrushingBlow || G.KeepCorruptedBitingStrike || G.KeepCorruptedArmorCleaving; + bool needSpells = G.KeepCorruptedAnySpell || !string.IsNullOrWhiteSpace(G.KeepCorruptedSpellIds); + var f = new CorruptedFacts + { + Unreadable = inv.ReadGap(wo, doubles: needDoubles, spells: needSpells), + NeverChunk = inv.Bool(wo, IltInventory.BoolNeverChunk), + Tinkers = inv.Int(wo, IltInventory.IntNumTimesTinkered), + Imbue = inv.Int(wo, IltInventory.IntImbuedEffect), + Workmanship = inv.Int(wo, IltInventory.IntItemWorkmanship), + AttackType = inv.Int(wo, IltInventory.IntAttackType), + Cleaving = inv.Int(wo, IltInventory.IntCleaving), + WieldSkill = inv.Int(wo, IltInventory.IntWieldSkillType), + WeaponType = inv.Int(wo, IltInventory.IntWeaponType), + CritFrequency = inv.Double(wo, IltInventory.FloatCriticalFrequency), + CritMultiplier = inv.Double(wo, IltInventory.FloatCriticalMultiplier), + IgnoreArmor = inv.Double(wo, IltInventory.FloatIgnoreArmor), + Slayer = inv.Int(wo, IltInventory.IntSlayerCreatureType), + ElementalBonus = inv.Int(wo, IltInventory.IntElementalDamageBonus), + MaxDamage = inv.Int(wo, IltInventory.IntDamage), + // Spells are only read when a spell rule is on (the read copies the item's spell list). + Spells = needSpells ? inv.SpellIds(wo) : Array.Empty(), + }; + return CorruptedSkip(G, f); + } + + /// + /// Chunk is allowed while the client is busy only in combat mode with ChunkInCombat on (ub-IT + /// AutoChunkCombatBusyPolicy v2.0.1059: a swinging bot is always busy). Peace mode still waits + /// for idle so the hammer never interrupts another use. Pure: the tests drive it. + /// + internal static bool AllowsChunkWhileBusy(bool isBusy, bool isPeace, bool chunkInCombat) + => !isBusy || (!isPeace && chunkInCombat); + + private WorldObject? NextChunkTarget() + { + _passSkips.Clear(); + foreach (var wo in _ctx.Inventory.Items()) + { + if (_skip.Contains(wo.Id)) continue; + string? reason; + switch (KindOf(wo.ObjectClass, wo.Name)) + { + case ChunkKind.Aetheria when G.AutoChunkAetheria || _manualPass: + reason = AetheriaSkip(wo); + break; + case ChunkKind.Corrupted when G.AutoChunkCorrupted || _manualPass: + reason = CorruptedSkip(wo); + break; + default: + continue; + } + if (reason == null) { _lastSkip.Remove(wo.Id); return wo; } + NoteSkip(wo, reason); + } + return null; + } + + /// Tallies a skip for the status line and logs it once per item and reason. + private void NoteSkip(WorldObject wo, string reason) + { + _passSkips[reason] = _passSkips.TryGetValue(reason, out int n) ? n + 1 : 1; + if (reason == Appraising) return; + if (_lastSkip.TryGetValue(wo.Id, out string? last) && last == reason) return; + _lastSkip[wo.Id] = reason; + RynthLog.Write(LogCat.IltGear, $"chunk: keep 0x{(uint)wo.Id:X8} '{wo.Name}': {reason}"); + } + + /// "3 kept for its C / CD / CDR rating, 1 appraising" — the current pass's skips. + private string PassSkipSummary() + => string.Join(", ", _passSkips.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Value} {kv.Key}")); + /// Runs one chunk pass now (both item kinds) regardless of the auto toggles. public void ChunkNow() { @@ -143,23 +367,37 @@ internal sealed class IltChunkClap : IIltFeature if (_waitingOn != 0) { - if (now - _waitStartedAt < ChunkResultWaitMs) return; - _skip.Add(_waitingOn); // no result line — don't hammer the same item forever - RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)_waitingOn:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass"); + int id = _waitingOn; + switch (WaitOutcome(now - _waitStartedAt, _ctx.Inventory.Items().Any(wo => wo.Id == id))) + { + case ChunkWait.Waiting: + return; + case ChunkWait.Gone: + _chunked++; + RynthLog.Write(LogCat.IltGear, $"chunk: 0x{(uint)id:X8} left the pack with no result line; counted as chunked"); + break; + case ChunkWait.TimedOut: + _skip.Add(id); // still carried and no result line: don't hammer the same item forever + RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)id:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass"); + break; + } _waitingOn = 0; } if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return; _lastChunkAt = now; - if (!G.ChunkInCombat && !_ctx.Inventory.InPeaceMode) { _chunkStatus = "waiting for peace mode"; return; } - if (_ctx.Inventory.IsBusy) return; + bool peace = _ctx.Inventory.InPeaceMode; + if (!G.ChunkInCombat && !peace) { _chunkStatus = "waiting for peace mode"; return; } + if (!AllowsChunkWhileBusy(_ctx.Inventory.IsBusy, peace, G.ChunkInCombat)) { _chunkStatus = "waiting for idle"; return; } var hammer = FindHammer(); if (hammer == null) { _chunkStatus = $"no {HammerName} carried"; _manualPass = false; return; } var target = NextChunkTarget(); if (target == null) { + string kept = PassSkipSummary(); _chunkStatus = (_chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible") + + (kept.Length > 0 ? $"; not chunked: {kept}" : "") + (_skip.Count > 0 ? $"; {_skip.Count} skipped with no answer (Chunk now retries them)" : ""); _manualPass = false; return; @@ -174,21 +412,64 @@ internal sealed class IltChunkClap : IIltFeature // ── Clap ──────────────────────────────────────────────────────────────── + internal enum ClapPart { None, Red, Blue, Empyrean, Falatacot } + + /// + /// Which side of /clap an item feeds (ACECustom PlayerCommands.HandleClap): red material (Red + /// Coalesced Aetheria, chunks, powder) pairs with Ancient Empyrean Trinkets, blue with Ancient + /// Falatacot Trinkets. Coalesced counts only unrevealed and at level 1-3; level 0 (not read yet) + /// counts, and the server has the last word. With no WCID yet, the chunk and trinket names + /// decide. Pure: the tests drive it. + /// + internal static ClapPart ClapPartOf(uint wcid, string name, int maxLevel) + { + bool lowCoalesced = name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase) && maxLevel <= 3; + switch (wcid) + { + case IltInventory.WcidRedCoalescedAetheria: return lowCoalesced ? ClapPart.Red : ClapPart.None; + case IltInventory.WcidBlueCoalescedAetheria: return lowCoalesced ? ClapPart.Blue : ClapPart.None; + case IltInventory.WcidRedAetheriaChunk: + case IltInventory.WcidRedAetheriaPowder: return ClapPart.Red; + case IltInventory.WcidBlueAetheriaChunk: + case IltInventory.WcidBlueAetheriaPowder: return ClapPart.Blue; + case IltInventory.WcidEmpyreanTrinket: return ClapPart.Empyrean; + case IltInventory.WcidFalatacotTrinket: return ClapPart.Falatacot; + case 0: break; + default: return ClapPart.None; + } + if (name.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Red; + if (name.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Blue; + if (name.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Empyrean; + if (name.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Falatacot; + return ClapPart.None; + } + + /// + /// True when /clap has a pair to work with: red material and an Empyrean Trinket, or blue + /// material and a Falatacot Trinket. One side alone gets "You don't have any aetheria materials". + /// Pure: the tests drive it. + /// + internal static bool CanClap(IEnumerable parts) + { + bool red = false, blue = false, empyrean = false, falatacot = false; + foreach (var part in parts) + { + switch (part) + { + case ClapPart.Red: red = true; break; + case ClapPart.Blue: blue = true; break; + case ClapPart.Empyrean: empyrean = true; break; + case ClapPart.Falatacot: falatacot = true; break; + } + } + return (red && empyrean) || (blue && falatacot); + } + private bool HasClapMaterials() { var inv = _ctx.Inventory; - foreach (var wo in inv.Items()) - { - uint w = inv.Wcid(wo); - if ((w == IltInventory.WcidRedAetheriaChunk || w == IltInventory.WcidBlueAetheriaChunk) - && inv.Int(wo, IltInventory.IntItemMaxLevel) <= 3) - return true; - string n = wo.Name; - if (n.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase) || n.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase) - || n.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase) || n.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase)) - return true; - } - return false; + return CanClap(inv.Items().Where(wo => !inv.IsEquipped(wo)) + .Select(wo => ClapPartOf(inv.Wcid(wo), wo.Name, inv.Int(wo, IltInventory.IntItemMaxLevel)))); } /// Sends "/clap all" through the capture queue (reply stays visible). @@ -197,7 +478,7 @@ internal sealed class IltChunkClap : IIltFeature RynthLog.Trace(LogCat.IltGear, $"ClapNow(manual={manual})"); if (_ctx.Options.IsOff(IltFeature.Clap)) { _clapStatus = "/clap is not available (server or AutoCraftingEnabled stamp)"; return; } if (_ctx.Capture.IsPending("/clap all")) return; - if (!manual && !HasClapMaterials()) { _clapStatus = "no aetheria materials carried"; return; } + if (!manual && !HasClapMaterials()) { _clapStatus = "no aetheria and trinket pair carried (red + Empyrean, blue + Falatacot)"; return; } _clapStatus = "sending /clap all..."; _ctx.Capture.Enqueue(new IltChatRequest { @@ -245,6 +526,21 @@ internal sealed class IltChunkClap : IIltFeature internal enum ChunkResult { None, Busy, Done, Refused } + /// Where a chunk in flight stands when no chat line has ended the wait. + internal enum ChunkWait { Waiting, Gone, TimedOut } + + /// + /// The wait for a chunk with no result line yet. The hammer destroys the target, so a target + /// that has left the pack was chunked: ILT does not always send a line the classifier knows + /// (Silentkelpie 2026-10-18: a Red Aetheria Chunk arrived and UseDone had no error, yet the + /// item was still filed as skipped after 10 s). Still carried after the wait = timed out. + /// Pure: the tests drive it. + /// + internal static ChunkWait WaitOutcome(long elapsedMs, bool targetStillCarried) + => !targetStillCarried ? ChunkWait.Gone + : elapsedMs >= ChunkResultWaitMs ? ChunkWait.TimedOut + : ChunkWait.Waiting; + /// /// What a chat line says about the chunk in flight. ILT names the item and the tool ("You /// smash the Corrupted Sword with the Lugian Aetheria Hammer."), so a line naming a corrupted @@ -288,6 +584,7 @@ internal sealed class IltChunkClap : IIltFeature { _waitingOn = 0; _skip.Clear(); + _lastSkip.Clear(); _manualPass = false; _clapWasEnabled = false; } @@ -306,7 +603,7 @@ internal sealed class IltChunkClap : IIltFeature ImGui.SetNextItemWidth(100); if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = ClampUnderLevel(under); if (ImGui.IsItemHovered()) - SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level."); + SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level.\nA levelled Coalesced Aetheria gets the cap too; an unlevelled one (level 0 after appraisal) is chunked, as in ub-IT."); bool kc = G.KeepAetheriaWithCrit, kcd = G.KeepAetheriaWithCritDamage, kcdr = G.KeepAetheriaWithCritDamageResist; ImGui.TextUnformatted("Never chunk aetheria with:"); ImGui.SameLine(); @@ -318,6 +615,39 @@ internal sealed class IltChunkClap : IIltFeature ImGui.SameLine(); if (ImGui.Checkbox("CDR##keepcdr", ref kcdr)) G.KeepAetheriaWithCritDamageResist = kcdr; if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage Resist rating (GearCritDamageResist)."); + int ratingAt = G.KeepAetheriaRatingAtLeast; + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Keep when the rating is at least##keeprating", ref ratingAt)) G.KeepAetheriaRatingAtLeast = ClampRatingLevel(ratingAt); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Rating level for the C / CD / CDR switches above (Coalesced Aetheria and revealed aetheria).\n" + + "At or above this level: kept. Below it: the rating does not protect the piece, so it chunks\n" + + "if the level cap and the other rules allow. 1 = any rating keeps."); + if (ImGui.TreeNode("Corrupted weapon keep rules##corrkeep")) + { + // ub-IT IdleActs > Corr Chunk: each matching rule keeps the weapon. + bool cb = G.KeepCorruptedCrushingBlow, bs = G.KeepCorruptedBitingStrike, acl = G.KeepCorruptedArmorCleaving; + bool sl = G.KeepCorruptedAnySlayer, ms = G.KeepCorruptedMultiStrike, el = G.KeepCorruptedElementalBonus, sp = G.KeepCorruptedAnySpell; + if (ImGui.Checkbox("Crushing Blow##ck", ref cb)) G.KeepCorruptedCrushingBlow = cb; + ImGui.SameLine(); + if (ImGui.Checkbox("Biting Strike##ck", ref bs)) G.KeepCorruptedBitingStrike = bs; + ImGui.SameLine(); + if (ImGui.Checkbox("Armor Cleaving##ck", ref acl)) G.KeepCorruptedArmorCleaving = acl; + if (ImGui.Checkbox("Any slayer##ck", ref sl)) G.KeepCorruptedAnySlayer = sl; + ImGui.SameLine(); + if (ImGui.Checkbox("Multi-strike##ck", ref ms)) G.KeepCorruptedMultiStrike = ms; + ImGui.SameLine(); + if (ImGui.Checkbox("Elemental bonus##ck", ref el)) G.KeepCorruptedElementalBonus = el; + if (ImGui.Checkbox("Any spell##ck", ref sp)) G.KeepCorruptedAnySpell = sp; + int maxDmg = G.KeepCorruptedMaxDamageAtLeast; + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Keep max damage at least (0 = off)##ck", ref maxDmg)) G.KeepCorruptedMaxDamageAtLeast = Math.Max(0, maxDmg); + string ids = G.KeepCorruptedSpellIds ?? ""; + ImGui.SetNextItemWidth(220); + if (ImGui.InputText("Keep spell ids##ck", ref ids, 512)) G.KeepCorruptedSpellIds = ids; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Comma or space separated spell ids: a corrupted weapon carrying any of them is kept."); + SafeImGui.TextDisabled("Always kept: tinkered, imbued, no workmanship, cleave over 1 (2 on two-handed, non-thrust)."); + ImGui.TreePop(); + } if (ImGui.Button("Chunk eligible items now...")) _ctx.Confirm("Chunk items", "Run one chunk pass now on every eligible aetheria and corrupted weapon?\nChunked items are destroyed.", ChunkNow, "Chunk"); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs index a0035c7..96b39c0 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs @@ -111,7 +111,7 @@ internal static class IltFeatureCatalog new("pets", "Pet log", GroupPets, "Mini Remote > Pets tab", "Captured pets, registered with Professor Ruggan (/pets).", IltFeature.Pets, IltKnown.Checked), new("shinies", "Shiny log", GroupPets, "Mini Remote > Pets tab", "Rare shiny creature variants you captured (/shinies).", IltFeature.Shinies, IltKnown.Checked), new("monster_capture", "Monster capture", GroupPets, "Mini Remote > Pets tab", - "Siphon lenses capture a creature's look into a pet essence (lens drops from kills are a separate server switch).", "monster_capture"), + "Siphon lenses capture a creature\'s look into a pet essence (<=20% health or under 20 HP; Asheron\'s Lens skips the gate). Auto-capture is the checkbox on the Pets roster.", "monster_capture"), new("pet_breeding", "Pet breeding", GroupPets, "Mini Remote > Pets > Breeding", "Breed two combat pet devices at the Seedy Motel for inherited and mutated offspring (/dance).", "pet_breeding"), new("pet_maturity", "Pet maturity", GroupPets, "Mini Remote > Pets > Breeding", diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs index 9ded4c5..7a74b7a 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs @@ -64,6 +64,8 @@ internal sealed class IltHubController public IltCharms CharmsTab { get; } /// Temple guardians: riddle translator, hand-in, attribute turn-in tracker. public IltGuardian Guardian { get; } + /// Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind RynthAi's master switch, off by default. + public IltVaultedDungeons VaultedDungeons { get; } /// True while this character's copy from RynthAi is unfinished (IltHubStore.WritesBlocked). /// The character's RynthAi folder while that copy is unfinished (read-only fallback). @@ -92,7 +94,8 @@ internal sealed class IltHubController Charms = new IltCharmTracker(_ctx); CharmsTab = new IltCharms(_ctx, Charms); Guardian = new IltGuardian(_ctx, QuestBonus); - _features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, Guardian }); + VaultedDungeons = new IltVaultedDungeons(_ctx); + _features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian }); Banking.BalanceChanged += Rates.OnBankBalanceChanged; Rates.MovingMoney = () => Banking.MovingMoney; @@ -192,6 +195,8 @@ internal sealed class IltHubController IltSection.Character => true, IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank), IltSection.Games => Available && Games.AnyGameAvailable, + // Content, not a server feature bit: an ILT world and the master switch (RynthAi's setting). + IltSection.VaultedDungeons => _ctx.Options.IsIltLikeWorld && VaultedDungeons.MasterEnabled(), _ => Available, }; @@ -320,6 +325,14 @@ internal sealed class IltHubController } } + /// The server's killer notification (pump thread): restarts the Vaulted Dungeons no-kill timer, on ILT only. + public void OnKillNotification() + { + if (!_ctx.Options.IsIltLikeWorld) return; + try { VaultedDungeons.OnKillNotification(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "VaultedDungeons.OnKillNotification"); } + } + /// Pump-thread chat line. Returns true when the line should be hidden. public bool OnChat(string text) { @@ -346,6 +359,7 @@ internal sealed class IltHubController IltProgression => LogCat.IltProgression, IltGear or IltCharms => LogCat.IltGear, IltGames => LogCat.IltGames, + IltVaultedDungeons => LogCat.IltHub, _ => LogCat.IltHub, }; @@ -390,7 +404,11 @@ internal sealed class IltHubController if (r.Lines.Count == 0) return; switch (key) { - case IltFeature.Aug: Progression.ApplyAugLines(r.Lines); break; + case IltFeature.Aug: + Progression.ApplyAugLines(r.Lines); + // Probe's OnComplete is not RequestAugs' — drain a queued Refresh current / empty retry. + Progression.AfterExternalAugCapture(); + break; case IltFeature.Pets: PetLogs.ApplyRoster(false, r.Lines); break; case IltFeature.Shinies: PetLogs.ApplyRoster(true, r.Lines); break; case IltFeature.Qb: QuestBonus.ApplyQbProbe(r.Lines); break; @@ -456,7 +474,7 @@ internal sealed class IltHubController { // Quests and Pets are RynthAi's tabs: not ours to open. if (args.Length >= 2 && IltSections.IsUniversalTabName(args[1])) return false; - _ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)"); + _ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|vaulted|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)"); break; } OpenSection(section, args.Length > 2 ? args[2] : "toggle"); @@ -494,7 +512,8 @@ internal sealed class IltHubController break; default: _ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|features|force on|off|servers [list]|clap|confirm|cancel"); - _ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)"); + _ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games|vaulted [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)"); + _ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: Settings > Navigation > Vaulted Dungeons)"); _ctx.Chat("[Mini Remote] /ra hub profile list|save [shared]|load /ra hub suit list|test|load [name]"); _ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every |raise (Skills panel > Progression)"); _ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)"); @@ -580,6 +599,13 @@ internal sealed class IltHubController OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode); return; } + if (section == IltSection.VaultedDungeons && !SectionAvailable(section)) + { + _ctx.Chat(_ctx.Options.IsIltLikeWorld + ? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in Settings > Navigation (the master switch, off by default)." + : "[Mini Remote] Vaulted Dungeons is not available on this server (Infinite Leaftide / ACECustom only)."); + return; + } string reply = _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), mode); if (!SectionAvailable(section) && !mode.Equals("hide", StringComparison.OrdinalIgnoreCase)) reply = $"The {IltSections.Label(section)} tab shows once the server reports that feature on."; diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs index b839669..97fffc0 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs @@ -204,7 +204,7 @@ public sealed class IltGearState public bool ChunkInCombat; public int ChunkIntervalMs = 2000; /// - /// Only chunk aetheria whose max level is below this (Coalesced always chunks). Infinite Leaftide + /// Only chunk aetheria whose max level is below this (Coalesced Aetheria too). Infinite Leaftide /// aetheria goes up to level , so the cap runs to one past it. /// public int ChunkAetheriaUnderLevel = 4; @@ -214,6 +214,32 @@ public sealed class IltGearState public bool KeepAetheriaWithCritDamage = true; /// Never chunk aetheria carrying a Crit Damage Resist rating (CDR, GearCritDamageResist 375). public bool KeepAetheriaWithCritDamageResist = true; + /// + /// Rating level for the C / CD / CDR keep switches: a rating at or above this keeps the piece, + /// a lower one does not protect it (it chunks if the other rules allow). 1 = any rating keeps. + /// + public int KeepAetheriaRatingAtLeast = 1; + + // Corrupted-weapon keep rules (ub-IT IdleActs > Corr Chunk). All off by default, as in ub-IT: + // the hard rules (unmodified, workmanship, cleaving, never-chunk) always apply on top. + /// Never chunk a corrupted weapon with Crushing Blow (CriticalFrequency float 147 > 0). + public bool KeepCorruptedCrushingBlow; + /// Never chunk a corrupted weapon with Biting Strike (CriticalMultiplier float 136 > 0). + public bool KeepCorruptedBitingStrike; + /// Never chunk a corrupted weapon with Armor Cleaving (IgnoreArmor float 155 > 0). + public bool KeepCorruptedArmorCleaving; + /// Never chunk a corrupted weapon with any slayer (SlayerCreatureType int 166 > 0). + public bool KeepCorruptedAnySlayer; + /// Never chunk a multi-strike corrupted weapon (AttackType int 47 = 160 / 166 / 486). + public bool KeepCorruptedMultiStrike; + /// Never chunk a corrupted weapon with an elemental damage bonus (int 204 > 0). + public bool KeepCorruptedElementalBonus; + /// Never chunk a corrupted weapon with any spell on it. + public bool KeepCorruptedAnySpell; + /// Never chunk a corrupted weapon whose max damage (int 44) is at least this. 0 = off. + public int KeepCorruptedMaxDamageAtLeast; + /// Spell ids (comma / space separated): never chunk a corrupted weapon carrying any of them. + public string KeepCorruptedSpellIds = ""; // Auto-clap (/clap all) public bool AutoClap; diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs index 9cca44f..6a9751d 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs @@ -70,6 +70,7 @@ internal sealed class IltHubUi case IltSection.Gear: _hub.Gear.Render(); break; case IltSection.Charms: _hub.CharmsTab.Render(); break; case IltSection.Games: _hub.Games.Render(); break; + case IltSection.VaultedDungeons: _hub.VaultedDungeons.Render(); break; default: // A saved tab id from before the move: say where the section lives now. if (IltSections.MovedCommand(section) is string moved) diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs index 272a233..6fe2672 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs @@ -36,8 +36,18 @@ internal sealed class IltInventory public const uint WcidSummonRefillCharm = 78780030; public const uint WcidUniversalMasteryCharm = 78780031; public static readonly uint[] WcidInfiniteCastingStone = { 777700019, 777700055 }; - public const uint WcidRedAetheriaChunk = 42636; - public const uint WcidBlueAetheriaChunk = 42635; + // Aetheria (ACECustom Aetheria.cs / PlayerCommands /clap). The Coalesced WCIDs stay the same once + // revealed (name "Aetheria", equipment set given), and /clap takes only unrevealed level 1-3 ones. + public const uint WcidBlueCoalescedAetheria = 42635; + public const uint WcidRedCoalescedAetheria = 42636; + public const uint WcidYellowCoalescedAetheria = 42637; + public const uint WcidRedAetheriaChunk = 310147; + public const uint WcidBlueAetheriaChunk = 310149; + public const uint WcidYellowAetheriaChunk = 310150; + public const uint WcidRedAetheriaPowder = 42644; + public const uint WcidBlueAetheriaPowder = 300019; + public const uint WcidEmpyreanTrinket = 34276; + public const uint WcidFalatacotTrinket = 34277; // ── Property ids used by several features ─────────────────────────────── public const uint IntStackSize = 12; @@ -48,6 +58,27 @@ internal sealed class IltInventory public const uint IntNumTimesTinkered = 171; public const uint IntImbuedEffect = 179; public const uint IntCleaving = 292; + // Corrupted-weapon chunk rules (ub-IT Leaftide.IsValidCorruptedWep / CorruptedChunkGuard). + /// ACE PropertyInt.Damage — a weapon's max damage. + public const uint IntDamage = 44; + /// ACE PropertyInt.AttackType — 2 = thrust; 160 / 166 / 486 are the multi-strike masks. + public const uint IntAttackType = 47; + /// ACE PropertyInt.ItemWorkmanship — loot-gen Craft (salvage-bag workmanship is not on weapons). + public const uint IntItemWorkmanship = 105; + /// ACE PropertyInt.WieldSkillType — 41 (Two Handed Combat) for two-handed weapons. + public const uint IntWieldSkillType = 159; + /// ACE PropertyInt.SlayerCreatureType. + public const uint IntSlayerCreatureType = 166; + /// ACE PropertyInt.ElementalDamageBonus. + public const uint IntElementalDamageBonus = 204; + /// ACE PropertyInt.WeaponType — 11 = TwoHanded. + public const uint IntWeaponType = 353; + /// ACE PropertyFloat.CriticalMultiplier — Biting Strike. + public const uint FloatCriticalMultiplier = 136; + /// ACE PropertyFloat.CriticalFrequency — Crushing Blow. + public const uint FloatCriticalFrequency = 147; + /// ACE PropertyFloat.IgnoreArmor — Armor Cleaving. + public const uint FloatIgnoreArmor = 155; public const uint IntItemMaxLevel = 319; /// Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5). public const int AetheriaMaxLevel = 10; @@ -176,6 +207,22 @@ internal sealed class IltInventory public long Quad(WorldObject wo, uint stype) => _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(unchecked((uint)wo.Id), stype, out long v) ? v : 0; + /// A float (PropertyFloat) value; 0 when the host cannot read it or the item has none. + public double Double(WorldObject wo, uint stype) + => _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(unchecked((uint)wo.Id), stype, out double v) ? v : 0; + + /// The spell ids on an item (empty when none or the host cannot read them). + public IReadOnlyList SpellIds(WorldObject wo) + { + if (!_host.HasGetObjectSpellIds) return Array.Empty(); + var buf = new uint[64]; + int n = _host.GetObjectSpellIds(unchecked((uint)wo.Id), buf, buf.Length); + if (n <= 0) return Array.Empty(); + var ids = new int[Math.Min(n, buf.Length)]; + for (int i = 0; i < ids.Length; i++) ids[i] = unchecked((int)buf[i]); + return ids; + } + public string Str(WorldObject wo, uint stype) => _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(unchecked((uint)wo.Id), stype, out string v) ? v ?? string.Empty : string.Empty; @@ -191,6 +238,25 @@ internal sealed class IltInventory public bool HasAppraisal(WorldObject wo) => !_host.HasHasAppraisalData || _host.HasAppraisalData(unchecked((uint)wo.Id)); + /// + /// Why an item's property reads cannot be trusted (null = they can). Every property read here + /// answers 0 / false both for "the item has none" and for "the host cannot read it", so a chunk + /// rule that acts on a 0 must first know the read was real: the host must expose the readers + /// and confirm the item's appraisal arrived. adds the 64-bit reads + /// (item XP), the float reads and the + /// spell list, for the rules that use them. + /// + public string? ReadGap(WorldObject wo, bool quads = false, bool doubles = false, bool spells = false) + { + if (!_host.HasGetObjectIntProperty) return "int properties"; + if (!_host.HasGetObjectBoolProperty) return "bool properties"; + if (quads && !_host.HasGetObjectQuadProperty) return "item XP"; + if (doubles && !_host.HasGetObjectDoubleProperty) return "float properties"; + if (spells && !_host.HasGetObjectSpellIds) return "spells"; + if (!_host.HasHasAppraisalData || !_host.HasAppraisalData(unchecked((uint)wo.Id))) return "appraisal"; + return null; + } + /// Requests appraisal data, throttled per object. Returns true if a request was sent. public bool RequestAppraisal(WorldObject wo) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs index 4d01937..7e728fc 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs @@ -48,6 +48,8 @@ internal static class LogEvents public const string IltCommand = "IltHub.Command"; public const string IltConfirmation = "IltHub.Confirmation"; public const string IltLogout = "IltHub.Logout"; + /// /aug ApplyAugLines outcome (Progress Refresh current / login probe). + public const string IltAugLoad = "IltHub.AugLoad"; /// Events written as a normal log line; the rest only while their category is traced. internal static readonly Dictionary Catalog = new(StringComparer.Ordinal) @@ -61,6 +63,7 @@ internal static class LogEvents [IltCommand] = (LogCat.IltHub, false), [IltConfirmation] = (LogCat.IltHub, false), [IltLogout] = (LogCat.IltHub, false), + [IltAugLoad] = (LogCat.IltProgression, true), }; } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs index 4d37e4b..d111074 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs @@ -18,7 +18,7 @@ internal static class IltParse /// "/aug" level line: "Creature:1,234", "Duration: 1,234", or "Specialize: 2". /// Trailing notes ("Triune Weave: 5 (adds ...)") are allowed; the planner only keeps known keys. /// - public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*([\d,]+)", Opt); + public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*(\d[\d,.\s']*)", Opt); /// "/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener". public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt); @@ -46,6 +46,22 @@ internal static class IltParse /// "/attr" success: "[ATTR] Strength attribute raised by 10, costing 1,234!". public static readonly Regex AttrRaised = new(@"^\[ATTR\] (\w+) attribute raised by (\d+), costing ([\d,]+)", Opt); + private static readonly Regex GroupedInt = new(@"^\d{1,3}(?:[,.\s']\d{3})+|^\d+", RegexOptions.CultureInvariant); + + /// + /// The level in an AugLine value: digits grouped by a comma, period, space or apostrophe + /// ("4,300", "4.300", "4 300", "4'300") read as one number; "2 (adds 5)" as 2; "1.5" as 1. 0 when absent. + /// + public static long ParseAugValue(string text) + { + if (string.IsNullOrEmpty(text)) return 0; + var m = GroupedInt.Match(text.Trim()); + if (!m.Success) return 0; + var digits = new System.Text.StringBuilder(m.Value.Length); + foreach (char c in m.Value) if (char.IsDigit(c)) digits.Append(c); + return long.TryParse(digits.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0; + } + /// Strips commas and parses the leading integer; 0 when absent. public static long ParseLeadingLong(string text) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs index ac87d89..0977bc5 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs @@ -65,6 +65,8 @@ internal sealed class IltProgression : IIltFeature private bool _augAutoTried; /// Second Refresh current while /aug is already queued or in flight (UB coalesces the same way). private bool _augRefreshAgain; + /// One silent retry after the login probe left Current empty (chat-hold / ArmsIdle race). + private bool _augProbeRetryDone; /// Passive /aug window: accept AugLine chat until this tick (like T11's report parser). private long _augPassiveUntilMs; @@ -113,7 +115,8 @@ internal sealed class IltProgression : IIltFeature _augStatus = "/aug is off for this world"; return; } - // Coalesce: a click during an in-flight /aug runs again when that capture finishes (UB). + // Coalesce: a click during an in-flight /aug (login probe or a prior Refresh) runs again + // when that capture finishes — including via AfterExternalAugCapture for the probe. if (_ctx.Capture.IsPending("/aug")) { _augRefreshAgain = true; @@ -121,15 +124,16 @@ internal sealed class IltProgression : IIltFeature return; } _augStatus = "loading..."; - _augPassiveUntilMs = IltHubContext.NowMs + 20_000; // also accept lines if capture finishes early + _augPassiveUntilMs = IltHubContext.NowMs + 30_000; // also accept lines if capture finishes early _ctx.Capture.Enqueue(new IltChatRequest { Command = "/aug", IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t), // Idle must not start on the banner alone — chat-hold / pump lag used to finish with 0 level lines. ArmsIdle = t => IltParse.AugLine.IsMatch(t), - IdleEndMs = 2000, - FirstLineTimeoutMs = 15000, + IdleEndMs = 2500, + // Login + chat-hold backlog can push Creature: past the old 15s first-line window. + FirstLineTimeoutMs = 30_000, Eat = true, OnComplete = r => { @@ -148,15 +152,36 @@ internal sealed class IltProgression : IIltFeature if (have == 0) _augStatus = "timed out waiting for /aug level lines"; } - if (_augRefreshAgain) - { - _augRefreshAgain = false; - RequestAugs(); - } + DrainAugRefreshAgain(); }, }); } + /// + /// Login probe finished its "/aug" capture (or another path applied lines). Drains a queued + /// Refresh current and, if the probe left Current empty, retries once. + /// + public void AfterExternalAugCapture() + { + if (DrainAugRefreshAgain()) return; + int have; + lock (_augLevels) have = _augLevels.Count; + if (have > 0 || _augProbeRetryDone || _ctx.Options.IsOff(IltFeature.Aug)) return; + if (_ctx.Capture.IsPending("/aug")) return; + _augProbeRetryDone = true; + RynthLog.Event(LogEvents.IltAugLoad, "aug probe left Current empty — retrying /aug once"); + RequestAugs(); + } + + /// Runs a coalesced Refresh current if one was queued. Returns true when it did. + private bool DrainAugRefreshAgain() + { + if (!_augRefreshAgain) return false; + _augRefreshAgain = false; + RequestAugs(); + return true; + } + /// Parses "/aug" output (also fed from the login probe and passive chat). public void ApplyAugLines(List lines) { @@ -166,8 +191,26 @@ internal sealed class IltProgression : IIltFeature { if (TryApplyAugLine(l)) n++; } - _augStatus = n > 0 ? $"{n} aug types @ {DateTime.Now:t}" : "no aug lines in reply"; - RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines done: {_augStatus} (raw lines={lines.Count})"); + if (n > 0) + { + _augStatus = $"{n} aug types @ {DateTime.Now:t}"; + _augPassiveUntilMs = IltHubContext.NowMs + 8_000; + } + else + { + bool sawBanner = false; + foreach (string l in lines) + { + if (l.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase)) + { sawBanner = true; break; } + } + _augStatus = sawBanner + ? "no level lines yet (banner only — waiting / retry)" + : "no aug lines in reply"; + // Keep the passive reader open so late Creature: lines still fill Current. + if (sawBanner) _augPassiveUntilMs = IltHubContext.NowMs + 15_000; + } + RynthLog.Event(LogEvents.IltAugLoad, $"ApplyAugLines: {_augStatus} (raw={lines.Count})"); } /// Applies one "/aug" Type: N line. Returns true when a known planner key was updated. @@ -182,7 +225,7 @@ internal sealed class IltProgression : IIltFeature foreach (var (k, _) in IltAugCosts.Labels) if (k.Equals(key, StringComparison.OrdinalIgnoreCase)) { known = true; break; } if (!known) return false; - lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value); + lock (_augLevels) _augLevels[key] = (int)IltParse.ParseAugValue(m.Groups[2].Value); return true; } @@ -249,6 +292,7 @@ internal sealed class IltProgression : IIltFeature lock (_augLevels) _augLevels.Clear(); _augAutoTried = false; _augRefreshAgain = false; + _augProbeRetryDone = false; _augPassiveUntilMs = 0; _augStatus = "not loaded"; } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs index 080c7df..3ca9153 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs @@ -1,7 +1,7 @@ // IltSections.cs - The Infinite Leaftide tabs of RynthAi's Mini Remote and the Guardian panel. // Originally SilentKelpie's ILT Hub sections (RynthAi IltHub/); moved to RynthILT 2026-10-13. // -// Banking, Gear, Charms and Games are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar +// Banking, Gear, Charms, Games and Vaulted Dungeons are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar // (after its Remote, Pets and Crafting tabs) and asks RynthILT for each tab's body (RynthILT.Hub // GetTabs / RenderTab); "/ra hub open
" picks one, and with RynthCore's sections rail // RynthAi lists them as "section:" views (Inventory). Guardian is a RynthCore ILT panel @@ -29,6 +29,11 @@ internal enum IltSection Banking, Gear, Games, + /// + /// Vaulted Dungeons keeper (portal-recall gem + kill-client). A Mini Remote tab on ILT worlds only, + /// and only while RynthAi's "Vaulted Dungeons" master switch (Settings > Navigation) is on. + /// + VaultedDungeons, /// Registry charms (acquired / status / tier / server) and the Guardian Hand. Charms, // Keep Guardian last. @@ -40,7 +45,7 @@ internal static class IltSections /// The ILT tabs, in tab-bar order (RynthAi puts them after its own tabs). public static readonly IltSection[] Tabs = { - IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, + IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons, }; /// The Mini Remote's own tab (the remote itself): its tab id. @@ -55,6 +60,7 @@ internal static class IltSections IltSection.Banking => "Banking", IltSection.Gear => "Gear", IltSection.Games => "Games", + IltSection.VaultedDungeons => "Vaulted Dungeons", IltSection.Charms => "Charms", IltSection.Guardian => "Guardian", _ => s.ToString(), @@ -70,13 +76,15 @@ internal static class IltSections IltSection.Banking => "banking", IltSection.Gear => "gear", IltSection.Games => "games", + IltSection.VaultedDungeons => "vaulted", IltSection.Charms => "charms", IltSection.Guardian => "guardian", _ => s.ToString().ToLowerInvariant(), }; - /// True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games). - public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games; + /// True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games, Vaulted Dungeons). + public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games + or IltSection.VaultedDungeons; /// /// Where a section that moved out of the Mini Remote lives now, as the chat command that opens @@ -104,6 +112,8 @@ internal static class IltSections case "banking": case "bank": section = IltSection.Banking; return true; case "gear": section = IltSection.Gear; return true; case "games": case "game": section = IltSection.Games; return true; + case "vaulted": case "vaulteddungeons": case "vaulted-dungeons": + section = IltSection.VaultedDungeons; return true; case "charms": case "charm": section = IltSection.Charms; return true; case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true; default: section = IltSection.Gear; return false; @@ -120,6 +130,7 @@ internal static class IltSections IltSection.Gear => new Vector2(560, 520), IltSection.Charms => new Vector2(560, 520), IltSection.Games => new Vector2(520, 440), + IltSection.VaultedDungeons => new Vector2(360, 420), _ => new Vector2(520, 440), }; diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs new file mode 100644 index 0000000..3520562 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs @@ -0,0 +1,919 @@ +// IltVaultedDungeons.cs — Mini Remote "Vaulted Dungeons" tab (ILT / ACECustom only). +// Written by Silentkelpie (RynthSuite PR #12), a port of the UtilityBelt VaultedDungeons.lua script +// (owner 2026-09-27 / 2026-10-03): keeps the character in one Vaulted Dungeon via a tied Portal +// Recall Gem, and optionally /rc quit after N minutes without a kill. +// +// Safety rules (the owner's, added when it was taken in): +// * ILT only. The module does nothing (no tick work, no recall, no quit, no tab) unless +// IltServerOptions.IsIltLikeWorld says this is an Infinite Leaftide / ACECustom world, the same +// verdict every other ILT feature follows. A command answers "not available on this server". +// * Master switch, off by default: RynthAi's "Vaulted Dungeons" setting (Settings > Navigation), +// read through RynthAi.Hub VaultedDungeonsEnabled. It is the only copy. While it is off the module +// ignores AutoStart, never ticks, sends no recall and no /rc quit, and the tab is hidden. Turning +// it off while running stops the keeper at once and says so once. +// * Active is never resumed from the saved settings. It starts when the player turns it on, or on +// arriving in the chosen dungeon with Auto Start On Arrival on (master on); a relog starts Off. +// * No recall gem while RynthAi is in combat, buffing or waiting on the server, or the client is +// busy: the recall waits until it is clear (a warning on the normal 30 s cadence). +// * /rc quit goes out at most once per activation, and only if Active, ILT and the master are all +// still true at the moment of sending. +// * The no-kill timer restarts on the luminance line, on the server's killer notification (a +// killing blow of yours) and on a pet-capture success reply. Kills by pets or fellows that pay +// no luminance still don't count; the tab says so. +using System; +using System.Collections.Generic; +using System.IO; +using System.Numerics; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One known Vaulted Dungeon (landblock high word; the client does not see the layer). +internal readonly record struct VaultedDungeon(string Name, uint Landblock); + +internal sealed class IltVaultedDungeons : IIltFeature +{ + // Keep order stable: saved picks are by 1-based index into this list. + private static readonly VaultedDungeon[] Dungeons = + { + new("Tyrant's Quarry", 0x01F7), + new("Tusgian Barracks", 0x8C03), + new("Wailing Cells", 0x01C2), + new("Chamber of Idols", 0x5649), + new("Fiun Redoubt", 0x0178), // added 2026-09-27 + new("Tumerok Tunnels", 0x5754), // added 2026-10-03 + }; + + private static readonly string[] GemNames = + { + "Primary Portal Recall Gem", + "Secondary Portal Recall Gem", + }; + + private static readonly (string Name, float Value)[] Powers = + { + ("Fast", 0f), ("Medium", 0.5f), ("Full Power", 1f), + }; + + private static readonly int[] QuitPresets = { 1, 2, 5, 10, 15, 30 }; + + private const long FirstRecallAfterMs = 1000; + private const long RecallAfterMs = 5000; + private const int QuitMin = 1, QuitMax = 30; + private const long WarnEveryMs = 30_000; + private const string SettingsFileName = "settings.json"; + private const string SettingsBadFileName = "settings.unreadable.json"; + + private const string CmdMetaOff = "/vt opt set EnableMeta False"; + private const string CmdNavOff = "/vt opt set EnableNav False"; + private const string CmdRepeatOn = "/ub playeroption AutoRepeatAttack on"; + private const string CmdAttackBar = "/vt setattackbar "; + private const string CmdQuit = "/rc quit"; + + // System line only (no player sender): "You've banked 1,234 Luminance." + private static readonly Regex KillLine = new( + @"^You've banked [\d,]+ Luminance\.\s*$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// Why the keeper is idle (): "" = it may run. + private const string GateWorld = "world", GateMaster = "master"; + + private readonly IltHubContext _ctx; + private readonly object _gate = new(); + private Cfg _cfg = new(); + private bool _loaded; + private bool _dirty; + private string? _lastGoodJson; + + // Seams (the tests fake them): the master switch, what RynthAi is doing, the clock, the gem use. + internal Func MasterEnabled; + internal Func Activity; + internal Func Clock = () => IltHubContext.NowMs; + /// Uses the named gem from the pack; false when the pack has none. + internal Func UseGem; + + // Runtime (pump thread). + private long _outSinceMs; + private long _lastRecallMs; + private long _clockStartMs; + private long _realKillMs; + private bool _wasInside; + private bool _quitSent; + private long _lastWarnMs = -WarnEveryMs; + private string _publishedGate = "?"; + private string _state = "paused"; // paused / setup / in / out / portal / nogem + private long? _quitLeftMs; + private bool? _presentBefore; + private long _idleSecs; + private long _inSinceMs; + private long _portalSinceMs; + private int _kills; + private long _dungeonSecs; + private long _lastTickMs; + + // Snapshot for the render thread (copied under _gate). + private Snapshot _snap = Snapshot.Empty; + + public IltVaultedDungeons(IltHubContext ctx) + { + _ctx = ctx; + MasterEnabled = () => _ctx.Ai.VaultedDungeonsEnabled; + Activity = () => _ctx.Ai.Activity(); + UseGem = gemName => + { + var gem = _ctx.Inventory.FindByName(n => n.Equals(gemName, StringComparison.OrdinalIgnoreCase)); + if (gem == null) return false; + _ctx.Inventory.Use(gem); + return true; + }; + } + + /// Whether the keeper is running (tests, status). + internal bool IsActive => _cfg.Active; + + private long Now() => Clock(); + + /// + /// The two hard rules, asked fresh each time: an ILT-like world, and the master switch on. + /// says which one failed ("" when allowed). + /// + private bool Allowed(out string gate) + { + gate = !_ctx.Options.IsIltLikeWorld ? GateWorld : !MasterEnabled() ? GateMaster : string.Empty; + return gate.Length == 0; + } + + /// Same, for commands and the tab: why the keeper can't be used now (null = it can). + private static string? GateReply(string gate) => gate switch + { + GateWorld => "Not available on this server (Infinite Leaftide / ACECustom only).", + GateMaster => "Off: turn on \"Vaulted Dungeons\" in Settings > Navigation first (the master switch, off by default).", + _ => null, + }; + + // ── Persistence ───────────────────────────────────────────────────────── + + private string SettingsDir => Path.Combine(_ctx.Store.CharFolder, "VaultedDungeons"); + private string SettingsPath => Path.Combine(SettingsDir, SettingsFileName); + + private void EnsureLoaded() + { + if (_loaded) return; + _loaded = true; + try + { + string path = SettingsPath; + if (!File.Exists(path)) return; + string text = File.ReadAllText(path); + var cfg = JsonSerializer.Deserialize(text, IltVaultedDungeonsJsonContext.Default.Cfg); + if (cfg == null) return; + _cfg = Sanitize(cfg); + _lastGoodJson = text; + } + catch (Exception ex) + { + RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings load failed: {ex.Message}"); + } + } + + private void SaveIfDirty() + { + if (!_dirty) return; + _dirty = false; + try + { + Directory.CreateDirectory(SettingsDir); + string path = SettingsPath; + // Corrupt / mid-write: keep a copy, then rewrite from last good + current cfg. + if (File.Exists(path)) + { + try + { + string existing = File.ReadAllText(path); + if (_lastGoodJson == null) + JsonSerializer.Deserialize(existing, IltVaultedDungeonsJsonContext.Default.Cfg); // throws if bad + } + catch + { + try + { + File.Copy(path, Path.Combine(SettingsDir, SettingsBadFileName), overwrite: true); + _ctx.Chat("[Vaulted Dungeons] settings.json would not read — kept a copy as " + + SettingsBadFileName + "."); + } + catch { /* best effort */ } + } + } + string json = JsonSerializer.Serialize(_cfg, IltVaultedDungeonsJsonContext.Default.Cfg); + File.WriteAllText(path, json); + _lastGoodJson = json; + } + catch (Exception ex) + { + RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings save failed: {ex.Message}"); + } + } + + private static Cfg Sanitize(Cfg c) + { + // Never resumed from disk: the file keeps its "active" field, but a relog (or turning the + // master switch back on) starts Off. Auto Start On Arrival is the only way back in by itself. + c.Active = false; + c.Dungeon = ClampInt(c.Dungeon, 0, Dungeons.Length, 0); + c.Gem = ClampInt(c.Gem, 0, GemNames.Length, 0); + c.QuitMinutes = ClampInt(c.QuitMinutes, QuitMin, QuitMax, 2); + c.AttackPower = Powers[PowerIndex(c.AttackPower)].Value; + return c; + } + + private static int ClampInt(int v, int lo, int hi, int def) + => v < lo || v > hi ? def : v; + + private static int PowerIndex(float v) + { + int best = 0; + float bestGap = float.MaxValue; + for (int i = 0; i < Powers.Length; i++) + { + float gap = Math.Abs(Powers[i].Value - v); + if (gap < bestGap) { best = i; bestGap = gap; } + } + return best; + } + + private static string PowerText(float p) + { + string t = p.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture); + return t; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + // The hard rules first: ILT only, master switch on. Nothing below runs otherwise (not even + // reading the settings file), and a keeper that was running is stopped on the spot. + if (!Allowed(out string gate)) + { + StopForGate(gate); + PublishGate(gate); + return; + } + + EnsureLoaded(); + SaveIfDirty(); + + // Time in dungeon (kills/hour): only while last state was "in". + if (_lastTickMs > 0 && _state == "in") + _dungeonSecs += Math.Max(0, (nowMs - _lastTickMs) / 1000); + _lastTickMs = nowMs; + + if (!_ctx.Host.HasGetPlayerPose || !_ctx.Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) || cell == 0) + { + Publish(); + return; + } + + uint landblock = cell >> 16; + bool portaling = _ctx.Host.HasIsPortaling && _ctx.Host.IsPortaling(); + VaultedDungeon? dungeon = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length + ? Dungeons[_cfg.Dungeon - 1] + : null; + + // Present check (for Auto Start / arrive actions) even while Off. + if (dungeon == null) + _presentBefore = null; + else if (!portaling) + { + bool here = landblock == dungeon.Value.Landblock; + if (here && _presentBefore != true) OnArrive(dungeon.Value, nowMs); + _presentBefore = here; + } + + _quitLeftMs = null; + if (!_cfg.Active) + { + _state = "paused"; + _outSinceMs = 0; + Publish(); + return; + } + + string? gemName = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length ? GemNames[_cfg.Gem - 1] : null; + if (dungeon == null || gemName == null) + { + _state = "setup"; + _wasInside = false; + Warn(nowMs, dungeon == null + ? "Pick a dungeon in the Vaulted Dungeons tab." + : "Pick a recall gem in the Vaulted Dungeons tab."); + Publish(); + return; + } + + bool inside = landblock == dungeon.Value.Landblock; + if (inside && !portaling) + { + if (!_wasInside) + { + _clockStartMs = nowMs; + _inSinceMs = nowMs; + } + _wasInside = true; + _outSinceMs = 0; + _portalSinceMs = 0; + _state = "in"; + _idleSecs = Math.Max(0, (nowMs - _clockStartMs) / 1000); + if (_cfg.Quit) + { + long quitAfterMs = _cfg.QuitMinutes * 60_000L; + _quitLeftMs = Math.Max(0, quitAfterMs - (nowMs - _clockStartMs)); + if (nowMs - _clockStartMs >= quitAfterMs && !_quitSent) + { + // Once per activation, and only if ILT, the master switch and Active are all + // still true right now (asked again: they may have changed since the top of the tick). + string nowGate = string.Empty; + if (!_cfg.Active || !Allowed(out nowGate)) + { + StopForGate(nowGate); + PublishGate(nowGate); + return; + } + _quitSent = true; + _ctx.Chat($"[Vaulted Dungeons] No kill in {_cfg.QuitMinutes} minute" + + (_cfg.QuitMinutes == 1 ? "" : "s") + " — quitting."); + Invoke(CmdQuit); + } + } + Publish(); + return; + } + + _wasInside = false; + if (portaling) + { + _state = "portal"; + _outSinceMs = 0; + if (_portalSinceMs == 0) _portalSinceMs = nowMs; + Publish(); + return; + } + _portalSinceMs = 0; + + if (_outSinceMs == 0) _outSinceMs = nowMs; + _state = "out"; + + bool tried = _lastRecallMs >= _outSinceMs; + bool due = (!tried && nowMs - _outSinceMs >= FirstRecallAfterMs) + || (tried && nowMs - _lastRecallMs >= RecallAfterMs); + if (due) + { + // Not in the middle of a fight, a buff chain or an unanswered use/cast: the recall waits + // (still due, so it goes out on the first clear tick) and says so on the normal cadence. + string? busy = BusyReason(); + if (busy != null) + { + _state = "busy"; + Warn(nowMs, $"Waiting to use the {gemName}: {busy}."); + } + else if (UseGem(gemName)) + { + _lastRecallMs = nowMs; + _ctx.Chat($"[Vaulted Dungeons] Not in {dungeon.Value.Name} — using the {gemName}."); + } + else + { + _state = "nogem"; + Warn(nowMs, $"No {gemName} in your pack."); + } + } + Publish(); + } + + /// + /// Why a recall gem must not be used now, or null when it may. RynthAi's activity (its "RynthAi.Activity" + /// bits: combat, buffing, loot, salvage, crafting, a use/cast waiting on the server) and the client's + /// busy hourglass; RynthAi not answering counts as busy (nothing is known, so nothing is used). + /// + private string? BusyReason() + { + RynthAiActivity? a = Activity(); + if (a is null) return "RynthAi is not ready"; + RynthAiActivity f = a.Value; + if ((f & RynthAiActivity.Combat) != 0) return "RynthAi is in combat"; + if ((f & RynthAiActivity.Buffing) != 0) return "RynthAi is buffing"; + if ((f & RynthAiActivity.ServerAction) != 0) return "RynthAi is waiting on the server"; + if ((f & RynthAiActivity.Looting) != 0) return "RynthAi is looting"; + if ((f & RynthAiActivity.Salvaging) != 0) return "RynthAi is salvaging"; + if ((f & RynthAiActivity.Crafting) != 0) return "RynthAi is crafting"; + if (_ctx.Inventory.IsBusy) return "the client is busy"; + return null; + } + + /// + /// A rule failed (not ILT any more, or the master switch went off): a running keeper stops at once + /// and says so once; an idle one has nothing to do. Safe to call every tick. + /// + private void StopForGate(string gate) + { + _outSinceMs = 0; + _wasInside = false; + _quitLeftMs = null; + _presentBefore = null; + if (!_cfg.Active) return; + _cfg.Active = false; + _dirty = true; + _state = "paused"; + _ctx.Chat("[Vaulted Dungeons] Stopped: " + (gate == GateWorld + ? "this is not an Infinite Leaftide / ACECustom world." + : "\"Vaulted Dungeons\" was turned off in Settings > Navigation.")); + SaveIfDirty(); + } + + /// The idle snapshot (only when the reason changes: nothing else runs while gated). + private void PublishGate(string gate) + { + if (gate == _publishedGate) return; + _publishedGate = gate; + Publish(gate); + } + + public bool OnChat(string text) + { + if (string.IsNullOrEmpty(text)) return false; + string line = text.TrimEnd(); + bool luminance = KillLine.IsMatch(line); + // A pet-capture success counts as a kill for the timer too (the same replies RynthAi's Pets + // tab matches); nothing else is guessed. + if (!luminance && !PetCaptureLines.IsSuccess(line)) return false; + if (!_cfg.Active || !Allowed(out _)) return false; + NoteKill(Now(), countKill: luminance); + return false; // never eat the luminance line + } + + /// + /// The server's killer notification: this character landed a killing blow (RynthILTPlugin + /// .OnKillNotification, pump thread). Restarts the no-kill timer, like the luminance line. + /// + public void OnKillNotification() + { + if (!_cfg.Active || !Allowed(out _)) return; + NoteKill(Now(), countKill: false); + } + + /// Restarts the Kill Client timer. The kill counter moves only on the luminance line (one per kill). + private void NoteKill(long now, bool countKill) + { + _clockStartMs = now; + _realKillMs = now; + if (countKill && _state == "in") _kills++; + Publish(); + } + + public void OnLogout() + { + // Logging out ends the run: Active is never carried over (see Sanitize). + _cfg.Active = false; + SaveIfDirty(); + _wasInside = false; + _outSinceMs = 0; + _presentBefore = null; + _state = "paused"; + Publish(); + } + + // ── Arrive / commands ─────────────────────────────────────────────────── + + private void OnArrive(VaultedDungeon dungeon, long nowMs) + { + // Only called while ILT and the master switch are on (Tick's gate), so Auto Start is honoured here only. + if (_cfg.AutoStart && !_cfg.Active) + { + Activate(nowMs); + _ctx.Chat($"[Vaulted Dungeons] Arrived in {dungeon.Name} — switched On (Auto Start On Arrival)."); + } + // The arrival settings are part of running the keeper: nothing is sent while it is Off. + if (!_cfg.Active) return; + if (_cfg.DisableMeta) Invoke(CmdMetaOff); + if (_cfg.DisableNav) Invoke(CmdNavOff); + if (_cfg.RepeatAttack) Invoke(CmdRepeatOn); + if (_cfg.SetPower) Invoke(CmdAttackBar + PowerText(_cfg.AttackPower)); + } + + private void Invoke(string cmd) + { + if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd); + } + + private void Warn(long nowMs, string text) + { + if (nowMs - _lastWarnMs < WarnEveryMs) return; + _lastWarnMs = nowMs; + _ctx.Chat("[Vaulted Dungeons] " + text); + } + + /// Pump-thread: /ilt vaulted [on|off|toggle|status]. + public bool HandleCommand(string[] args) + { + // ILT only, master switch on: otherwise the only answer is why (the keeper itself stays idle). + if (!Allowed(out string gate)) + { + if (_cfg.Active) StopForGate(gate); + _ctx.Chat("[Vaulted Dungeons] " + GateReply(gate)); + return true; + } + + EnsureLoaded(); + string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status"; + switch (sub) + { + case "on": + case "start": + SetActive(true); + return true; + case "off": + case "stop": + SetActive(false); + _ctx.Chat("[Vaulted Dungeons] Off."); + return true; + case "toggle": + SetActive(!_cfg.Active); + if (!_cfg.Active) _ctx.Chat("[Vaulted Dungeons] Off."); + return true; + default: + string d = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length + ? Dungeons[_cfg.Dungeon - 1].Name : "(none)"; + string g = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length + ? GemNames[_cfg.Gem - 1] : "(none)"; + _ctx.Chat($"[Vaulted Dungeons] {(_cfg.Active ? "On" : "Off")} — dungeon={d}, gem={g}, " + + $"kill-client={(_cfg.Quit ? $"{_cfg.QuitMinutes}m" : "off")}, state={_state}."); + _ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: Settings > Navigation > Vaulted Dungeons)"); + return true; + } + } + + /// Starts the keeper (the player's own action, or Auto Start On Arrival). Pump thread; ILT and master already checked. + private void Activate(long nowMs) + { + _cfg.Active = true; + _dirty = true; + _outSinceMs = 0; + _wasInside = false; // the no-kill clock starts when the first in-dungeon tick sees us inside + _clockStartMs = nowMs; + _quitSent = false; // /rc quit: once per activation + _lastRecallMs = 0; + Publish(); + } + + private void SetActive(bool value) + { + if (value) + { + // From the tab's button too (posted to the pump): re-check, the switch may have gone off since. + if (!Allowed(out string gate)) + { + _ctx.Chat("[Vaulted Dungeons] " + GateReply(gate)); + return; + } + EnsureLoaded(); + if (!_cfg.Active) + { + Activate(Now()); + _ctx.Chat("[Vaulted Dungeons] On."); + } + return; + } + _cfg.Active = false; + _outSinceMs = 0; + _dirty = true; + _clockStartMs = Now(); + _wasInside = false; + _quitLeftMs = null; + _state = "paused"; + Publish(); + } + + // ── Render snapshot ───────────────────────────────────────────────────── + + private void Publish(string gate = "") + { + _publishedGate = gate; + lock (_gate) + { + _snap = new Snapshot( + _cfg.Active, _cfg.Dungeon, _cfg.Gem, _cfg.Quit, _cfg.QuitMinutes, + _cfg.ShowInDungeon, _cfg.AutoStart, _cfg.DisableMeta, _cfg.DisableNav, + _cfg.RepeatAttack, _cfg.SetPower, _cfg.AttackPower, + _state, _quitLeftMs, _idleSecs, _inSinceMs, _outSinceMs, _portalSinceMs, + _realKillMs, _kills, _dungeonSecs, Now(), gate); + } + } + + private Snapshot Take() + { + lock (_gate) return _snap; + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + private bool _showAdvanced; + // Pending edits from the UI, applied on the next pump tick via Post. + private void PostEdit(Action edit) + { + _ctx.Post(() => + { + if (!Allowed(out _)) return; // gated while it waited: an edit changes nothing + EnsureLoaded(); + edit(_cfg); + _dirty = true; + Publish(); + }); + } + + public void Render() + { + // Settings load on the pump (Tick); the window only reads the snapshot. + Snapshot s = Take(); + + Vector4 colLabel = new(0.53f, 0.53f, 0.53f, 1f); + Vector4 colValue = new(1f, 1f, 1f, 1f); + Vector4 colGreen = new(0.27f, 0.80f, 0.40f, 1f); + Vector4 colAmber = new(0.95f, 0.65f, 0.20f, 1f); + Vector4 colRed = new(0.90f, 0.30f, 0.30f, 1f); + Vector4 colPurple = new(0.72f, 0.52f, 0.95f, 1f); + Vector4 colTitleRed = new(0.85f, 0.25f, 0.25f, 1f); + + // Title row: Vaulted (red) Dungeons (white) + On/Off + Advanced. + ImGui.TextColored(colTitleRed, "Vaulted"); + ImGui.SameLine(0, ImGui.CalcTextSize(" ").X); + ImGui.TextColored(colValue, "Dungeons"); + + // Not offered right now (the tab is hidden then; this covers a stale frame or a direct open). + if (s.Gate.Length > 0) + { + ImGui.Separator(); + ImGui.TextWrapped(GateReply(s.Gate) ?? "Not available."); + return; + } + ImGui.SameLine(0, 16); + Vector4 pill = s.Active ? colGreen : new(0.85f, 0.10f, 0.10f, 1f); + ImGui.PushStyleColor(ImGuiCol.Button, pill); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, pill); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, pill); + ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.05f, 0.05f, 0.05f, 1f)); + if (ImGui.SmallButton((s.Active ? " On " : " Off ") + "##vdactive")) + _ctx.Post(() => SetActive(!s.Active)); + ImGui.PopStyleColor(4); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip(s.Active + ? "On: keeping this character in the chosen dungeon.\nClick: turn off." + : "Off: doing nothing.\nClick: turn on."); + ImGui.SameLine(); + if (ImGui.SmallButton("Advanced##vdoptions")) _showAdvanced = !_showAdvanced; + + ImGui.Separator(); + + float labelW = ImGui.CalcTextSize("Recall Gem").X + 12; + void Label(string text) + { + ImGui.AlignTextToFramePadding(); + ImGui.TextColored(colLabel, text); + ImGui.SameLine(labelW); + } + + // Status + var (statusWord, statusCol) = s.State switch + { + "in" => ("In Dungeon", colGreen), + "out" => ("Recalling", colAmber), + "portal" => ("Portal Space", colPurple), + "setup" => ("Setup Needed", colAmber), + "nogem" => ("No Gem", colRed), + "busy" => ("Waiting (busy)", colAmber), + _ => ("Not Running", colRed), + }; + long since = s.State == "in" ? s.InSinceMs + : s.State == "out" ? s.OutSinceMs + : s.State == "portal" ? s.PortalSinceMs : 0; + string statusText = statusWord; + if (since > 0) + { + long secs = Math.Max(0, (s.NowMs - since) / 1000); + long h = secs / 3600, m = (secs / 60) % 60, sec = secs % 60; + statusText += h > 0 ? $" ({h}:{m:D2}:{sec:D2})" : $" ({m}:{sec:D2})"; + } + Label("Status"); + ImGui.TextColored(statusCol, statusText); + + // Dungeon combo (0 = pick, 1..N = Dungeons[i-1]) + Label("Dungeon"); + string[] dungeonChoices = BuildDungeonChoices(); + int dungeonIdx = s.Dungeon; + ImGui.SetNextItemWidth(260); + if (ImGui.Combo("##vddungeon", ref dungeonIdx, dungeonChoices, dungeonChoices.Length)) + PostEdit(c => { c.Dungeon = dungeonIdx; }); + + Label("Recall Gem"); + string[] gemChoices = { "Pick a gem", GemNames[0], GemNames[1] }; + int gemIdx = s.Gem; + ImGui.SetNextItemWidth(260); + if (ImGui.Combo("##vdgem", ref gemIdx, gemChoices, gemChoices.Length)) + PostEdit(c => { c.Gem = gemIdx; }); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Tie this gem to the dungeon's portal first."); + + Label("Last Kill"); + if (s.State == "in" && s.RealKillMs > 0) + ImGui.TextUnformatted($"{(s.NowMs - s.RealKillMs) / 1000} s ago"); + else + ImGui.TextUnformatted("-"); + + Label("Session"); + string perHour = s.DungeonSecs < 60 ? "-" + : Commas((long)(s.Kills * 3600.0 / Math.Max(1, s.DungeonSecs))); + ImGui.TextUnformatted($"{Commas(s.Kills)} kills ({perHour} Per Hour)"); + + if (s.QuitLeftMs is long left && s.QuitMinutes > 0) + { + float frac = (float)(left / (double)(s.QuitMinutes * 60_000L)); + string barLabel = $"Kill Client ({left / 60_000}:{(left / 1000) % 60:D2})"; + ImGui.ProgressBar(Math.Clamp(frac, 0f, 1f), new Vector2(-1, ImGui.GetTextLineHeight()), barLabel); + } + + if (_showAdvanced) + { + ImGui.Separator(); + ImGui.TextColored(colValue, "Advanced"); + + bool quit = s.Quit; + if (ImGui.Checkbox("Kill Client##vdquit", ref quit)) + { + bool on = quit; + _ctx.Post(() => + { + if (!Allowed(out _)) return; + EnsureLoaded(); + _cfg.Quit = on; + _cfg.QuitMinutes = ClampInt(_cfg.QuitMinutes, QuitMin, QuitMax, 2); + _clockStartMs = Now(); + _dirty = true; + Publish(); + }); + } + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("No kill for the set minutes in the dungeon: /rc quit closes the client (once per run).\n" + + "The timer restarts on the server's \"You've banked N Luminance.\" line, on your own killing blow,\n" + + "and on a successful pet capture. Kills by pets or fellows that pay you no luminance\n" + + "do NOT restart it, so keep the minutes generous if you hunt with pets."); + + ImGui.SameLine(); + ImGui.TextColored(colLabel, "after"); + ImGui.SameLine(); + if (ImGui.SmallButton($"{s.QuitMinutes} minute{(s.QuitMinutes == 1 ? "" : "s")}##vdmincycle")) + _ctx.Post(() => + { + if (!Allowed(out _)) return; + EnsureLoaded(); + _cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, +1); + _clockStartMs = Now(); + _dirty = true; + Publish(); + }); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + _ctx.Post(() => + { + if (!Allowed(out _)) return; + EnsureLoaded(); + _cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, -1); + _clockStartMs = Now(); + _dirty = true; + Publish(); + }); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Minutes with no kill before Kill Client quits.\nClick: longer. Right-click: shorter. (1, 2, 5, 10, 15, 30)"); + + BoolRow("Auto Start On Arrival##vdautostart", s.AutoStart, + v => PostEdit(c => c.AutoStart = v), + "Switch On by itself when you arrive in the chosen dungeon (logging in there counts)."); + + BoolRow("Disable Meta##vdnometa", s.DisableMeta, + v => PostEdit(c => c.DisableMeta = v), + "On arriving: " + CmdMetaOff); + + BoolRow("Disable Nav##vdnonav", s.DisableNav, + v => PostEdit(c => c.DisableNav = v), + "On arriving: " + CmdNavOff); + + BoolRow("Repeat Attacks On##vdrepeat", s.RepeatAttack, + v => PostEdit(c => c.RepeatAttack = v), + "On arriving: " + CmdRepeatOn); + + BoolRow("Set Attack Power##vdpower", s.SetPower, + v => PostEdit(c => c.SetPower = v), + "On arriving: " + CmdAttackBar + PowerText(s.AttackPower)); + ImGui.SameLine(); + int pi = PowerIndex(s.AttackPower); + if (ImGui.SmallButton(Powers[pi].Name + "##vdpowercycle")) + PostEdit(c => c.AttackPower = Powers[(pi + 1) % Powers.Length].Value); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + PostEdit(c => c.AttackPower = Powers[(pi - 1 + Powers.Length) % Powers.Length].Value); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Fast (0), Medium (0.5) or Full Power (1).\nClick: next. Right-click: back."); + } + + ImGui.Spacing(); + ImGui.TextDisabled("Note: the client sees the landblock, not the layer - standing in the retail copy also counts as \"in it\"."); + ImGui.TextDisabled("Kill Client: pet or fellow kills that pay you no luminance do not restart its timer."); + ImGui.TextDisabled("Recalls wait while RynthAi is in combat, buffing or waiting on the server."); + ImGui.TextDisabled("/ilt vaulted [on|off|toggle|status]"); + } + + private static void BoolRow(string id, bool value, Action set, string tip) + { + bool v = value; + if (ImGui.Checkbox(id, ref v)) set(v); + if (ImGui.IsItemHovered()) ImGui.SetTooltip(tip); + } + + private static string[] BuildDungeonChoices() + { + var list = new string[Dungeons.Length + 1]; + list[0] = "Pick a dungeon"; + for (int i = 0; i < Dungeons.Length; i++) list[i + 1] = Dungeons[i].Name; + return list; + } + + private static int StepPreset(int current, int dir) + { + if (dir > 0) + { + foreach (int m in QuitPresets) if (m > current) return m; + return QuitPresets[0]; + } + for (int i = QuitPresets.Length - 1; i >= 0; i--) + if (QuitPresets[i] < current) return QuitPresets[i]; + return QuitPresets[^1]; + } + + private static string Commas(long n) + { + string s = Math.Abs(n).ToString(); + var chars = new List(); + for (int i = 0; i < s.Length; i++) + { + if (i > 0 && (s.Length - i) % 3 == 0) chars.Add(','); + chars.Add(s[i]); + } + return (n < 0 ? "-" : "") + new string(chars.ToArray()); + } + + // ── Config / snapshot types ───────────────────────────────────────────── + + // internal (not private) so the source-generated IltVaultedDungeonsJsonContext can reach it. + internal sealed class Cfg + { + public bool Active { get; set; } + /// 0 = none, 1..N = Dungeons index. + public int Dungeon { get; set; } + /// 0 = none, 1 = primary, 2 = secondary. + public int Gem { get; set; } + public bool Quit { get; set; } + public int QuitMinutes { get; set; } = 2; + public bool ShowInDungeon { get; set; } + public bool AutoStart { get; set; } + public bool DisableMeta { get; set; } + public bool DisableNav { get; set; } + public bool RepeatAttack { get; set; } + public bool SetPower { get; set; } + public float AttackPower { get; set; } + } + + private readonly record struct Snapshot( + bool Active, int Dungeon, int Gem, bool Quit, int QuitMinutes, + bool ShowInDungeon, bool AutoStart, bool DisableMeta, bool DisableNav, + bool RepeatAttack, bool SetPower, float AttackPower, + string State, long? QuitLeftMs, long IdleSecs, long InSinceMs, long OutSinceMs, long PortalSinceMs, + long RealKillMs, int Kills, long DungeonSecs, long NowMs, string Gate) + { + /// Before the first tick (the tab is only offered while the keeper may run). + public static Snapshot Empty => new(false, 0, 0, false, 2, + false, false, false, false, false, false, 0f, + "paused", null, 0, 0, 0, 0, 0, 0, 0, 0, string.Empty); + } +} + +// Source-generated JSON only: the NativeAOT build (what the installer ships) has reflection-based +// serialization turned off, so JsonSerializer.Deserialize(text, options) failed there and the +// Vaulted Dungeons settings never loaded or saved. Same file format as before (camelCase, +// indented, nulls left out, case-sensitive property names on read). +[JsonSerializable(typeof(IltVaultedDungeons.Cfg))] +[JsonSourceGenerationOptions( + WriteIndented = true, + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +internal partial class IltVaultedDungeonsJsonContext : JsonSerializerContext { } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs index f696ec3..d06001a 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs @@ -123,6 +123,44 @@ internal sealed unsafe class RynthAiClient } } + // ── Vaulted Dungeons (master switch, activity) ────────────────────────── + + /// + /// RynthAi's "Vaulted Dungeons" setting (Settings > Navigation): the master switch of the Vaulted + /// Dungeons keeper, and the only place it is stored. False when RynthAi isn't loaded, is older than + /// the call, hasn't logged in, or has it off (the default): the keeper then does nothing. Any thread. + /// + public bool VaultedDungeonsEnabled + { + get + { + var t = AnyThreadTable; + return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.VaultedDungeonsEnabledOffset) + && t->VaultedDungeonsEnabled != null && t->VaultedDungeonsEnabled() != 0; + } + } + + /// + /// What RynthAi is doing now (its "RynthAi.Activity" interface: combat, buffing, loot, a use or cast + /// waiting on the server...); null when RynthAi isn't loaded or isn't ready. Resolved again every + /// call, as that interface requires (a RynthAi reload frees its table). Pump thread. + /// + public RynthAiActivity? Activity() + { + if (!_host.HasGetPluginInterface) return null; + try + { + var act = (RynthAiActivityApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion); + if (act == null || act->Version < 1 || act->StructSize < (uint)sizeof(RynthAiActivityApiV1) || act->GetActivityFlags == null) return null; + uint flags = 0; + return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null; + } + catch + { + return null; // a RynthAi mid-reload: not there this tick + } + } + // ── Quests (/myquests) ────────────────────────────────────────────────── /// A /myquests flag from RynthAi's tracker (pump thread). diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj index 7e7966a..5172b35 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj @@ -56,6 +56,10 @@ + + + + diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs index a918fbb..58948b4 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs @@ -520,7 +520,11 @@ public sealed class RynthILTPlugin : RynthPluginBase } // The server's killer notification: this character landed the killing blow. - public override void OnKillNotification(string? deathMessage) => _bounties?.OnKill(); + public override void OnKillNotification(string? deathMessage) + { + _bounties?.OnKill(); + _hub?.OnKillNotification(); + } private void DrainTypedBounty() { @@ -674,6 +678,15 @@ public sealed class RynthILTPlugin : RynthPluginBase case "hub": case "rates": break; + case "vaulted": + case "vaulteddungeons": + { + // "/ilt vaulted [on|off|toggle|status]": the Vaulted Dungeons keeper (ILT only; the + // module answers "not available" elsewhere, and while the master switch is off). + if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } + _hub.VaultedDungeons.HandleCommand(args); + return; + } case "settings": case "options": { @@ -694,6 +707,7 @@ public sealed class RynthILTPlugin : RynthPluginBase case "help": ChatLine("[RynthILT] /ilt hub ... (the Mini Remote's ILT tabs; same as /ra hub ...), /ilt guardian ..., /ilt servers [list||default],"); ChatLine("[RynthILT] /ilt bounty [list|refresh] - the tracked ACECustom bounties (the Bounties window: the ILT button on the RynthCore bar, or /rc bounties),"); + ChatLine("[RynthILT] /ilt vaulted [on|off|toggle|status] - Vaulted Dungeons keeper (ILT only; master switch: RynthAi Settings > Navigation > Vaulted Dungeons, off by default),"); ChatLine("[RynthILT] /ilt settings [show|hide|toggle] - the ILT settings: the world verdict, the ILT world names and the server's features (force a server: RynthCore Options > Diagnostics),"); ChatLine("[RynthILT] /ilt fellow [show|hide|toggle] - ILT's /fship commands as buttons (also in the Mini Remote's Fellowship section),"); ChatLine("[RynthILT] /ilt trace [on|off], /ilt debug [on|off]."); diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs index 8bc646e..41a94e2 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs @@ -90,9 +90,12 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _vault = new VaultFeed(text => Host.InvokeChatParser(text)); _view = new InventoryView(_c); + // No bar button of its own: opened from the engine Inventory window's GInv button, the + // Scripts menu or /ginv. _window = _ui.Add(new UiWindow("RynthInventory/Main", "Global Inventory") { DefaultWidth = 640f, DefaultHeight = 600f, MinWidth = 420f, MinHeight = 300f, + BarButton = false, }); Host.Log($"[RynthInventory] {Version} initialized. /ginv opens the window. Files: {_c.Store.Root}"); diff --git a/Plugins/RynthCore.Plugin.RynthNav/Atlas.cs b/Plugins/RynthCore.Plugin.RynthNav/Atlas.cs index 521eaf8..ba34068 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/Atlas.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/Atlas.cs @@ -143,6 +143,22 @@ internal sealed class Atlas // ── Search ─────────────────────────────────────────────────────────────── + /// + /// "a || b || c": the first candidate that is coordinates, or that names a place on the map as a + /// whole word or more ( 60+: "Mite Maze" yes, "Bur" inside "Burun" no), + /// so a loose candidate never picks an unrelated place. Null when none does. + /// + public string? FirstOnMap(string alternatives, bool hasPos, double ns, double ew) + { + foreach (string raw in alternatives.Split("||", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + if (NavCoords.TrySplitCoordsAndName(raw, out _, out _, out _)) return raw; + AtlasLocation? best = FindBest(raw, hasPos, ns, ew); + if (best != null && MatchScore(best.Name, raw) >= 60) return raw; + } + return null; + } + /// How well matches (lower case): 0 = not at all. public static int MatchScore(string name, string q) { diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs index 508cd8f..5668df3 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs @@ -669,6 +669,25 @@ public sealed partial class RynthNavPlugin return true; } + /// + /// "a || b || c": the first candidate that is coordinates, or that names a place on the map + /// as a whole word or more (Atlas.MatchScore 60+: "Mite Maze" yes, "Bur" inside "Burun" no), + /// so a loose candidate never sends the character to an unrelated place. False (and why) + /// when none does. + /// + private bool PickAlternative(string text, out string picked, out string why) + { + why = ""; + bool hasPos = PlayerMapPos(out double pns, out double pew); + picked = _atlas.FirstOnMap(text, hasPos, pns, pew) ?? ""; + if (picked.Length > 0) return true; + // Coordinates are always taken, so here every candidate was a name. + why = _atlas.Locations.Count == 0 + ? "the Atlas isn't loaded (" + _atlasStatus + ")" + : "none of these is a place on the map: " + text.Replace("||", ","); + return false; + } + /// The Atlas place the last ResolveTarget picked (null for bare coordinates). Tick thread. private AtlasLocation? _resolvedPlace; @@ -995,6 +1014,12 @@ public sealed partial class RynthNavPlugin int sp = raw.IndexOf(' '); string cmd = (sp < 0 ? raw : raw.Substring(0, sp)).ToLowerInvariant(); string rest = sp < 0 ? string.Empty : raw.Substring(sp + 1).Trim(); + // "go a || b || c" (Oracle's Dynamic Stamps, any caller): the first candidate on the map. + if (cmd is "go" or "goto" or "route" or "arrow" && rest.Contains("||", StringComparison.Ordinal)) + { + if (!PickAlternative(rest, out string picked, out string why)) { Note(why); return; } + rest = picked; + } switch (cmd) { case "": diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestText.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestText.cs new file mode 100644 index 0000000..643b92f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestText.cs @@ -0,0 +1,41 @@ +// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// +/// The lines a click on a quest prints in chat. Upstream's quest list "thinks" them to the player: +/// the quest's info and hint text ("{flag}: {details}", or "{flag}: No hint available"), its wiki +/// link ("{flag}: No url available" when there is none), and the flag's own history +/// ("{flag}: {description} CompletedOn:... Solves:... MaxSolves:... RepeatTime:...", or +/// "{flag}: Never completed"). The texts come from the quest list's Info and Hint columns. +/// +internal static class QuestText +{ + public static List Lines(Quest q, QuestFlagStore flags, QuestBook book, DateTime utcNow) + { + string flag = q.Flag; + var lines = new List(); + + string status = q.IsComplete(flags) ? q.Status(flags, utcNow) : "not done"; + string name = q.IsNew ? (q.Name.Length > 0 ? q.Name : "Not in the quest list") : q.DisplayName; + lines.Add($"{name} ({flag}) - {status}"); + + string details = q.Details(); + lines.Add(details.Length > 0 ? $"{flag}: {details}" : $"{flag}: No hint available"); + lines.Add(q.Url.Length > 0 ? $"{flag}: {q.Url}" : $"{flag}: No url available"); + lines.Add(History(flag, flags)); + + if (book.TryGetReward(flag, out QuestReward r)) lines.Add("Rewards: " + r.LongSummary()); + return lines; + } + + /// Upstream's QuestFlag.ToString(), or "Never completed" for a flag the character doesn't hold. + public static string History(string flag, QuestFlagStore flags) + { + if (!flags.TryGet(flag, out QuestFlag f)) return $"{flag}: Never completed"; + string done = f.CompletedOnUtc == DateTime.MinValue ? "never" : f.CompletedOnUtc.ToLocalTime().ToString("yyyy-MM-dd HH:mm"); + return $"{f.Key}: {f.Description} CompletedOn:{done} Solves:{f.Solves} MaxSolves:{f.MaxSolves} RepeatTime:{TimeText.Friendly(f.RepeatTime)}"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestTimerWatcher.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestTimerWatcher.cs new file mode 100644 index 0000000..b4ddd68 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestTimerWatcher.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// +/// Notices when a quest timer comes up. It remembers which watched quests were on cooldown and +/// reports each one once, the moment its timer runs out. A quest that is simply ready when first +/// seen (the login read) is not reported: only the step from waiting to ready is. +/// +internal sealed class QuestTimerWatcher +{ + private readonly HashSet _waiting = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _seen = new(StringComparer.OrdinalIgnoreCase); + private readonly List _ready = new(); + + /// Forget everything (logout, or a different character). + public void Reset() => _waiting.Clear(); + + /// + /// Checks the watched quests and returns those whose timers came up since the last check (the + /// list is reused: read it before the next call). is the flags to + /// watch, or null for every quest the character holds. + /// + public IReadOnlyList Check(QuestFlagStore flags, QuestCatalog catalog, IEnumerable? watch, DateTime utcNow) + { + _ready.Clear(); + if (flags.LastReadUtc == DateTime.MinValue) return _ready; + + _seen.Clear(); + foreach (string flag in watch ?? flags.Flags.Keys) + { + _seen.Add(flag); + Quest q = catalog.TryGet(flag, out Quest known) ? known : new Quest { Flag = flag, IsNew = true }; + if (!flags.TryGet(flag, out _)) { _waiting.Remove(flag); continue; } + QuestTimerState state = QuestTimer.State(q, flags, utcNow, out _); + if (state == QuestTimerState.Waiting) _waiting.Add(flag); + else if (state == QuestTimerState.Ready && _waiting.Remove(flag)) _ready.Add(q); + else _waiting.Remove(flag); // in progress, or done for good + } + _waiting.RemoveWhere(k => !_seen.Contains(k)); // no longer watched + return _ready; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs index bc841aa..aa5dbef 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs @@ -12,6 +12,7 @@ internal sealed class OracleContext public readonly OracleSettings Settings = new(); public readonly QuestFlagStore Flags = new(); public readonly QuestCatalog Catalog = new(); + public readonly QuestTimerWatcher Timers = new(); public readonly QuestCatalogUpdater Updater = new(); /// This character's tracked quests and recorded rewards (loaded once the name is known). public readonly QuestBook Book = new(); @@ -42,8 +43,20 @@ internal sealed class OracleContext /// The last thing the quest list check said, shown on the About tab. public string UpdaterMessage = ""; - /// Set by the plugin: sends /myquests (reply hidden when the setting says so). - public Action RequestQuests = () => { }; + /// Set by the plugin: sends /myquests (reply hidden when the setting says so). False when nothing was sent (not in world, or one went out moments ago). + public Func RequestQuests = () => false; + + /// Set by the plugin (the Refresh buttons): re-reads the character's stats and buffs, and RynthAi's session, at once. + public Action RereadCharacter = () => { }; + + /// Set by the plugin: re-reads the titles the engine holds for the character. + public Action RereadTitles = () => { }; + + /// Set by the plugin: reloads the quest list and server pack from their files and re-asks RynthCore which server this is. + public Action ReloadQuestList = () => { }; + + /// Where goes instead of the chat window (the offline tests). + public Action? PrintSink = null; /// Set by the plugin: sends a chat command to the server as if typed (the views' buttons). public Func Send = _ => false; @@ -61,7 +74,14 @@ internal sealed class OracleContext /// A line in the player's chat window only (nothing is sent to the server). public void Print(string text) { + if (PrintSink != null) { PrintSink(text); return; } if (!Host.WriteToChat("[RynthOracle] " + text, 1)) Host.Log("[RynthOracle] " + text); } + + /// A click on a quest: its info and hint text, link and flag history in chat (upstream "thinks" them). + public void PrintQuest(Quest q) + { + foreach (string line in QuestText.Lines(q, Flags, Book, UtcNow)) Print(line); + } } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs index 68df70f..4aa69dc 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs @@ -29,6 +29,10 @@ internal sealed class OracleSettings public string TabName = "Quests"; /// ConquestAC: "/bank deposit" at every ten-minute mark (upstream's auto-deposit; off by default). public bool ConquestAutoDeposit; + /// Say so in chat when a tracked quest's timer comes up. + public bool AlertTimers = true; + /// false: only tracked quests are watched; true: every quest the character holds. + public bool AlertAllTimers; private static string FilePath => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json"); @@ -48,6 +52,8 @@ internal sealed class OracleSettings MainWindowOpen = Bool(r, "mainWindowOpen", MainWindowOpen); QuestTimersOpen = Bool(r, "questTimersOpen", QuestTimersOpen); ConquestAutoDeposit = Bool(r, "conquestAutoDeposit", ConquestAutoDeposit); + AlertTimers = Bool(r, "alertTimers", AlertTimers); + AlertAllTimers = Bool(r, "alertAllTimers", AlertAllTimers); if (r.TryGetProperty("tabName", out JsonElement t) && t.ValueKind == JsonValueKind.String) TabName = t.GetString() ?? TabName; if (r.TryGetProperty("lastQuestListCheck", out JsonElement c) && c.ValueKind == JsonValueKind.String && DateTime.TryParse(c.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime when)) @@ -73,6 +79,8 @@ internal sealed class OracleSettings sb.Append(" \"mainWindowOpen\": ").Append(MainWindowOpen ? "true" : "false").Append(",\n"); sb.Append(" \"questTimersOpen\": ").Append(QuestTimersOpen ? "true" : "false").Append(",\n"); sb.Append(" \"conquestAutoDeposit\": ").Append(ConquestAutoDeposit ? "true" : "false").Append(",\n"); + sb.Append(" \"alertTimers\": ").Append(AlertTimers ? "true" : "false").Append(",\n"); + sb.Append(" \"alertAllTimers\": ").Append(AlertAllTimers ? "true" : "false").Append(",\n"); sb.Append(" \"tabName\": \"").Append(JsonEncodedText.Encode(TabName).ToString()).Append("\"\n"); sb.Append("}\n"); Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs index d3c9231..1babccf 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs @@ -38,7 +38,7 @@ public static unsafe class PluginExports public static IntPtr GetVersion() { // Keep in step with RynthOraclePlugin.Version (a u8 literal can't be built from a const string). - try { return LiteralPointer("0.2.1"u8); } + try { return LiteralPointer("0.2.2"u8); } catch { return IntPtr.Zero; } } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs index 1cd8e30..60b8190 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs @@ -18,8 +18,8 @@ namespace RynthCore.Plugin.RynthOracle; /// public sealed class RynthOraclePlugin : RynthPluginBase { - // Previous release: 0.2.0. - public const string Version = "0.2.1"; + // Previous release: 0.2.1. + public const string Version = "0.2.2"; private const long QuestReadDelayMs = 6000; // after login, before the hidden /myquests private const long CharacterReadMs = 1000; @@ -33,6 +33,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase private OracleView? _mainView; private VoidView? _voidView; private QuestTimersView? _timersView; + private SkillsEmbed? _skills; private int _seenBookRevision = -1; private readonly ConcurrentQueue _commands = new(); @@ -57,11 +58,16 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Host = Host; _c.Settings.Load(); _c.RequestQuests = RequestQuests; + _c.RereadCharacter = RereadCharacter; + _c.RereadTitles = RereadTitles; + _c.ReloadQuestList = ReloadQuestList; _c.Send = cmd => _c.InWorld && Host.InvokeChatParser(cmd); _c.RunCommand = cmd => _c.InWorld && Host.InvokeChatParser(cmd); _ui.Log = msg => Host.Log(msg); _mainView = new OracleView(_c); + // The Skills / Attributes / Progress tabs: RynthCore draws its Skills panel body in the window. + _skills = new SkillsEmbed(cmd => Host.InvokeChatParser(cmd)); _voidView = new VoidView(_c); _timersView = new QuestTimersView(_c); _main = _ui.Add(new UiWindow("RynthOracle/Oracle", "Oracle") @@ -135,6 +141,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (_void != null) { _void.Visible = false; _void.NeedsPass = true; } // The quest book loads once the character's name (and world) are known (TickData). _c.Book.Clear(); + _c.Timers.Reset(); if (_timers != null) { _timers.Visible = _c.Settings.QuestTimersOpen; _timers.NeedsPass = true; } } @@ -146,8 +153,10 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (_main != null) { _main.Visible = false; _main.NeedsPass = true; } if (_void != null) { _void.Visible = false; _void.NeedsPass = true; } if (_timers != null) { _timers.Visible = false; _timers.NeedsPass = true; } + _skills?.Update(string.Empty, false, false, Environment.TickCount64); _ui.SubmitEmpty(Host); _c.Book.Clear(); // saved as it changed + _c.Timers.Reset(); _c.Flags.Clear(); _c.Void.Clear(); _c.Conquest.Clear(); @@ -214,6 +223,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase public override void Shutdown() { + _skills?.Shutdown(); _ui.SubmitEmpty(Host); _c.Updater.Shutdown(); _c.Settings.Save(); @@ -315,6 +325,21 @@ public sealed class RynthOraclePlugin : RynthPluginBase // RynthAi, RynthILT and RynthCore's menus link here; it shows, never toggles off. ShowTab(OracleView.TabCharacter); break; + case "skills": + case "skill": + // The Skills tab: RynthCore's skills panel (raise and train) inside this window. + ShowTab(OracleView.TabSkills); + break; + case "attributes": + case "attrs": + case "attribute": + case "vitals": + ShowTab(OracleView.TabAttributes); + break; + case "progress": + case "progression": + ShowTab(OracleView.TabProgress); + break; case "status": string pack = _c.Catalog.PackServer.Length > 0 ? $" + {_c.Catalog.ServerCount} {_c.Catalog.PackServer}" : ""; string titles = _c.TitlesKnown ? $", {_c.EarnedTitles.Count} titles held" : ""; @@ -327,12 +352,14 @@ public sealed class RynthOraclePlugin : RynthPluginBase ShowTab(OracleView.TabAbout); break; default: - _c.Print("Commands: /ro (window), /ro character (Character tab: status, session), /ro void (Void window), " + _c.Print("Commands: /ro (window), /ro character (Character tab: status, session), " + + "/ro skills|attributes|progress (those tabs), /ro void (Void window), " + "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), /ro quests (read quest flags), /ro status, " + "/ro about (About tab: settings, server)"); break; } if (arg is "" or "void" or "timers" or "timer" or "fellowship" or "fellow" or "fship" or "character" or "char" + or "skills" or "skill" or "attributes" or "attrs" or "attribute" or "vitals" or "progress" or "progression" or "about" && !Host.HasUi && !_noUiLogged) { _noUiLogged = true; @@ -340,11 +367,54 @@ public sealed class RynthOraclePlugin : RynthPluginBase } } - private void RequestQuests() + /// Sends /myquests; false when nothing went out (not in the world, or one was sent moments ago). + private bool RequestQuests() + { + if (!_c.InWorld) return false; + bool sent = _c.Flags.Request(cmd => Host.InvokeChatParser(cmd), Environment.TickCount64); + if (!sent) Host.Log("[RynthOracle] /myquests was sent moments ago; waiting for that reply."); + if (_main != null) _main.NeedsPass = true; + return sent; + } + + // ── The Oracle window's Refresh buttons (the data side; Views\RefreshBar.cs has the rest) ── + + /// Reads the character's stats, buffs and (on the Character tab) RynthAi's session now, not at the next timer. + private void RereadCharacter() { if (!_c.InWorld) return; - if (!_c.Flags.Request(cmd => Host.InvokeChatParser(cmd), Environment.TickCount64)) - Host.Log("[RynthOracle] /myquests was sent moments ago; waiting for that reply."); + long now = Environment.TickCount64; + _c.Character.Read(Host); + _c.Void.RemoveExpired(now); + _nextCharacterReadMs = now + CharacterReadMs; + _nextCharacterExtrasMs = 0; + ReadCharacterExtras(now); + if (_main != null) _main.NeedsPass = true; + if (_void != null) _void.NeedsPass = true; + } + + /// Asks the engine for the character's titles again (it keeps them from the login events). + private void RereadTitles() + { + _titleCount = -2; + ReadTitles(); + if (_main != null) _main.NeedsPass = true; + } + + /// + /// Reloads the quest list and the server's pack from their files (a downloaded list, or a pack + /// dropped into %APPDATA%\RynthCore\RynthOracle\packs) and asks RynthCore which server this is. + /// + private void ReloadQuestList() + { + long now = Environment.TickCount64; + _c.ServerState.Poll(Host, now, force: true); + _seenServerStateRevision = _c.ServerState.Revision; + _c.Server.Refresh(Host, _c.Character.PlayerId != 0 ? _c.Character.PlayerId : Host.GetPlayerId(), _c.ServerState.State); + try { _c.Catalog.Load(_c.Server.Tag, msg => Host.Log(msg)); } + catch (Exception ex) { Host.Log($"[RynthOracle] Couldn't load the quest list: {ex.Message}"); } + _c.Catalog.SyncDiscoveries(_c.Flags); + ApplyServer(); if (_main != null) _main.NeedsPass = true; } @@ -362,6 +432,9 @@ public sealed class RynthOraclePlugin : RynthPluginBase TickData(now); if (!Host.HasUi) return; + // After the poll, so a tab clicked this tick is already selected. + if (_skills != null && _main != null && _mainView != null) + _skills.Update(_mainView.Tab, _main.Visible, _c.InWorld, now); RecordWindows(now); _ui.Submit(Host, now); @@ -454,6 +527,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Server.Refresh(Host, _c.Character.PlayerId, _c.ServerState.State); ApplyServer(); LoadQuestBook(now); + AnnounceTimers(); ReadTitles(); TickConquest(now); if (!_voidAutoDecided && _c.Character.Valid) @@ -475,6 +549,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase } } + /// Says in chat which watched quest timers came up: tracked quests, or every held quest if so set. + private void AnnounceTimers() + { + if (!_c.Settings.AlertTimers || !_c.Book.Loaded) { _c.Timers.Reset(); return; } + var ready = _c.Timers.Check(_c.Flags, _c.Catalog, _c.Settings.AlertAllTimers ? null : _c.Book.Tracked, _c.UtcNow); + foreach (Quest q in ready) + _c.Print($"Quest ready again: {q.Label}"); + } + /// /// Loads this character's quest book (tracked quests, rewards) once the name is known and the /// world has been announced, or after without one (then filed diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs index 3e76598..7af7c22 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs @@ -21,6 +21,9 @@ internal sealed partial class OracleView w.Checkbox("Hide the replies to RynthOracle's own requests", "o.hide", s.HideOwnQuestReplies, v => { s.HideOwnQuestReplies = v; s.Save(); }); w.Tooltip("/myquests, and on their servers /b, /augs, /top and the like. A command you type yourself always shows its reply."); w.Checkbox("Show the Void window for characters with Void Magic", "o.void", s.AutoShowVoidWindow, v => { s.AutoShowVoidWindow = v; s.Save(); }); + w.Checkbox("Say in chat when a quest timer comes up", "o.alert", s.AlertTimers, v => { s.AlertTimers = v; s.Save(); }); + w.Tooltip("Watches the quests you track (the * on the Quests tab) and prints a line the moment a cooldown ends."); + w.Checkbox("...for every quest you hold, not just tracked ones", "o.alertall", s.AlertAllTimers, v => { s.AlertAllTimers = v; s.Save(); }); w.Checkbox("Check once a day for a newer quest list", "o.daily", s.CheckQuestListDaily, v => { s.CheckQuestListDaily = v; s.Save(); }); w.Tooltip("Downloads Oracle of Dereth's master quest list from GitHub, as the original plugin does."); @@ -64,6 +67,7 @@ internal sealed partial class OracleView w.SeparatorText("Commands"); w.BulletText("/ro open or close this window"); w.BulletText("/ro character the Character tab (status, session)"); + w.BulletText("/ro skills the Skills tab (raise and train); /ro attributes, /ro progress likewise"); w.BulletText("/ro timers open or close the Quest Timers window"); w.BulletText("/ro fellowship the Fellowship tab"); w.BulletText("/ro about this tab (settings, server)"); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/BoardsTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/BoardsTab.cs index 3b2d806..60e1c75 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/BoardsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/BoardsTab.cs @@ -34,9 +34,6 @@ internal sealed partial class OracleView w.ToggleButton(cq.Boards[i].Label, "cb.tab." + i, i == _conquestBoard, () => _conquestBoard = index, small: true); } ConquestBoard b = cq.Boards[_conquestBoard]; - w.Button("Refresh", "cb.refresh", () => _c.Send(cq.RequestBoard(b, _c.NowMs))); - w.Tooltip($"Sends {b.Command} and reads the reply."); - w.SameLine(); w.TextDisabled(b.UpdatedUtc == DateTime.MinValue ? "not read yet" : $"read at {b.UpdatedUtc.ToLocalTime():HH:mm}"); if (b.You != null) w.Text($"You: #{b.You.Rank} with {b.You.Value}"); DrawRows(w, "cb.rows", b.Rows); @@ -76,8 +73,6 @@ internal sealed partial class OracleView if (_aelrynthView == 1) { - w.Button("Refresh", "ab.me", () => _c.Send(a.RequestTop("me", _c.NowMs))); - w.Tooltip("Sends /top me."); w.BeginChild("ab.melist", 0f, 0f, border: true); foreach (AelrynthStanding s in a.Standings) { @@ -93,9 +88,6 @@ internal sealed partial class OracleView if (_aelrynthView == 2) { - w.Button("Refresh", "ab.trials", () => _c.Send(a.RequestTrial("", _c.NowMs))); - w.Tooltip("Sends /trial."); - w.SameLine(); w.InputText("Dungeon", "ab.trialarg", _trialArg, 48, s => _trialArg = s); w.SameLine(); w.Button("Top 10", "ab.trialtop", () => { if (_trialArg.Trim().Length > 0) _c.Send(a.RequestTrial(_trialArg, _c.NowMs)); }); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/ConquestTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/ConquestTab.cs index 63a1b61..1964c09 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/ConquestTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/ConquestTab.cs @@ -44,9 +44,6 @@ internal sealed partial class OracleView private void DrawConquestBank(UiWindow w) { ConquestData cq = _c.Conquest; - w.Button("Refresh", "cq.bank.refresh", () => _c.Send(cq.RequestBank(_c.NowMs))); - w.Tooltip("Sends /b and reads your balances."); - w.SameLine(); w.TextDisabled(ReadAt(cq.BankUtc)); foreach (NamedValue b in cq.Bank.OrderBy(b => b.Name, StringComparer.OrdinalIgnoreCase)) { @@ -90,9 +87,6 @@ internal sealed partial class OracleView private void DrawConquestAugs(UiWindow w) { ConquestData cq = _c.Conquest; - w.Button("Refresh", "cq.augs.refresh", () => _c.Send(cq.RequestAugs(_c.NowMs))); - w.Tooltip("Sends /augs."); - w.SameLine(); w.TextDisabled($"{ReadAt(cq.AugsUtc)}, {cq.AugTotal} in total"); w.TextDisabled("Aug"); w.SameLine(120f); w.TextDisabled("Have"); w.SameLine(170f); w.TextDisabled("Next costs"); w.SameLine(330f); w.TextDisabled("Effect now"); foreach (ConquestAug a in cq.Augs) @@ -111,9 +105,6 @@ internal sealed partial class OracleView private void DrawConquestEnl(UiWindow w) { ConquestData cq = _c.Conquest; - w.Button("Refresh", "cq.enl.refresh", () => _c.Send(cq.RequestEnl(_c.NowMs))); - w.Tooltip("Sends /enl augs."); - w.SameLine(); w.TextDisabled(ReadAt(cq.EnlUtc)); foreach (NamedValue a in cq.EnlAugs) { @@ -157,9 +148,6 @@ internal sealed partial class OracleView w.Text($"Next costs {TimeText.Number(ConquestData.EnlCoinCost(target))} coins and {(ConquestData.EnlLuminanceCost(target) / 1_000_000.0):0.##}M luminance"); w.SeparatorText("Experience bonuses"); - w.Button("Refresh", "cq.bonus.refresh", () => _c.Send(cq.RequestBonus(_c.NowMs))); - w.Tooltip("Sends /bonus."); - w.SameLine(); w.TextDisabled(ReadAt(cq.BonusUtc)); foreach (NamedValue b in cq.Bonuses) { @@ -172,9 +160,6 @@ internal sealed partial class OracleView private void DrawConquestFships(UiWindow w) { ConquestData cq = _c.Conquest; - w.Button("Refresh", "cq.fship.refresh", () => _c.Send(cq.RequestFships(_c.NowMs))); - w.Tooltip("Sends /fship list."); - w.SameLine(); w.TextDisabled($"{ReadAt(cq.FshipUtc)}, {cq.Fellowships.Count} looking for members"); w.Combo("Sort", "cq.fship.sort", _fshipSort, new[] { "Name", "Leader", "Most members", "Location" }, i => _fshipSort = i); var list = _fshipSort switch diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs index 949dce7..46c3242 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs @@ -9,12 +9,18 @@ namespace RynthCore.Plugin.RynthOracle.Views; /// internal sealed partial class OracleView { - public const string TabQuests = "Quests", TabCharacter = "Character", TabAugs = "Augs", TabSociety = "Society", + public const string TabQuests = "Quests", TabCharacter = "Character", + TabSkills = "Skills", TabAttributes = "Attributes", TabProgress = "Progress", + TabAugs = "Augs", TabSociety = "Society", TabMarkers = "Markers", TabTitles = "Titles", TabVoid = "Void", TabFellowship = "Fellowship", TabBoards = "Leaderboards", TabConquest = "Conquest", TabAbout = "About"; - /// A tab: shown where any of its server tags matches the server; no tags = everywhere (retail). - private sealed record TabDef(string Name, string[] Servers, Action Draw, bool LiveTimers); + /// + /// A tab: shown where any of its server tags matches the server; no tags = everywhere (retail). + /// Refresh is the page's Refresh button (Views\RefreshBar.cs); Help its tooltip. + /// + private sealed record TabDef(string Name, string[] Servers, Action Draw, bool LiveTimers, + Func Refresh, Func Help); private readonly OracleContext _c; private readonly TabDef[] _tabs; @@ -29,18 +35,35 @@ internal sealed partial class OracleView string[] any = Array.Empty(); _tabs = new TabDef[] { - new(TabQuests, any, DrawQuests, true), - new(TabCharacter, any, DrawCharacter, true), - new(TabAugs, any, DrawAugs, true), - new(TabSociety, any, DrawSociety, true), - new(TabMarkers, any, DrawMarkers, false), - new(TabTitles, any, DrawTitles, false), - new(TabVoid, any, DrawVoid, true), - new(TabFellowship, any, DrawFellowship, false), + new(TabQuests, any, DrawQuests, true, () => RefreshQuests(), + () => "Sends /myquests to the server and reads the reply."), + new(TabCharacter, any, DrawCharacter, true, RefreshCharacter, + () => "Re-reads your level, experience, buffs and skills from the game now (and RynthAi's session)."), + // Skills / Attributes / Progress: RynthCore draws its Skills panel body under the tab + // strip (SkillsEmbed). The engine's panel reads the game itself, so there is no Refresh row. + new(TabSkills, any, DrawEmbedded, false, RefreshCharacter, + () => "RynthCore's skills panel: raise and train skills."), + new(TabAttributes, any, DrawEmbedded, false, RefreshCharacter, + () => "RynthCore's skills panel: attributes and vitals."), + new(TabProgress, any, DrawEmbedded, false, RefreshCharacter, + () => "RynthCore's skills panel: progression planners (Infinite Leaftide)."), + new(TabAugs, any, DrawAugs, true, RefreshCharacterAndQuests, + () => "Re-reads your character from the game and sends /myquests for the gem timers."), + new(TabSociety, any, DrawSociety, true, RefreshCharacterAndQuests, + () => "Re-reads your society standing from the game and sends /myquests for today's ribbons and quest timers."), + new(TabMarkers, any, DrawMarkers, false, () => RefreshQuests(), + () => "Sends /myquests: the markers you found are in your quest flags."), + new(TabTitles, any, DrawTitles, false, RefreshTitles, + () => "Re-reads the titles you hold from the game."), + new(TabVoid, any, DrawVoid, true, RefreshVoid, + () => "Re-reads your buffs from the game and drops the spell timers that ran out."), + new(TabFellowship, any, DrawFellowship, false, RefreshFellowship, + () => "Re-reads the fellowship and its members from the game."), // Server-specific: each parser and its commands only exist on its own server. - new(TabBoards, new[] { Data.ServerTags.Conquest, Data.ServerTags.Aelrynth }, DrawBoards, false), - new(TabConquest, new[] { Data.ServerTags.Conquest }, DrawConquest, true), - new(TabAbout, any, DrawAbout, false), + new(TabBoards, new[] { Data.ServerTags.Conquest, Data.ServerTags.Aelrynth }, DrawBoards, false, RefreshBoards, BoardsHelp), + new(TabConquest, new[] { Data.ServerTags.Conquest }, DrawConquest, true, RefreshConquest, ConquestHelp), + new(TabAbout, any, DrawAbout, false, RefreshAbout, + () => "Loads the quest list and server pack from their files again and asks RynthCore which server this is."), }; } @@ -103,11 +126,20 @@ internal sealed partial class OracleView return; } + // Skills / Attributes / Progress: nothing more is recorded. The rest of the window is + // the region RynthCore fills with its Skills panel body (see SkillsEmbed), so the page + // has no Refresh row and no child of its own to cover it. + if (SkillsEmbed.IsEmbedTab(tab)) return; + + if (current != null) DrawRefreshRow(w, current); w.BeginChild("page." + tab, 0f, 0f, border: false); (current?.Draw ?? DrawAbout)(w); w.EndChild(); } + /// The Skills-family tabs record nothing: returns before it would call this. + private void DrawEmbedded(UiWindow w) { } + // ── Shared helpers ────────────────────────────────────────────────────── /// "Done" in green or "--" in grey, the status column most lists start with. @@ -125,7 +157,7 @@ internal sealed partial class OracleView w.Text(value); } - /// Prints a quest's name, status, notes and wiki link in chat (upstream "thinks" them). + /// Prints an entry's name, status, notes and wiki link in chat (upstream "thinks" them). Quests print more: . private void PrintEntry(string name, string flag, string status, string details, string url) { _c.Print(flag.Length > 0 ? $"{name} ({flag}){(status.Length > 0 ? " - " + status : "")}" : name); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestTimersView.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestTimersView.cs index e58ab7a..59cb61e 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestTimersView.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestTimersView.cs @@ -54,9 +54,10 @@ internal sealed class QuestTimersView foreach (Quest q in _rows) { string flag = q.Flag; - w.Text(Cut(q.Label, 26)); + Quest row = q; + w.Selectable(Cut(q.Label, 26), "qt.r." + flag, false, () => _c.PrintQuest(row), StatusX - 10f); string reward = _c.Book.RewardText(flag); - w.Tooltip(reward.Length > 0 ? $"{q.Label}\n{flag}\nRewards: {reward}" : $"{q.Label}\n{flag}"); + w.Tooltip((reward.Length > 0 ? $"{q.Label}\n{flag}\nRewards: {reward}" : $"{q.Label}\n{flag}") + "\nClick: prints its texts in chat."); w.SameLine(StatusX); QuestTimerState s = QuestTimer.State(q, flags, now, out string text); bool held = flags.TryGet(flag, out _); @@ -74,7 +75,7 @@ internal sealed class QuestTimersView if (flags.Loading) w.TextColored(UiColors.Yellow, "Reading quest flags..."); else if (flags.LastReadUtc == DateTime.MinValue) w.TextDisabled("Quest flags not read yet."); - w.SmallButton("Refresh", "qt.refresh", _c.RequestQuests); + w.SmallButton("Refresh", "qt.refresh", () => _c.RequestQuests()); w.Tooltip("Sends /myquests and reads the reply (timers count down by themselves between reads)."); if (flags.LastReadUtc != DateTime.MinValue) { diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs index dbfae10..859baa1 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs @@ -51,9 +51,6 @@ internal sealed partial class OracleView else w.Text($"{flags.Flags.Count} quest flags on this character, read at {flags.LastReadUtc.ToLocalTime():HH:mm}."); - w.Button("Refresh", "q.refresh", _c.RequestQuests); - w.Tooltip("Sends /myquests to the server and reads the reply."); - w.SameLine(); bool timersShown = _c.QuestTimersWindowVisible(); w.Button(timersShown ? "Hide quest timers" : "Show quest timers", "q.timers", () => _c.SetQuestTimersWindow(!timersShown)); w.Tooltip("A small window with the quests you track (the * column) and the time left on each."); @@ -125,7 +122,7 @@ internal sealed partial class OracleView w.SameLine(72f); Quest row = q; w.Selectable(Cut(q.Label, 44), "q.r." + flag, flag == _questSel, () => SelectQuest(row), 290f); - w.Tooltip(flag); + w.Tooltip(flag + "\nClick: opens it below and prints its texts in chat."); w.SameLine(370f); TimerText(w, q, flags, now, done); string solves = q.SolvesText(flags); @@ -163,9 +160,14 @@ internal sealed partial class OracleView // ── The opened quest and its rewards ────────────────────────────────── + /// + /// A click opens the quest below the list (a second click closes it) and, as upstream's list + /// does, prints its texts in chat: the info and hint, the wiki link and the flag's history. + /// private void SelectQuest(Quest q) { - if (_questSel == q.Flag) { _questSel = ""; return; } // a second click closes it + _c.PrintQuest(q); + if (_questSel == q.Flag) { _questSel = ""; return; } _questSel = q.Flag; _rewardMsg = ""; LoadRewardEdit(q.Flag); @@ -208,7 +210,7 @@ internal sealed partial class OracleView w.Tooltip("List this quest in the Quest Timers window."); w.SameLine(); Quest print = q; - w.Button("Print in chat", "q.sel.print", () => PrintQuest(print)); + w.Button("Print in chat", "q.sel.print", () => _c.PrintQuest(print)); w.SameLine(); w.Button("Close", "q.sel.close", () => _questSel = ""); @@ -272,13 +274,6 @@ internal sealed partial class OracleView _rewardMsg = r.IsEmpty ? "Cleared." : "Saved: " + r.ShortSummary(); } - private void PrintQuest(Quest q) - { - string status = q.IsComplete(_c.Flags) ? q.Status(_c.Flags, _c.UtcNow) : "not done"; - PrintEntry(q.IsNew ? (q.Name.Length > 0 ? q.Name : "Not in the quest list") : q.DisplayName, q.Flag, status, q.Details(), q.Url); - if (_c.Book.TryGetReward(q.Flag, out QuestReward r)) _c.Print("Rewards: " + r.LongSummary()); - } - // ── Rows ────────────────────────────────────────────────────────────── /// The filtered, sorted rows; rebuilt when the filter or data changed (or every 5 s for timers). diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs new file mode 100644 index 0000000..57f0686 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.RynthOracle.Ui; + +namespace RynthCore.Plugin.RynthOracle.Views; + +/// +/// The Refresh button every page of the Oracle window starts with, and the status line beside it. +/// What "refresh" means depends on where a page's data comes from: +/// - data the server owns (quest flags, ConquestAC's bank and boards, Aelrynth's /top and /trial) +/// is asked for again with the same command the page always used, and the line waits for the +/// reply; +/// - data read from the game client (level, buffs, titles, fellowship) is re-read at once instead +/// of at the next timer; +/// - files (the About page) are loaded again. +/// A page that needs both does both. Nothing here blocks: a request is one chat command, and the +/// same request is refused for after it went out (the quest read has its +/// own 5 s gap), so the button can't spam the server. +/// +internal sealed partial class OracleView +{ + private const long CooldownMs = 3000; + private const long ReplyWaitMs = 15_000; + + /// What a Refresh did, and (when it asked the server) how to tell the reply has landed. + private sealed record RefreshResult(string What, Func? Done = null); + + private string _refreshScope = "", _refreshWhat = ""; + private Func? _refreshDone; + private bool _refreshDoneSeen; + private long _refreshAtMs; + private DateTime _refreshAtUtc, _refreshDoneUtc; + private readonly Dictionary _refreshSent = new(); + + /// The tab, plus the sub-page a tab has (Conquest's views, the boards), so a status line stays with its own page. + private string RefreshScope(string tab) => tab switch + { + TabConquest => tab + _conquestView, + TabBoards => tab + _aelrynthView + _conquestBoard, + _ => tab, + }; + + private void DrawRefreshRow(UiWindow w, TabDef def) + { + string scope = RefreshScope(def.Name); + w.Button("Refresh", "refresh." + scope, () => DoRefresh(def, scope), small: true); + w.Tooltip(def.Help()); + if (_refreshScope != scope || _refreshWhat.Length == 0) return; + + w.SameLine(); + if (_refreshDone != null && !_refreshDoneSeen && _refreshDone()) + { + _refreshDoneSeen = true; + _refreshDoneUtc = _c.UtcNow; + } + if (_refreshDone != null && !_refreshDoneSeen) + { + if (_c.NowMs - _refreshAtMs > ReplyWaitMs) w.TextColored(UiColors.Red, "No reply yet. Press Refresh to ask again."); + else w.TextColored(UiColors.Yellow, _refreshWhat + " Waiting for the reply..."); + } + else if (_refreshDone != null) + w.TextDisabled($"Updated {_refreshDoneUtc.ToLocalTime():HH:mm:ss}. {_refreshWhat}"); + else + w.TextDisabled($"Refreshed {_refreshAtUtc.ToLocalTime():HH:mm:ss}. {_refreshWhat}"); + } + + private void DoRefresh(TabDef def, string scope) + { + RefreshResult r; + try { r = def.Refresh(); } + catch (Exception ex) { r = new RefreshResult("Couldn't refresh: " + ex.Message); } + _refreshScope = scope; + _refreshWhat = r.What; + _refreshDone = r.Done; + _refreshDoneSeen = false; + _refreshAtMs = _c.NowMs; + _refreshAtUtc = _c.UtcNow; + } + + // ── What each page's Refresh does ─────────────────────────────────────── + + /// The same request twice within is refused. + private bool CoolingDown(string key) + { + if (_refreshSent.TryGetValue(key, out long t) && _c.NowMs - t < CooldownMs) return true; + _refreshSent[key] = _c.NowMs; + return false; + } + + private const string TooSoon = "That was just asked for; wait a few seconds before asking again."; + + /// Sends one chat command (the page's own) and waits for to change. + private RefreshResult Ask(string key, Func state, Func command) + { + if (CoolingDown(key)) return new RefreshResult(TooSoon); + long before = state(); + string cmd = command(); + if (!_c.Send(cmd)) return new RefreshResult($"Couldn't send {cmd} (not in the world)."); + return new RefreshResult($"Sent {cmd}.", () => state() != before); + } + + /// /myquests (refused for 5 s after the last one); the line waits for the new flags. + private RefreshResult RefreshQuests(string before = "") + { + QuestFlagStore f = _c.Flags; + int rev = f.Revision; + if (_c.RequestQuests()) return new RefreshResult(before + "Asked the server for your quest flags (/myquests).", () => f.Revision != rev); + if (f.Loading) return new RefreshResult(before + "Your quest flags are already being read.", () => f.Revision != rev); + return new RefreshResult(before + "Your quest flags were asked for a moment ago; wait a few seconds before asking again."); + } + + private RefreshResult RefreshCharacter() + { + _c.RereadCharacter(); + return new RefreshResult("Re-read your level, experience, buffs and skills from the game."); + } + + /// Pages built from the character's properties and the quest flags: both are read again. + private RefreshResult RefreshCharacterAndQuests() + { + _c.RereadCharacter(); + return RefreshQuests("Re-read your character from the game. "); + } + + private RefreshResult RefreshTitles() + { + _c.RereadTitles(); + return new RefreshResult(_c.TitlesKnown + ? $"Re-read your titles from the game: {_c.EarnedTitles.Count} held." + : "The game hasn't sent this character's titles yet (they arrive at login)."); + } + + private RefreshResult RefreshVoid() + { + _c.RereadCharacter(); + return new RefreshResult("Re-read your buffs and dropped the spell timers that ran out. Timers on targets are learned from your casts."); + } + + private RefreshResult RefreshFellowship() + { + _c.Fellowship.Invalidate(); + return new RefreshResult("Re-read the fellowship from the game."); + } + + private RefreshResult RefreshAbout() + { + if (CoolingDown("about")) return new RefreshResult(TooSoon); + _c.ReloadQuestList(); + QuestCatalog cat = _c.Catalog; + string pack = cat.PackServer.Length > 0 ? $" + {cat.ServerCount} {cat.PackServer}" : ""; + return new RefreshResult($"Reloaded the quest list ({cat.RetailCount} retail{pack}) and asked RynthCore which server this is."); + } + + private RefreshResult RefreshBoards() + { + if (_c.Server.Is(ServerTags.Conquest)) + { + ConquestData cq = _c.Conquest; + ConquestBoard b = cq.Boards[Math.Clamp(_conquestBoard, 0, cq.Boards.Count - 1)]; + return Ask("board" + b.Key, () => b.UpdatedUtc.Ticks, () => cq.RequestBoard(b, _c.NowMs)); + } + AelrynthBoards a = _c.Boards; + return _aelrynthView switch + { + 1 => Ask("top me", () => a.Revision, () => a.RequestTop("me", _c.NowMs)), + 2 => Ask("trial", () => a.Revision, () => a.RequestTrial("", _c.NowMs)), + _ => Ask("top " + _aelrynthBoardArg, () => a.Revision, + () => a.RequestTop(a.BoardTitle.Length > 0 ? _aelrynthBoardArg : "", _c.NowMs)), + }; + } + + private string BoardsHelp() + { + if (_c.Server.Is(ServerTags.Conquest)) + { + ConquestBoard b = _c.Conquest.Boards[Math.Clamp(_conquestBoard, 0, _c.Conquest.Boards.Count - 1)]; + return $"Sends {b.Command} and reads the reply."; + } + return _aelrynthView switch + { + 1 => "Sends /top me and reads the reply.", + 2 => "Sends /trial and reads the dungeon list.", + _ => "Sends /top (every board's leader), or asks again for the board that is open.", + }; + } + + private RefreshResult RefreshConquest() + { + ConquestData cq = _c.Conquest; + switch (_conquestView) + { + case 0: return Ask("bank", () => cq.BankUtc.Ticks, () => cq.RequestBank(_c.NowMs)); + case 1: return Ask("augs", () => cq.AugsUtc.Ticks, () => cq.RequestAugs(_c.NowMs)); + case 2: return Ask("enl", () => cq.EnlUtc.Ticks, () => cq.RequestEnl(_c.NowMs)); + case 3: + _c.RereadCharacter(); + return Ask("bonus", () => cq.BonusUtc.Ticks, () => cq.RequestBonus(_c.NowMs)); + case 4: return Ask("fship", () => cq.FshipUtc.Ticks, () => cq.RequestFships(_c.NowMs)); + default: return RefreshQuests(); + } + } + + private string ConquestHelp() => _conquestView switch + { + 0 => "Sends /b and reads your balances.", + 1 => "Sends /augs and reads your advanced augmentations.", + 2 => "Sends /enl augs and reads your enlightenment augmentations.", + 3 => "Re-reads your level, and sends /bonus for the experience bonuses.", + 4 => "Sends /fship list and reads the fellowships looking for members.", + _ => "Sends /myquests: the custom quests' status comes from your quest flags.", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/SkillsEmbed.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/SkillsEmbed.cs new file mode 100644 index 0000000..8ca39db --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/SkillsEmbed.cs @@ -0,0 +1,90 @@ +using System; + +namespace RynthCore.Plugin.RynthOracle.Views; + +/// +/// The Skills, Attributes and Progress tabs have no page of their own: RynthCore draws its Skills +/// panel body (raise and train, attributes and vitals, the ILT planners) into the Oracle window, +/// below the tab strip. This class is the plugin's half of that hand-off. It tells the engine +/// which body to draw with "/rc oracle-skills skills|attrs|progress" and to stop with +/// "/rc oracle-skills off". +/// +/// It is a small state machine over what the engine was last told, so a command goes out only +/// when the wanted mode changes: never once per frame or per recorded pass. The first command, +/// once a character is in the world, is sent whatever the mode (usually "off"): the engine takes +/// any "/rc oracle-skills" as Oracle announcing that it has these tabs, and only then points the +/// bar's Skills icon and "/rc skills" at them instead of its standalone Skills panel. +/// +internal sealed class SkillsEmbed +{ + /// The engine's word for "no embedded Skills body". + public const string Off = "off"; + + /// A failed send is tried again no sooner than this. + public const long RetryMs = 1000; + + private readonly Func _send; + private string? _sent; // null until the first command has gone out (the engine knows nothing of us yet) + private long _retryAtMs; + + /// Runs a chat command through the engine; false when it didn't go out. + public SkillsEmbed(Func send) => _send = send; + + /// What the engine was last told (and accepted): "skills", "attrs", "progress" or "off"; "off" before any command. + public string Sent => _sent ?? Off; + + /// True once the engine has been sent a command (it then knows Oracle has these tabs). + public bool Announced => _sent != null; + + /// The engine mode for an Oracle tab, or null when the tab isn't one of the three. + public static string? ModeFor(string tab) => tab switch + { + OracleView.TabSkills => "skills", + OracleView.TabAttributes => "attrs", + OracleView.TabProgress => "progress", + _ => null, + }; + + /// True for the tabs whose page is drawn by the engine. + public static bool IsEmbedTab(string tab) => ModeFor(tab) != null; + + /// + /// The mode the engine should be in: the selected tab's while the Oracle window is showing and + /// a character is in the world, otherwise off. + /// + public static string Wanted(string tab, bool windowVisible, bool inWorld) => + windowVisible && inWorld ? ModeFor(tab) ?? Off : Off; + + /// + /// Sends the command for the wanted mode if it differs from the last one sent (the first + /// command waits for the world). Returns true when a command went out. A refused send leaves + /// the state as it was and is retried after . + /// + public bool Update(string tab, bool windowVisible, bool inWorld, long nowMs) + { + if (_sent == null && !inWorld) return false; + string want = Wanted(tab, windowVisible, inWorld); + if (want == _sent || nowMs < _retryAtMs) return false; + if (!_send("/rc oracle-skills " + want)) + { + _retryAtMs = nowMs + RetryMs; + return false; + } + _sent = want; + return true; + } + + /// + /// Unload: leave the engine with no embedded body, whatever was shown. One attempt; nothing is + /// kept to retry. Returns true when a command went out. + /// + public bool Shutdown() + { + if (_sent == null || _sent == Off) return false; + bool ok; + try { ok = _send("/rc oracle-skills " + Off); } + catch { ok = false; } + if (ok) _sent = Off; + return ok; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs index c1f6c28..883b990 100644 --- a/Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs @@ -66,6 +66,21 @@ public static unsafe class PluginExports try { if (utf8 != IntPtr.Zero) Runtime.Plugin?.EnqueueCommand(Marshal.PtrToStringUTF8(utf8)); } catch { } } + // Commands from other plugins (host SendPluginCommand): action "rsort", value an /rsort + // command without the "/rsort" ("now", "status"); RynthAi sends ub-IT's /ub packsort this way. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi) + { + try + { + string action = actionAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(actionAnsi) ?? "" : ""; + string value = valueAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(valueAnsi) ?? "" : ""; + string? arg = RynthSortPlugin.RemoteSortArgument(action, value); + if (arg != null) Runtime.Plugin?.EnqueueCommand(arg); + } + catch { } + } + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId); } diff --git a/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs b/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs index 1e55cc6..1e694ef 100644 --- a/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs @@ -60,6 +60,13 @@ public sealed class RynthSortPlugin : RynthPluginBase /// For the engine's dashboard toggle (RynthSortAutoState): -1 not logged in yet, 0 auto-sort off, 1 on. Any thread. public int AutoState => _autoState; + /// + /// A command from another plugin (RynthPluginApplyRemoteCommand): the /rsort argument when + /// is "rsort" (value "now", "status"...), else null (not ours). + /// + internal static string? RemoteSortArgument(string? action, string? value) + => string.Equals(action, "rsort", StringComparison.OrdinalIgnoreCase) ? value ?? string.Empty : null; + /// An /rsort command from the engine (RynthSortCommand), without "/rsort". Any thread; runs on the tick. public void EnqueueCommand(string? arg) { @@ -77,9 +84,12 @@ public sealed class RynthSortPlugin : RynthPluginBase Warnings = () => _warnings, Character = () => _identityKnown ? _character : string.Empty, }; + // No bar button of its own: opened from the engine Inventory window's Sort button, the + // Scripts menu or /rsort. _window = _ui.Add(new UiWindow("RynthSort/Main", "RynthSort") { DefaultWidth = 360f, DefaultHeight = 420f, MinWidth = 300f, MinHeight = 200f, + BarButton = false, }); Host.Log($"[RynthSort] {Version} initialized. /rsort shows or hides the window; /rsort on|off|now|tidy|clean|unpack. Files: {_store.Root}"); return 0; diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index 83267e3..28e9a26 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -197,7 +197,8 @@ internal static class ActionPacer _gapEnd = 0; _gapLen = 0; _errorAnswers.Clear(); - _staleDrops = _latchExpiries = _burstHolds = 0; + _staleDrops = _latchExpiries = _burstHolds = _emergencyThroughLatch = 0; + _healWaitAt = 0; } } @@ -381,8 +382,10 @@ internal static class ActionPacer bool animationGate = true, bool settleGate = true, bool attackRepeat = false) { if (!Enabled) { why = ""; return true; } - if (ServerBusyHolds(host, who, attackRepeat, out why, healStart: heal != HealNeed.None)) return false; - if (settleGate && MoveAudit.SettleHolds(host, out why)) + if (ServerBusyHolds(host, who, attackRepeat, out why, heal)) return false; + // An emergency heal does not wait for the movement settle (150-600 ms): at Emergency Heal At + // the heal comes first; it still obeys the in-flight rules below (OutstandingAllows, GestureHolds). + if (settleGate && heal != HealNeed.Emergency && MoveAudit.SettleHolds(host, out why)) { bool log; lock (Gate) { _settleHolds++; log = _settleLogged.Add(who); } @@ -662,7 +665,11 @@ internal static class ActionPacer private static long _lastFrameMs; // the last NoteFrame (gap detection; 0 = never) private static long _gapEnd, _gapLen; // the frame that ended the last gap, and its length (0 = none) private static readonly Queue _errorAnswers = new(); // times of error UseDones (burst limiter) - private static long _staleDrops, _latchExpiries, _burstHolds; + private static long _staleDrops, _latchExpiries, _burstHolds, _emergencyThroughLatch; + private static long _healWaitAt; // when a plain heal was last held by the 'too busy' latch (0 = none) + /// A heal held by the latch this recently keeps the latch's probe slot from starts that are no heal. + public const long HealWaitFreshMs = 500; + public static long EmergencyThroughLatch => _emergencyThroughLatch; public static long StaleDrops => _staleDrops; public static long LatchExpiries => _latchExpiries; public static long BurstHolds => _burstHolds; @@ -711,6 +718,16 @@ internal static class ActionPacer } } + /// + /// The macro was switched on. The host gives no time for a UseDone, only its count, so a UseDone that + /// came while nothing was checking (the macro off) cannot be told from a new one; the next check takes + /// the current count as its baseline instead, so a stale 0x1D read at the start latches nothing. + /// + public static void NoteMacroStart() + { + lock (Gate) _lastSeenSeq = int.MinValue; + } + /// Reads the last UseDone: a 0x1D starts or feeds the latch, any other answer clears it. private static void ObserveUseDone(RynthCoreHost host, long now, out string? line) { @@ -745,9 +762,10 @@ internal static class ActionPacer /// a hung cast) or the character is in the air after a breaker jump. Runs the held-cast turn and /// the stuck-cast breaker. Called by MayStart. ///
- private static bool ServerBusyHolds(RynthCoreHost host, string who, bool attackRepeat, out string why, bool healStart = false) + private static bool ServerBusyHolds(RynthCoreHost host, string who, bool attackRepeat, out string why, HealNeed heal = HealNeed.None) { why = ""; + bool healStart = heal != HealNeed.None; long now = NowMs(); long gapEnd, gapLen; lock (Gate) { gapEnd = _gapEnd; gapLen = _gapLen; } @@ -789,7 +807,12 @@ internal static class ActionPacer // A forced break with no cast of ours open (stage for nothing): once on the ground, it is // over. Left set it would block the latch expiry and the probe for good. else if (_stageFor == null && _stage != BreakStage.None && _jumpAt == 0) { _stage = BreakStage.None; _stageAt = 0; } - if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None + // A plain heal held by the latch (an emergency heal is never held by it): the probe slot is its. + // While one waited a moment ago, a start that is no heal does not take the slot (a door or corpse + // use would send first every time and the heal would see the next slot, up to BusyProbeMaxMs later). + if (heal == HealNeed.Heal && _busySince != 0) _healWaitAt = now; + bool healWaiting = heal != HealNeed.Heal && _healWaitAt != 0 && now - _healWaitAt < HealWaitFreshMs; + if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None && !healWaiting && now - Math.Max(_busySince, _lastProbeAt) >= Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs)) { probe = true; @@ -825,6 +848,16 @@ internal static class ActionPacer lock (Gate) latched = _busySince != 0 || _hung != null; // Our cast still inside CastMaxMs with no 0x1D: OutstandingAllows holds it (heal rules included). if (!latched) return false; + // At Emergency Heal At the heal is not held by the latch, whatever set it (any refused use or + // pickup): a refusal of the heal costs a chat line, a held heal can cost the character. The jump + // wait (AirborneHolds, above) and the in-flight rules (MayStart) still apply. + if (heal == HealNeed.Emergency) + { + bool logEm; + lock (Gate) { _emergencyThroughLatch++; logEm = _busyLogged.Add(who + "/emergency"); } + if (logEm) Log(host, $"[Pace] {who}: the emergency heal goes ahead of the server's 'too busy' answer"); + return false; + } if (probe) { Log(host, $"[Pace] {who}: one try (#{_probes}) after the server's 'too busy' answer; no cast of ours is open"); diff --git a/Plugins/Shared/PetCaptureLines.cs b/Plugins/Shared/PetCaptureLines.cs new file mode 100644 index 0000000..e70109d --- /dev/null +++ b/Plugins/Shared/PetCaptureLines.cs @@ -0,0 +1,29 @@ +// PetCaptureLines.cs - The chat lines that mean an ACECustom siphon-lens capture worked. +// +// One list for both plugins (linked source): RynthAi's Pets tab reads them to time its auto-capture +// (success -> short cooldown), and RynthILT's Vaulted Dungeons keeper counts a capture as a kill for +// its "Kill Client" timer (a hunter who captures instead of killing is not idle). They are the +// MonsterCapture success replies the Pets tab already matched; nothing new is guessed here. +using System; + +namespace RynthCore.Plugin.Shared; + +internal static class PetCaptureLines +{ + /// Substrings of the success replies (matched case-insensitively). + private static readonly string[] Success = + { + "successfully siphoned the essence", + "The echo resonates perfectly", + "The essence is captured", + }; + + /// True when is a capture-success reply. + public static bool IsSuccess(string? text) + { + if (string.IsNullOrEmpty(text)) return false; + foreach (string part in Success) + if (text.IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0) return true; + return false; + } +} diff --git a/Plugins/Shared/RynthAiHubApi.cs b/Plugins/Shared/RynthAiHubApi.cs index 404ddd7..bc5680f 100644 --- a/Plugins/Shared/RynthAiHubApi.cs +++ b/Plugins/Shared/RynthAiHubApi.cs @@ -166,4 +166,19 @@ public unsafe struct RynthAiHubApiV1 /// cap); 0 before login. RynthTracker shows RynthAi's session through this and SessionStats. Any thread. ///
public delegate* unmanaged[Cdecl] SessionStatsMore; + + // ── Appended 2026-10-18 (check with Has before calling) ───────────────── + + /// + /// The byte offset of (for ): right after + /// SessionStatsMore. + /// + public static int VaultedDungeonsEnabledOffset => (int)BaseStructSize + sizeof(nint); + + /// + /// VaultedDungeonsEnabled(): 1 when RynthAi's "Vaulted Dungeons" setting (Settings > Navigation) is + /// on. That setting is the master switch of RynthILT's Vaulted Dungeons keeper and lives only in + /// RynthAi; 0 (off) is also the answer before login and after shutdown. Any thread. + /// + public delegate* unmanaged[Cdecl] VaultedDungeonsEnabled; } diff --git a/Plugins/Shared/RynthIltHubApi.cs b/Plugins/Shared/RynthIltHubApi.cs index 91028cb..5fff5fa 100644 --- a/Plugins/Shared/RynthIltHubApi.cs +++ b/Plugins/Shared/RynthIltHubApi.cs @@ -60,6 +60,8 @@ public static class RynthIltHub public const string FeatureQuests = "quests"; public const string FeaturePetRefill = "pet_refill"; public const string FeatureUniversalMastery = "universal_mastery"; + /// ACECustom siphon lenses (monster capture into a pet essence). + public const string FeatureMonsterCapture = "monster_capture"; public const string FeatureRequireComps = "require_spell_comps"; /// Pet breeding (the Pets tab's Breeding sub-tab is hidden while the server reports it off). public const string FeaturePetBreeding = "pet_breeding"; diff --git a/Shared/RynthCore.LootSdk/Editing/LootEditWire.cs b/Shared/RynthCore.LootSdk/Editing/LootEditWire.cs index ad658ce..4c98cd9 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootEditWire.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootEditWire.cs @@ -138,10 +138,53 @@ public sealed class LootEditItemRequest /// 2026-10-07; an older engine never sends it, so it reads false. ///
public bool IncludeT11 { get; set; } + /// + /// The attribute checklist's choices (added 2026-10-18), one per row the player changed; rows + /// without a choice keep their default (ticked for "items like this", T11 rows with + /// IncludeT11). Null from an older engine: every row at its default, as before. + /// + public List? Choices { get; set; } /// Echoed in the draft so the popup knows the answer is to its latest ask. public int Seq { get; set; } } +/// One checklist row as the player set it (LootEditItemAttribute.Id). +public sealed class LootEditItemChoice +{ + public string Id { get; set; } = string.Empty; + public bool On { get; set; } + /// A LootItemAttributeOp code; -1 = the row's default. + public int Op { get; set; } = -1; + /// The edited value; empty = the item's own. + public string Value { get; set; } = string.Empty; +} + +/// +/// One row of the popup's attribute checklist (added 2026-10-18): something the item has that a +/// rule can require, its value, and how it is required now. +/// +public sealed class LootEditItemAttribute +{ + /// Stable within the item ("L:131", "D:152", "spell:Major Strength", "t11:tier"). + public string Id { get; set; } = string.Empty; + /// Item, Weapon / Armor, Ratings, Spells, Pet essence, T11, Requirements. + public string Group { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; + /// The item's own value, for display ("Gold", "7", "1.12", "Major"). + public string ItemValue { get; set; } = string.Empty; + /// The value the rule uses now (the item's, or the player's edit). + public string Value { get; set; } = string.Empty; + /// The row's comparison now (LootItemAttributeOp). + public int Op { get; set; } + /// The comparisons the row offers, the default first. + public List Ops { get; set; } = new(); + /// The value can be typed (a number); named values and spells can't. + public bool Editable { get; set; } + /// The rule requires this row now. + public bool On { get; set; } + public string Tip { get; set; } = string.Empty; +} + /// The rule an item makes, as the popup shows it, and what happened when it was added. public sealed class LootEditItemDraft { @@ -182,6 +225,13 @@ public sealed class LootEditItemDraft /// public string BuiltInReason { get; set; } = string.Empty; public List Notes { get; set; } = new(); + /// + /// True from a RynthAi with the attribute checklist (added 2026-10-18): the popup shows + /// instead of its single "Include T11 attributes" box. + /// + public bool AttributesSupported { get; set; } + /// The item's checklist rows, grouped in display order (added 2026-10-18). + public List Attributes { get; set; } = new(); /// item_add went through; Message says what was added where. public bool Added { get; set; } public string Message { get; set; } = string.Empty; diff --git a/Shared/RynthCore.LootSdk/Editing/LootItemAttributes.cs b/Shared/RynthCore.LootSdk/Editing/LootItemAttributes.cs new file mode 100644 index 0000000..35188a2 --- /dev/null +++ b/Shared/RynthCore.LootSdk/Editing/LootItemAttributes.cs @@ -0,0 +1,539 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using RynthCore.Loot.T11; +using RynthCore.Loot.VTank; + +namespace RynthCore.Loot.Editing; + +// "Add to loot profile"'s attribute checklist (2026-10-18): every attribute a clicked item +// has that a loot rule can require, grouped for the popup, each with the item's value, the +// comparisons it offers and whether it is ticked by default. LootItemRules.Build turns the +// ticked rows into conditions, in row order. With no choices from the popup (an older engine, +// /ra loot add) the defaults reproduce the rules "items like this" and "Include T11 +// attributes" always made. + +/// How a checklist row is required (LootEditItemAttribute.Op). +public enum LootItemAttributeOp +{ + AtLeast = 0, + Exactly = 1, + AtMost = 2, + Not = 3, + /// A spell by its exact name. + SpellExact = 10, + /// This spell at this tier or a higher one (Major Strength: Major, Epic or Legendary). + SpellOrBetter = 11, + /// This spell at any tier. + SpellAnyTier = 12, +} + +/// One checklist row while a rule is built (the wire form is LootEditItemAttribute). +public sealed class LootItemAttribute +{ + internal enum Shape { Long, Double, TotalRatings, Spell, CantripTier, SpellCount } + + public string Id { get; init; } = string.Empty; + public string Group { get; init; } = string.Empty; + public string Label { get; init; } = string.Empty; + public string Tip { get; init; } = string.Empty; + internal Shape Kind { get; init; } + /// The property key (long or double rows), or the cantrip tier (CantripTier rows). + internal int Key { get; init; } + internal double ItemValue { get; init; } + public string ItemText { get; init; } = string.Empty; + public LootItemAttributeOp[] Ops { get; init; } = Array.Empty(); + /// The item's value can be replaced by a typed number. + public bool Editable { get; init; } + /// Spell rows: the spell's name. + internal string Spell { get; init; } = string.Empty; + + // Where the row stands now (defaults, then the player's choice). + public bool On { get; set; } + public LootItemAttributeOp Op { get; set; } + internal double Value { get; set; } + /// The value as the player typed it (empty: the item's). + internal string Typed { get; set; } = string.Empty; + + public LootEditItemAttribute ToWire() => new() + { + Id = Id, Group = Group, Label = Label, ItemValue = ItemText, Tip = Tip, Editable = Editable, On = On, + Op = (int)Op, Ops = new List(Array.ConvertAll(Ops, o => (int)o)), + Value = Editable ? LootItemAttributes.Number(Value) : ItemText, + }; +} + +public static class LootItemAttributes +{ + public const string GroupItem = "Item", GroupGear = "Weapon / Armor", GroupRatings = "Ratings", GroupSpells = "Spells", + GroupPet = "Pet essence", GroupT11 = "T11", GroupRequirements = "Requirements"; + + /// Cantrip tiers, lowest first: "Major Strength" is tier 2. + public static readonly string[] CantripTiers = { "Minor", "Major", "Epic", "Legendary" }; + private static readonly string[] Roman = { "I", "II", "III", "IV", "V", "VI", "VII", "VIII" }; + + // Pet essence property ids (ACECustom; the Mini Remote's PetStats reads the same). + public const int KeyBond = 9053, KeyCapturedDamageType = 9054, KeyPotencyStored = 9056, KeyBreedingCharges = 9057, + KeyMutations = 9075, KeySummoningMastery = 362, KeyUseLevelRequirement = 364, KeyUseRequiresSkill = 366, + KeyUseRequiresSkillSpec = 368, KeyUseRequiresLevel = 369; + private const int SkillSummoning = 54; + + private enum Cmp { Min, Max, Named } + + private readonly record struct Spec(string Group, int Key, bool IsDouble, string Label, Cmp Cmp, string Tip = ""); + + /// The property rows, in display (and condition) order. Spells, T11 and the rating total are built separately. + private static readonly Spec[] Specs = + { + new(GroupItem, LootItemRules.KeyMaterial, false, "Material", Cmp.Named), + new(GroupItem, LootItemRules.KeyWorkmanship, false, "Workmanship", Cmp.Min), + new(GroupItem, 19, false, "Value", Cmp.Min), + new(GroupItem, 5, false, "Burden", Cmp.Max), + new(GroupItem, 106, false, "Spellcraft", Cmp.Min), + new(GroupItem, 108, false, "Max mana", Cmp.Min), + new(GroupItem, 109, false, "Arcane Lore to use", Cmp.Max, "The Arcane Lore the item's spells need (lower is easier)."), + new(GroupItem, 92, false, "Uses left", Cmp.Min), + new(GroupItem, 91, false, "Max uses", Cmp.Min), + new(GroupItem, 265, false, "Armor set", Cmp.Named, "The set id (the same set's pieces share it)."), + new(GroupItem, 353, false, "Imbue", Cmp.Named), + new(GroupItem, 166, false, "Slayer", Cmp.Named), + new(GroupItem, 45, false, "Damage type", Cmp.Named), + + new(GroupGear, LootItemRules.KeyWieldSkill, false, "Wield skill", Cmp.Named), + new(GroupGear, LootItemRules.KeyWeaponSkill, false, "Weapon skill", Cmp.Named), + new(GroupGear, LootItemRules.KeyDamage, false, "Max damage", Cmp.Min), + new(GroupGear, 22, true, "Damage variance", Cmp.Max, "Lower is steadier damage."), + new(GroupGear, 63, true, "Damage modifier", Cmp.Min, "Missile weapons' damage multiplier."), + new(GroupGear, 62, true, "Attack modifier", Cmp.Min), + new(GroupGear, 29, true, "Melee defense modifier", Cmp.Min), + new(GroupGear, 149, true, "Missile defense modifier", Cmp.Min), + new(GroupGear, 150, true, "Magic defense modifier", Cmp.Min), + new(GroupGear, 144, true, "Mana conversion modifier", Cmp.Min), + new(GroupGear, LootItemRules.KeyElementalDamageMod, true, "Elemental damage vs monsters", Cmp.Min), + new(GroupGear, LootItemRules.KeyEquipSlots, false, "Equip slots", Cmp.Named, "Where it is worn or wielded."), + new(GroupGear, LootItemRules.KeyArmorLevel, false, "Armor level", Cmp.Min), + + // The rating total comes first in this group (built separately); then each rating. + new(GroupRatings, 370, false, "Damage rating", Cmp.Min), + new(GroupRatings, 371, false, "Damage resist rating", Cmp.Min), + new(GroupRatings, 372, false, "Crit rating", Cmp.Min), + new(GroupRatings, 373, false, "Crit resist rating", Cmp.Min), + new(GroupRatings, 374, false, "Crit damage rating", Cmp.Min), + new(GroupRatings, 375, false, "Crit damage resist rating", Cmp.Min), + new(GroupRatings, 376, false, "Heal boost rating", Cmp.Min), + new(GroupRatings, 377, false, "Nether resist rating", Cmp.Min), + new(GroupRatings, 379, false, "Vitality rating", Cmp.Min), + + new(GroupPet, KeyBond, false, "Bond level", Cmp.Min), + new(GroupPet, KeyUseRequiresLevel, false, "Level", Cmp.Min), + new(GroupPet, KeyUseLevelRequirement, false, "Level requirement", Cmp.Min), + new(GroupPet, KeyPotencyStored, false, "Potency stored", Cmp.Min), + new(GroupPet, KeySummoningMastery, false, "Summoning mastery", Cmp.Named), + new(GroupPet, KeyMutations, false, "Mutations", Cmp.Min), + new(GroupPet, 9070, false, "Damage mutations", Cmp.Min), + new(GroupPet, 9071, false, "Damage resist mutations", Cmp.Min), + new(GroupPet, 9072, false, "Crit mutations", Cmp.Min), + new(GroupPet, 9073, false, "Vitality mutations", Cmp.Min), + new(GroupPet, 9074, false, "Potency mutations", Cmp.Min), + new(GroupPet, KeyCapturedDamageType, false, "Captured damage type", Cmp.Named), + new(GroupPet, 307, false, "Pet damage rating", Cmp.Min), + new(GroupPet, 308, false, "Pet damage resist rating", Cmp.Min), + new(GroupPet, 313, false, "Pet crit rating", Cmp.Min), + new(GroupPet, 314, false, "Pet crit damage rating", Cmp.Min), + new(GroupPet, 315, false, "Pet crit resist rating", Cmp.Min), + new(GroupPet, 316, false, "Pet crit damage resist rating", Cmp.Min), + new(GroupPet, KeyBreedingCharges, false, "Breeding charges", Cmp.Min), + + new(GroupRequirements, 158, false, "Wield requirement", Cmp.Named), + new(GroupRequirements, 160, false, "Wield difficulty", Cmp.Max, "Lower is easier to wield."), + }; + + /// Every int property a checklist can use: what RynthAi reads into LootItemFacts. + public static readonly int[] IntKeys = BuildKeys(isDouble: false); + /// Every float property a checklist can use. + public static readonly int[] DoubleKeys = BuildKeys(isDouble: true); + + private static int[] BuildKeys(bool isDouble) + { + var keys = new List(); + foreach (Spec s in Specs) + if (s.IsDouble == isDouble && !keys.Contains(s.Key)) keys.Add(s.Key); + if (!isDouble) + foreach (int k in new[] { KeyUseRequiresSkill, KeyUseRequiresSkillSpec }) + if (!keys.Contains(k)) keys.Add(k); + return keys.ToArray(); + } + + /// + /// A combat / summoning essence: the plugin says so, or the item carries ACECustom's bond or + /// potency, or using it needs Summoning. + /// + public static bool IsPetEssence(LootItemFacts f) + => f.IsPetEssence || f.Int(KeyBond) > 0 || f.Ints.ContainsKey(KeyPotencyStored) + || f.Int(KeyUseRequiresSkill) == SkillSummoning || f.Int(KeyUseRequiresSkillSpec) == SkillSummoning + || f.ObjectClass == (int)AcObjectClass.CombatPet; + + /// + /// The item's rows with their defaults: ticked for "items like this" () + /// what that match always required, the T11 rows when . + /// + public static List For(LootItemFacts f, bool like, bool includeT11) + { + var rows = new List(); + bool pet = IsPetEssence(f); + HashSet likeKeys = like ? LikeKeys(f, pet) : new HashSet(); + + foreach (Spec s in Specs) + { + if (s.Group == GroupPet && !pet) continue; + if (s.Group == GroupRatings && s.Key == 370) AddTotalRatings(rows, f, like); + double v = s.IsDouble ? f.Double(s.Key) : f.Int(s.Key); + if (s.Cmp == Cmp.Named ? v == 0 : v <= 0) continue; + // A pet's level comes from 369 when it has one (PetStats does the same). + if (s.Key == KeyUseLevelRequirement && f.Int(KeyUseRequiresLevel) > 0) continue; + rows.Add(PropertyRow(s, v, likeKeys.Contains(s.IsDouble ? -s.Key : s.Key))); + } + // Spells and T11 go after the ratings and before Requirements. + int req = rows.FindIndex(r => r.Group == GroupRequirements); + var tail = req >= 0 ? rows.GetRange(req, rows.Count - req) : new List(); + if (req >= 0) rows.RemoveRange(req, rows.Count - req); + AddSpellRows(rows, f, like); + AddT11Rows(rows, f, includeT11); + rows.AddRange(tail); + return rows; + } + + /// + /// The keys "items like this" required before the checklist (doubles negated), plus a + /// pet essence's bond, level, potency, mastery and mutations. + /// + private static HashSet LikeKeys(LootItemFacts f, bool pet) + { + var k = new HashSet { LootItemRules.KeyMaterial, LootItemRules.KeyWorkmanship }; + int wieldSkill = f.Int(LootItemRules.KeyWieldSkill); + switch ((AcObjectClass)f.ObjectClass) + { + case AcObjectClass.MeleeWeapon: + k.Add(wieldSkill != 0 ? LootItemRules.KeyWieldSkill : LootItemRules.KeyWeaponSkill); + k.Add(LootItemRules.KeyDamage); + break; + case AcObjectClass.MissileWeapon: + k.Add(wieldSkill != 0 ? LootItemRules.KeyWieldSkill : LootItemRules.KeyWeaponSkill); + break; + case AcObjectClass.WandStaffOrb: + k.Add(LootItemRules.KeyWieldSkill); + k.Add(-LootItemRules.KeyElementalDamageMod); + break; + case AcObjectClass.Armor: + case AcObjectClass.Clothing: + k.Add(LootItemRules.KeyEquipSlots); + k.Add(LootItemRules.KeyArmorLevel); + break; + case AcObjectClass.Jewelry: + k.Add(LootItemRules.KeyEquipSlots); + break; + } + if (pet) + foreach (int key in new[] { KeyBond, KeyUseRequiresLevel, KeyUseLevelRequirement, KeyPotencyStored, KeySummoningMastery, KeyMutations }) + k.Add(key); + return k; + } + + private static LootItemAttribute PropertyRow(Spec s, double v, bool on) + { + LootItemAttributeOp[] ops = s.Cmp switch + { + Cmp.Named => new[] { LootItemAttributeOp.Exactly, LootItemAttributeOp.Not }, + Cmp.Max => new[] { LootItemAttributeOp.AtMost, LootItemAttributeOp.Exactly, LootItemAttributeOp.AtLeast }, + _ => new[] { LootItemAttributeOp.AtLeast, LootItemAttributeOp.Exactly, LootItemAttributeOp.AtMost }, + }; + string text = s.IsDouble ? Number(v) : NamedOrNumber(s.Key, (int)v); + return new LootItemAttribute + { + Id = (s.IsDouble ? "D:" : "L:") + s.Key.ToString(CultureInfo.InvariantCulture), + Group = s.Group, Label = s.Label, Tip = s.Tip, + Kind = s.IsDouble ? LootItemAttribute.Shape.Double : LootItemAttribute.Shape.Long, + Key = s.Key, ItemValue = v, ItemText = text, Ops = ops, Editable = s.Cmp != Cmp.Named, + On = on, Op = ops[0], Value = v, + }; + } + + private static void AddTotalRatings(List rows, LootItemFacts f, bool like) + { + int total = 0; + foreach (int k in LootItemRules.RatingKeys) total += Math.Max(0, f.Int(k)); + if (total <= 0 || rows.Exists(r => r.Kind == LootItemAttribute.Shape.TotalRatings)) return; + rows.Add(new LootItemAttribute + { + Id = "ratings", Group = GroupRatings, Label = "Total ratings", Kind = LootItemAttribute.Shape.TotalRatings, + Tip = "Damage, damage resist, crit, crit resist, crit damage, crit damage resist, heal boost and vitality ratings added up.", + ItemValue = total, ItemText = Number(total), Ops = new[] { LootItemAttributeOp.AtLeast }, Editable = true, + On = like, Op = LootItemAttributeOp.AtLeast, Value = total, + }); + } + + // ── Spells ────────────────────────────────────────────────────────────── + + /// "Major Strength": tier 1 (CantripTiers index) and "Strength". + public static bool TryCantrip(string spell, out int tier, out string rest) + { + for (int i = 0; i < CantripTiers.Length; i++) + { + string p = CantripTiers[i] + " "; + if (spell.StartsWith(p, StringComparison.OrdinalIgnoreCase) && spell.Length > p.Length) + { + tier = i; + rest = spell.Substring(p.Length); + return true; + } + } + tier = -1; + rest = string.Empty; + return false; + } + + /// "Strength Self VI": level 6 and "Strength Self". + public static bool TryLevel(string spell, out int level, out string rest) + { + int sp = spell.LastIndexOf(' '); + if (sp > 0) + { + int idx = Array.IndexOf(Roman, spell.Substring(sp + 1).ToUpperInvariant()); + if (idx >= 0) + { + level = idx + 1; + rest = spell.Substring(0, sp); + return true; + } + } + level = 0; + rest = string.Empty; + return false; + } + + /// The spell condition's pattern for a spell row's comparison. + public static string SpellPattern(string spell, LootItemAttributeOp op) + { + if (op == LootItemAttributeOp.SpellOrBetter || op == LootItemAttributeOp.SpellAnyTier) + { + int from; + if (TryCantrip(spell, out int tier, out string rest)) + { + from = op == LootItemAttributeOp.SpellAnyTier ? 0 : tier; + return "^(" + string.Join("|", CantripTiers, from, CantripTiers.Length - from) + ") " + LootItemRules.EscapeText(rest) + "$"; + } + if (TryLevel(spell, out int level, out rest)) + { + from = op == LootItemAttributeOp.SpellAnyTier ? 0 : level - 1; + return "^" + LootItemRules.EscapeText(rest) + " (" + string.Join("|", Roman, from, Roman.Length - from) + ")$"; + } + } + return LootItemRules.ExactPattern(spell); + } + + /// + /// A row per spell (cantrips default to "or better", leveled spells to the exact spell, as + /// "items like this" always did; the first ticked + /// for it), then "N cantrips of a tier or better" and the spell count. + /// + private static void AddSpellRows(List rows, LootItemFacts f, bool like) + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var tiers = new List(); + int ticked = 0, count = 0; + foreach (string raw in f.Spells) + { + string s = LootItemRules.OneLine(raw).Trim(); + if (s.Length == 0 || !seen.Add(s)) continue; + count++; + bool cantrip = TryCantrip(s, out int tier, out _); + int level = 0; + bool leveled = !cantrip && TryLevel(s, out level, out _); + if (cantrip) tiers.Add(tier); + LootItemAttributeOp[] ops = cantrip + ? new[] { LootItemAttributeOp.SpellOrBetter, LootItemAttributeOp.SpellExact, LootItemAttributeOp.SpellAnyTier } + : leveled + ? new[] { LootItemAttributeOp.SpellExact, LootItemAttributeOp.SpellOrBetter, LootItemAttributeOp.SpellAnyTier } + : new[] { LootItemAttributeOp.SpellExact }; + bool on = like && ticked < LootItemRules.MaxSpells; + if (on) ticked++; + rows.Add(new LootItemAttribute + { + Id = "spell:" + s, Group = GroupSpells, Label = s, Kind = LootItemAttribute.Shape.Spell, Spell = s, + ItemText = cantrip ? CantripTiers[tier] + " cantrip" : leveled ? "level " + Roman[level - 1] : "spell", + Tip = cantrip ? "Or better: this cantrip at this tier or higher. Any tier: Minor to Legendary." + : leveled ? "Or better: this spell at this level or higher. Any tier: any level." + : "The item has this spell.", + Ops = ops, On = on, Op = ops[0], + }); + } + + // "At least N Epic-or-better cantrips": one row per tier the item has, highest first. + tiers.Sort(); + for (int t = CantripTiers.Length - 1; t >= 0; t--) + { + if (!tiers.Contains(t)) continue; + int n = tiers.FindAll(x => x >= t).Count; + string label = t == CantripTiers.Length - 1 ? CantripTiers[t] + " cantrips" : CantripTiers[t] + "-or-better cantrips"; + rows.Add(new LootItemAttribute + { + Id = "cantrips:" + CantripTiers[t], Group = GroupSpells, Label = label, Kind = LootItemAttribute.Shape.CantripTier, + Key = t, ItemValue = n, ItemText = Number(n), Ops = new[] { LootItemAttributeOp.AtLeast }, Editable = true, + Tip = "How many of the item's cantrips are this tier or higher.", Op = LootItemAttributeOp.AtLeast, Value = n, + }); + } + if (count > 0) + rows.Add(new LootItemAttribute + { + Id = "spellcount", Group = GroupSpells, Label = "Spell count", Kind = LootItemAttribute.Shape.SpellCount, + ItemValue = count, ItemText = Number(count), Ops = new[] { LootItemAttributeOp.AtLeast }, Editable = true, + Op = LootItemAttributeOp.AtLeast, Value = count, + }); + } + + /// How many spell rows there are (the "more than 4 spells" note). + internal static int SpellRowCount(List rows) => rows.FindAll(r => r.Kind == LootItemAttribute.Shape.Spell).Count; + + /// True for the T11 group's rows. + internal static bool IsT11Row(LootItemAttribute r) => r.Group == GroupT11; + + // ── T11 ───────────────────────────────────────────────────────────────── + + /// + /// The T11 rows on RynthAi's virtual T11 keys, in the order "Include T11 attributes" always + /// added them (Is T11, tier, weapon grade, damage %, gear grade, each catalogued modifier, + /// Has Slot Special for a value-less one, Cast on Strike count), then the summary keys, + /// off by default. Left out on purpose: Can Wield (the character), Zone Locked (where it + /// was appraised), property slots and Tainted (bag state, not quality). + /// + private static void AddT11Rows(List rows, LootItemFacts f, bool on) + { + T11ItemInfo? t = f.T11; + if (t == null || !t.IsT11) return; + void Row(string id, string label, int key, int v, bool named, bool def = true, bool equal = false, string tip = "") + { + LootItemAttributeOp[] ops = equal ? new[] { LootItemAttributeOp.Exactly } + : new[] { LootItemAttributeOp.AtLeast, LootItemAttributeOp.Exactly, LootItemAttributeOp.AtMost }; + rows.Add(new LootItemAttribute + { + Id = "t11:" + id, Group = GroupT11, Label = label, Kind = LootItemAttribute.Shape.Long, Key = key, Tip = tip, + ItemValue = v, ItemText = named ? NamedOrNumber(key, v) : equal ? "yes" : Number(v), Ops = ops, + Editable = !named && !equal, On = on && def, Op = ops[0], Value = v, + }); + } + + Row("is", "Is T11", T11Keys.IsT11, 1, named: false, equal: true); + if (!t.HasText) return; + if (t.Tier > 0) Row("tier", t.TierIsExact ? "Tier" : "Tier (estimated)", T11Keys.EstimatedTier, t.Tier, named: false); + if (t.GradeRank > 0) Row("grade", "Weapon grade", T11Keys.WeaponGrade, t.GradeRank, named: true); + if (t.DamagePercent > 0) Row("dmgpct", "Damage %", T11Keys.DamagePercent, t.DamagePercent, named: false); + if (t.GearGradeRank > 0) Row("geargrade", "Gear grade", T11Keys.GearGrade, t.GearGradeRank, named: true); + bool valuelessSpecial = false; + foreach (T11Modifier m in t.Modifiers) + { + if (T11Catalog.ModifierByKey(m.Key) == null) 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) Row("mod:" + m.Key.ToString(CultureInfo.InvariantCulture), "Mod: " + m.Name, T11Keys.ForModifier(m.Key), m.Value, named: false); + else if (m.IsSlotSpecial) valuelessSpecial = true; + } + if (valuelessSpecial) Row("special", "Has slot special", T11Keys.HasSlotSpecial, 1, named: false, equal: true); + if (t.Procs.Count > 0) Row("cos", "Cast on Strike count", T11Keys.CastOnStrikeCount, t.Procs.Count, named: false); + + foreach (var (key, label) in new[] { (T11Keys.ModifierCount, "Modifier count"), (T11Keys.ModifierRatingTotal, "Modifier rating total"), (T11Keys.BestRollPercent, "Best roll %") }) + if (T11Keys.TryGetValue(t, key, null, out int v) && v > 0) + Row("sum:" + key.ToString(CultureInfo.InvariantCulture), label, key, v, named: false, def: false); + } + + /// The catalogued-but-unknown T11 modifiers (the rule can't require them). + internal static List UnknownT11Modifiers(LootItemFacts f) + { + var unknown = new List(); + if (f.T11 is { IsT11: true } t) + foreach (T11Modifier m in t.Modifiers) + if (T11Catalog.ModifierByKey(m.Key) == null) unknown.Add(m.Name); + return unknown; + } + + // ── Choices and conditions ────────────────────────────────────────────── + + /// + /// The player's choices onto the rows (unknown ids are ignored: the item may have changed). + /// A typed value that isn't a number keeps the item's and says so in . + /// + public static void Apply(List rows, IReadOnlyList? choices, List notes) + { + if (choices == null) return; + foreach (LootEditItemChoice c in choices) + { + LootItemAttribute? r = rows.Find(x => x.Id == c.Id); + if (r == null) continue; + r.On = c.On; + if (c.Op >= 0 && Array.IndexOf(r.Ops, (LootItemAttributeOp)c.Op) >= 0) r.Op = (LootItemAttributeOp)c.Op; + string typed = (c.Value ?? string.Empty).Trim(); + if (!r.Editable || typed.Length == 0) continue; + bool whole = r.Kind != LootItemAttribute.Shape.Double; + if (double.TryParse(typed, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) && v >= 0 && (!whole || v == Math.Floor(v))) + { + r.Value = v; + r.Typed = typed; + } + else + notes.Add($"{r.Label}: '{typed}' isn't a{(whole ? " whole" : "")} number of 0 or more; the item's {r.ItemText} is used."); + } + } + + /// The ticked rows' conditions onto , in row order; how many rows added one. + public static int AddConditions(VTankLootRule rule, List rows) + { + int n = 0; + foreach (LootItemAttribute r in rows) + { + if (!r.On) continue; + n++; + string key = r.Key.ToString(CultureInfo.InvariantCulture); + switch (r.Kind) + { + case LootItemAttribute.Shape.Long: + string iv = ((long)r.Value).ToString(CultureInfo.InvariantCulture); + int type = r.Op switch + { + LootItemAttributeOp.Exactly => VTankNodeTypes.LongValKeyE, + LootItemAttributeOp.AtMost => VTankNodeTypes.LongValKeyLE, + LootItemAttributeOp.Not => VTankNodeTypes.LongValKeyNE, + _ => VTankNodeTypes.LongValKeyGE, + }; + rule.Conditions.Add(Cond(type, iv, key)); + break; + case LootItemAttribute.Shape.Double: + string dv = Number(r.Value); + if (r.Op != LootItemAttributeOp.AtMost) rule.Conditions.Add(Cond(VTankNodeTypes.DoubleValKeyGE, dv, key)); + if (r.Op != LootItemAttributeOp.AtLeast) rule.Conditions.Add(Cond(VTankNodeTypes.DoubleValKeyLE, dv, key)); + break; + case LootItemAttribute.Shape.TotalRatings: + rule.Conditions.Add(Cond(VTankNodeTypes.TotalRatingsGE, Number(r.Value))); + break; + case LootItemAttribute.Shape.Spell: + rule.Conditions.Add(Cond(VTankNodeTypes.SpellNameMatch, SpellPattern(r.Spell, r.Op))); + break; + case LootItemAttribute.Shape.CantripTier: + string tiers = string.Join("|", CantripTiers, r.Key, CantripTiers.Length - r.Key); + rule.Conditions.Add(Cond(VTankNodeTypes.SpellMatch, "^(" + tiers + ") ", string.Empty, Number(r.Value))); + break; + case LootItemAttribute.Shape.SpellCount: + rule.Conditions.Add(Cond(VTankNodeTypes.SpellCountGE, Number(r.Value))); + break; + } + } + return n; + } + + private static VTankLootCondition Cond(int type, params string[] lines) => new(type, "0", lines); + + /// A number as rules write it: whole numbers plain, decimals to 4 places. + public static string Number(double v) => v.ToString("0.####", CultureInfo.InvariantCulture); + + /// A long key's value by name when it has one ("Gold", "Light Weapons"), else the number. + private static string NamedOrNumber(int key, int v) + => LootRuleText.ValueName(key, v.ToString(CultureInfo.InvariantCulture)) ?? v.ToString(CultureInfo.InvariantCulture); +} diff --git a/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs b/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs index c12e8bc..60b58c0 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs @@ -32,6 +32,8 @@ public sealed class LootItemFacts /// for an item that isn't T11 gear. /// public T11ItemInfo? T11 { get; set; } + /// The plugin knows it for a summoning essence (by WCID, icon, use requirement; added 2026-10-18). + public bool IsPetEssence { get; set; } public bool Stackable => MaxStackSize > 1 || StackSize > 1; @@ -64,6 +66,11 @@ public sealed class LootItemRuleOptions /// slot special, Cast on Strike), each at least as good as this item's. Works with any match. /// public bool IncludeT11 { get; set; } + /// + /// The popup's attribute checklist choices (LootItemAttributes); null: every row at its + /// default, which is the rule "items like this" and IncludeT11 always made. + /// + public IReadOnlyList? Choices { get; set; } } /// A built rule, ready to preview and insert. @@ -76,6 +83,8 @@ public sealed class LootItemRuleDraft public string DefaultName { get; init; } = string.Empty; /// Things the player should know (a broad rule, spells left out...). public List Notes { get; init; } = new(); + /// The item's checklist rows as the rule used them (the popup shows them). + public List Attributes { get; init; } = new(); } public static class LootItemRules @@ -86,10 +95,9 @@ public static class LootItemRules public const int KeyElementalDamageMod = 152; /// The ratings TotalRatingsGE adds up (same list as both evaluators). public static readonly int[] RatingKeys = { 370, 371, 372, 373, 374, 375, 376, 379 }; - /// The int properties a "like this" rule can use: what RynthAi reads into LootItemFacts. - public static readonly int[] IntKeys = - { KeyArmorLevel, KeyEquipSlots, KeyDamage, KeyWeaponSkill, KeyWorkmanship, KeyMaterial, KeyWieldSkill, 370, 371, 372, 373, 374, 375, 376, 379 }; - public static readonly int[] DoubleKeys = { KeyElementalDamageMod }; + /// The int properties a rule from an item can use: what RynthAi reads into LootItemFacts. + public static int[] IntKeys => LootItemAttributes.IntKeys; + public static int[] DoubleKeys => LootItemAttributes.DoubleKeys; /// Spell conditions a "like this" rule takes at most (all must match: more makes it narrower). public const int MaxSpells = 4; @@ -109,16 +117,17 @@ public static class LootItemRules /// A name as an exact, case-insensitive regex: ^name$ with the regex /// metacharacters escaped (spaces left alone, unlike Regex.Escape, so it reads well). /// - public static string ExactPattern(string name) + public static string ExactPattern(string name) => "^" + EscapeText(name) + "$"; + + /// Text with the regex metacharacters escaped (spaces left alone), for a pattern's middle. + public static string EscapeText(string text) { - var sb = new StringBuilder(name.Length + 8); - sb.Append('^'); - foreach (char ch in name) + var sb = new StringBuilder(text.Length + 8); + foreach (char ch in text) { if ("\\*+?|{}[]()^$.#".IndexOf(ch) >= 0) sb.Append('\\'); sb.Append(ch); } - sb.Append('$'); return sb.ToString(); } @@ -189,139 +198,60 @@ public static class LootItemRules return null; } rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass))); - likeBare = AddLikeConditions(rule, f, notes) == 0; + likeBare = true; break; } - int t11Added = o.IncludeT11 ? AddT11Conditions(rule, f, notes) : 0; - if (likeBare && t11Added == 0) + // The attribute checklist: defaults for this match, then the popup's choices. + List rows = LootItemAttributes.For(f, match == LootItemMatch.Like, o.IncludeT11); + LootItemAttributes.Apply(rows, o.Choices, notes); + int added = LootItemAttributes.AddConditions(rule, rows); + AddRowNotes(f, o, rows, match, notes); + if (likeBare && added == 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; - return new LootItemRuleDraft { Rule = rule, Match = match, Action = action, KeepCount = keep, DefaultName = defaultName, Notes = notes }; - } - - /// The "like this" conditions for the item's kind; how many it added. - private static int AddLikeConditions(VTankLootRule rule, LootItemFacts f, List notes) - { - int n = rule.Conditions.Count; - var cls = (AcObjectClass)f.ObjectClass; - void LongE(int key) { int v = f.Int(key); if (v != 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyE, Num(v), Num(key))); } - void LongGE(int key) { int v = f.Int(key); if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyGE, Num(v), Num(key))); } - void DoubleGE(int key) + return new LootItemRuleDraft { - double v = f.Double(key); - if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.DoubleValKeyGE, v.ToString("0.####", CultureInfo.InvariantCulture), Num(key))); - } - - LongE(KeyMaterial); - LongGE(KeyWorkmanship); - switch (cls) - { - case AcObjectClass.MeleeWeapon: - if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); else LongE(KeyWeaponSkill); - LongGE(KeyDamage); - break; - case AcObjectClass.MissileWeapon: - if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); else LongE(KeyWeaponSkill); - break; - case AcObjectClass.WandStaffOrb: - if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); - DoubleGE(KeyElementalDamageMod); - break; - case AcObjectClass.Armor: - case AcObjectClass.Clothing: - LongE(KeyEquipSlots); - LongGE(KeyArmorLevel); - break; - case AcObjectClass.Jewelry: - LongE(KeyEquipSlots); - break; - } - - int ratings = 0; - foreach (int k in RatingKeys) ratings += Math.Max(0, f.Int(k)); - if (ratings > 0) rule.Conditions.Add(Cond(VTankNodeTypes.TotalRatingsGE, Num(ratings))); - - int spells = 0; - foreach (string s in f.Spells) - { - string sn = OneLine(s).Trim(); - if (sn.Length == 0) continue; - if (spells == MaxSpells) - { - notes.Add($"The item has more than {MaxSpells} spells; the rule checks the first {MaxSpells}."); - break; - } - rule.Conditions.Add(Cond(VTankNodeTypes.SpellNameMatch, ExactPattern(sn))); - spells++; - } - return rule.Conditions.Count - n; + Rule = rule, Match = match, Action = action, KeepCount = keep, DefaultName = defaultName, Notes = notes, Attributes = rows, + }; } /// - /// The T11 conditions, on RynthAi's virtual T11 keys: Is T11, then tier (the server's - /// stamped tier when sent), weapon grade, damage %, gear grade, 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), the modifier count / rating total / roll % (they - /// follow from the per-modifier values), and the property slots and Tainted (bag state, - /// not quality). How many it added. + /// What the player should know about the rows: spells "like this" left unticked, a T11 item + /// not identified yet, T11 modifiers RynthAi has no key for, T11 asked of a non-T11 item. /// - private static int AddT11Conditions(VTankLootRule rule, LootItemFacts f, List notes) + private static void AddRowNotes(LootItemFacts f, LootItemRuleOptions o, List rows, LootItemMatch match, List notes) { + if (match == LootItemMatch.Like && o.Choices == null && LootItemAttributes.SpellRowCount(rows) > MaxSpells) + notes.Add($"The item has more than {MaxSpells} spells; the rule checks the first {MaxSpells} (the Add to loot profile popup can tick the rest)."); + + bool t11Asked = o.IncludeT11 || rows.Exists(r => r.On && LootItemAttributes.IsT11Row(r)); + if (!t11Asked) return; 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; + return; } - - 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; + return; } - - AtLeast(T11Keys.EstimatedTier, t.Tier); - AtLeast(T11Keys.WeaponGrade, t.GradeRank); - AtLeast(T11Keys.DamagePercent, t.DamagePercent); - AtLeast(T11Keys.GearGrade, t.GearGradeRank); - - 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); - + List unknown = LootItemAttributes.UnknownT11Modifiers(f); 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); - private static string OneLine(string? s) => + internal static string OneLine(string? s) => string.IsNullOrEmpty(s) ? string.Empty : s.Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' '); // ===================================================================== diff --git a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs index 9145fce..b55ee99 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs @@ -47,8 +47,24 @@ public static class LootRuleText { (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"), + // 87 / 88 were labelled MaxStructure / Structure until 2026-10-18; uses are 91 / 92 + // (what the Pets tab reads for an essence's uses), and 107 is the current mana. + (86, "MinLevelRestrict"), (87, "MaxLevelRestrict"), (88, "LockpickSkillBonus"), + (91, "UsesTotal (MaxStructure)"), (92, "UsesRemaining (Structure)"), + (105, "ItemWorkmanship"), (106, "ItemSpellcraft"), (107, "ItemCurMana"), (108, "ItemMaxMana"), + (109, "ItemDifficulty (Arcane Lore)"), (131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"), + // ACECustom / ACE appraisal: slayer weapons (166) and combat-essence pet stats (9053-9075). + // "Slayer Type" is the player-facing name; the ACE property is still SlayerCreatureType. + (166, "Slayer Type"), (9053, "Pet Bond Level"), (9054, "Pet Captured Damage Type"), (9056, "Pet Potency Stored"), + (9057, "Pet Breeding Charges"), (9070, "Pet Damage Mutations"), (9071, "Pet Damage Resist Mutations"), + (9072, "Pet Crit Mutations"), (9073, "Pet Vitality Mutations"), (9074, "Pet Potency Mutations"), + (9075, "Pet Mutation Count"), + (307, "Pet DamageRating"), (308, "Pet DamageResistRating"), (313, "Pet CritRating"), + (314, "Pet CritDamageRating"), (315, "Pet CritResistRating"), (316, "Pet CritDamageResistRating"), + (362, "SummoningMastery"), (364, "UseLevelRequirement"), (366, "UseRequiresSkill"), + (368, "UseRequiresSkillSpec"), (369, "UseRequiresLevel"), + (179, "Imbued (Decal)"), (265, "EquipmentSetId (armor set)"), (218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"), (372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"), (375, "CritDamageResistRating"), (376, "HealBoostRating"), (377, "NetherResistRating"), (379, "VitalityRating"), @@ -81,7 +97,8 @@ public static class LootRuleText public static readonly (int Id, string Name)[] DoubleKeys = { (5, "ManaRate"), (22, "DamageVariance"), (29, "WeaponDefense"), (62, "WeaponOffense"), - (63, "DamageMod"), (144, "ManaConversionMod"), (149, "WeaponMissileDefense"), + (63, "DamageMod"), (138, "Slayer Damage Bonus"), // often unset on ACE appraisal; prefer LongDesc / int 166 + (144, "ManaConversionMod"), (149, "WeaponMissileDefense"), (150, "WeaponMagicDefense"), (152, "ElementalDamageVsMonsters"), (167, "CooldownDuration"), (0x0A000009, "SalvageWorkmanship"), (0x0A00000B, "Variance"), (0x0A00000C, "AttackBonus"), (0x0A00000E, "DamageBonus"), @@ -158,27 +175,85 @@ public static class LootRuleText (512, "Mana"), (1024, "Nether"), }; + /// + /// Slayer Type (166 / ACE SlayerCreatureType): ACE CreatureType enum names + /// (same set as RynthAi CreatureTypeNames). Index 0 is Invalid and omitted. + /// Listed A–Z so players can find a type quickly; ids stay ACE order for .utl. + /// Unknown ids still show as "value N". + /// + public static readonly (int Id, string Name)[] CreatureTypes = BuildCreatureTypes(); + + private static (int Id, string Name)[] BuildCreatureTypes() + { + // Keep in sync with Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureTypeNames.cs. + string[] names = + { + "Invalid", "Olthoi", "Banderling", "Drudge", "Mosswart", "Lugian", "Tumerok", "Mite", "Tusker", + "Phyntos Wasp", "Rat", "Auroch", "Cow", "Golem", "Undead", "Gromnie", "Reedshark", "Armoredillo", + "Fae", "Virindi", "Wisp", "Knathtead", "Shadow", "Mattekar", "Mumiyah", "Rabbit", "Sclavus", + "Shallows Shark", "Monouga", "Zefir", "Skeleton", "Human", "Shreth", "Chittick", "Moarsman", + "Olthoi Larvae", "Slithis", "Deru", "Fire Elemental", "Snowman", "Unknown", "Bunny", + "Lightning Elemental", "Rockslide", "Grievver", "Niffis", "Ursuin", "Crystal", "Hollow Minion", + "Scarecrow", "Idol", "Empyrean", "Hopeslayer", "Doll", "Marionette", "Carenzi", "Siraluun", + "Aun Tumerok", "Hea Tumerok", "Simulacrum", "Acid Elemental", "Frost Elemental", "Elemental", + "Statue", "Wall", "Altered Human", "Device", "Harbinger", "Dark Sarcophagus", "Chicken", + "Gotrok Lugian", "Margul", "Bleached Rabbit", "Nasty Rabbit", "Grimacing Rabbit", "Burun", + "Target", "Ghost", "Fiun", "Eater", "Penguin", "Ruschk", "Thrungus", "Viamontian Knight", + "Remoran", "Swarm", "Moar", "Enchanted Arms", "Sleech", "Mukkir", "Merwart", "Food", + "Paradox Olthoi", "Harvest", "Energy", "Apparition", "Aerbax", "Touched", "Blighted Moarsman", + "Gear Knight", "Gurog", "Anekshay", + }; + var list = new List<(int, string)>(names.Length - 1); + for (int i = 1; i < names.Length; i++) + list.Add((i, names[i])); + // Alphabetical for the picker (same idea as Skills); id is what the .utl stores. + list.Sort((a, b) => string.Compare(a.Item2, b.Item2, StringComparison.OrdinalIgnoreCase)); + return list.ToArray(); + } + /// /// The names for a long key's value, or null when the key's value is a plain /// number. Unknown values are still valid: show them as "value N". /// + /// + /// ImbuedEffect (353): ACE's ImbuedEffectType flags. A combination (two imbues) shows as + /// "value N". + /// + public static readonly (int Id, string Name)[] ImbuedEffects = + { + (1, "Critical Strike"), (2, "Crippling Blow"), (4, "Armor Rending"), (8, "Slash Rending"), + (16, "Pierce Rending"), (32, "Bludgeon Rending"), (64, "Acid Rending"), (128, "Cold Rending"), + (256, "Electric Rending"), (512, "Fire Rending"), (1024, "Melee Defense"), (2048, "Missile Defense"), + (4096, "Magic Defense"), (8192, "Spellbook"), (16384, "Nether Rending"), + }; + + /// SummoningMastery (362): the pet school an essence needs (ACE SummoningMastery). + public static readonly (int Id, string Name)[] SummoningMasteries = + { + (1, "Primalist"), (2, "Necromancer"), (3, "Naturalist"), + }; + public static (int Id, string Name)[]? ValueTableFor(int longKey) => longKey switch { - 45 or 0x0D000021 => DamageTypes, + 45 or 0x0D000021 or 9054 => DamageTypes, 48 or 0x0D000020 => Skills, 131 => Materials, 158 => WieldRequirements, - 159 => Skills, + 159 or 366 or 368 => Skills, + 166 => CreatureTypes, + 353 => ImbuedEffects, + 362 => SummoningMasteries, T11.T11Keys.WeaponGrade => T11.T11Catalog.Grades, T11.T11Keys.GearGrade => T11.T11Catalog.Grades, _ => null, }; /// 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 is 45 or 0x0D000021; + public static bool ValueTableIsFlags(int longKey) => longKey is 45 or 0x0D000021 or 9054 or 353; /// The long keys that have a value table, for the vocabulary. - public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159, 0x0D000020, 0x0D000021, T11.T11Keys.WeaponGrade, T11.T11Keys.GearGrade }; + public static readonly int[] KeysWithValueTables = + { 45, 48, 131, 158, 159, 166, 353, 362, 366, 368, 9054, 0x0D000020, 0x0D000021, T11.T11Keys.WeaponGrade, T11.T11Keys.GearGrade }; /// /// True for the conditions whose value is picked by name when the key has a diff --git a/Tools/RynthCore.LootEditor/LongValuePicker.cs b/Tools/RynthCore.LootEditor/LongValuePicker.cs index a358fd7..9a284c2 100644 --- a/Tools/RynthCore.LootEditor/LongValuePicker.cs +++ b/Tools/RynthCore.LootEditor/LongValuePicker.cs @@ -81,10 +81,20 @@ internal sealed class LongValuePicker : ContentControl _box.Width = 80; _box.Margin = new Thickness(4, 0, 0, 0); ToolTip.SetTip(_box, "Any number, named or not"); - _combo = new ComboBox { HorizontalAlignment = HorizontalAlignment.Stretch, MinWidth = 160 }; + _combo = new ComboBox + { + HorizontalAlignment = HorizontalAlignment.Stretch, + MinWidth = 160, + IsTextSearchEnabled = true, // type while open to jump (Olthoi, Virindi, …) + MaxDropDownHeight = 360, + }; _combo.DisplayMemberBinding = new Avalonia.Data.Binding(nameof(Opt.Display)); if (LootRuleText.ValueTableIsFlags(key)) ToolTip.SetTip(_combo, "Flags: other combinations are typed as a number in the box"); + else if (key == 166) + ToolTip.SetTip(_combo, "Slayer creature type — pick by name (list is A–Z). Any slayer: use >= 1"); + else + ToolTip.SetTip(_combo, "Pick by name, or type a number in the box"); _combo.SelectionChanged += (_, _) => { if (_syncing || _combo.SelectedItem is not Opt { Id: int id }) return; diff --git a/Tools/RynthCore.LootSdkTests/LootAddAttributeTests.cs b/Tools/RynthCore.LootSdkTests/LootAddAttributeTests.cs new file mode 100644 index 0000000..d36b6ce --- /dev/null +++ b/Tools/RynthCore.LootSdkTests/LootAddAttributeTests.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using RynthCore.Loot; +using RynthCore.Loot.Editing; +using RynthCore.Loot.VTank; + +namespace RynthCore.LootSdkTests; + +// "Add to loot profile"'s attribute checklist (2026-10-18): every attribute a clicked item has, +// grouped, each ticked or not with a comparison and a value; spells by tier; pet essences. +// The defaults (no choices) are covered by LootAddItemTests / LootAddT11Tests, which still +// expect the rules "items like this" and "Include T11 attributes" always made. +internal static partial class Program +{ + private static void RunLootAddAttributeTests() + { + Console.WriteLine("\n-- LootAdd: attribute checklist --"); + TestAttrRowsAndGroups(); + TestAttrChoices(); + TestAttrSpellTiers(); + TestAttrCantripCounts(); + TestAttrPetEssence(); + TestAttrNativeAndWire(); + TestAttrVocab(); + } + + private static LootItemFacts Sword() => new() + { + Id = 10, Name = "Gold Tachi", ObjectClass = (int)AcObjectClass.MeleeWeapon, + Ints = { [131] = 60, [105] = 8, [159] = 45, [44] = 52, [5] = 300, [370] = 3, [374] = 2, [160] = 400, [158] = 2 }, + Doubles = { [62] = 1.18, [29] = 1.2 }, + Spells = { "Legendary Blood Thirst", "Epic Heart Thirst", "Major Strength", "Blood Drinker Self VI" }, + }; + + private static List Pick(params (string Id, bool On, LootItemAttributeOp Op, string Value)[] p) + => p.Select(x => new LootEditItemChoice { Id = x.Id, On = x.On, Op = (int)x.Op, Value = x.Value }).ToList(); + + private static void TestAttrRowsAndGroups() + { + LootItemRuleDraft d = BuildOk(Sword()); + List rows = d.Attributes; + Check(rows.Count > 0, "attr: rows for an item"); + Check(!rows.Any(r => r.On), "attr: name + class ticks nothing by default"); + string[] groups = rows.Select(r => r.Group).Distinct().ToArray(); + Eq(string.Join(",", groups), "Item,Weapon / Armor,Ratings,Spells,Requirements", "attr: groups in display order"); + LootItemAttribute mat = rows.Single(r => r.Id == "L:131"); + Eq(mat.ItemText, "Gold", "attr: named value shown by name"); + Check(!mat.Editable && mat.Ops[0] == LootItemAttributeOp.Exactly, "attr: material is = (or !=), not typed"); + LootItemAttribute burden = rows.Single(r => r.Id == "L:5"); + Eq(burden.Ops[0], LootItemAttributeOp.AtMost, "attr: burden defaults to at most"); + Check(rows.Any(r => r.Id == "ratings" && r.ItemText == "5"), "attr: total ratings row (3 + 2)"); + Check(rows.Any(r => r.Id == "D:62") && rows.Any(r => r.Id == "D:29"), "attr: weapon modifiers (doubles)"); + Check(!rows.Any(r => r.Group == LootItemAttributes.GroupPet), "attr: no pet rows on a sword"); + + // "Items like this" ticks what it always required, nothing more. + LootItemRuleDraft like = BuildOk(Sword(), new() { Match = LootItemMatch.Like }); + Eq(string.Join(",", like.Attributes.Where(r => r.On).Select(r => r.Id)), + "L:131,L:105,L:159,L:44,ratings,spell:Legendary Blood Thirst,spell:Epic Heart Thirst,spell:Major Strength,spell:Blood Drinker Self VI", + "attr: like ticks material, workmanship, wield skill, damage, ratings, the first 4 spells"); + } + + private static void TestAttrChoices() + { + // Burden at most 250 (typed), attack modifier exactly (two double conditions), material !=, + // and a row the item doesn't have (ignored). + List c = Pick( + ("L:5", true, LootItemAttributeOp.AtMost, "250"), + ("D:62", true, LootItemAttributeOp.Exactly, ""), + ("L:131", true, LootItemAttributeOp.Not, ""), + ("L:9999", true, LootItemAttributeOp.AtLeast, "1")); + LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = c }); + string conds = string.Join(" ; ", d.Rule.Conditions.Select(Lines)); + Eq(conds, "7:1 ; 1:^Gold Tachi$|1 ; 13:60|131 ; 2:250|5 ; 5:1.18|62 ; 4:1.18|62", + "attr: name + class, then the ticked rows in row order with their comparisons"); + Eq(d.Attributes.Single(r => r.Id == "L:5").ToWire().Value, "250", "attr: the typed value goes back to the popup"); + Check(d.Notes.Count == 0, "attr: no notes"); + + // A bad typed value keeps the item's and says so; an op the row doesn't offer is ignored. + LootItemRuleDraft bad = BuildOk(Sword(), new() { Choices = Pick(("L:105", true, LootItemAttributeOp.SpellOrBetter, "lots")) }); + Check(bad.Rule.Conditions.Any(x => Lines(x) == "3:8|105"), "attr: bad value: the item's 8, at least"); + Check(bad.Notes.Any(n => n.StartsWith("Workmanship: 'lots'")), "attr: bad value: a note"); + LootItemRuleDraft frac = BuildOk(Sword(), new() { Choices = Pick(("L:105", true, LootItemAttributeOp.AtLeast, "7.5")) }); + Check(frac.Notes.Any(n => n.Contains("whole number")), "attr: a long row takes whole numbers only"); + + // "Items like this" with a row unticked: the choice wins over the default. + LootItemRuleDraft like = BuildOk(Sword(), new() { Match = LootItemMatch.Like, Choices = Pick(("L:131", false, LootItemAttributeOp.Exactly, "")) }); + Check(!like.Rule.Conditions.Any(x => Lines(x) == "12:60|131"), "attr: like, material unticked"); + Check(like.Rule.Conditions.Any(x => Lines(x) == "3:8|105"), "attr: like, the other defaults stay"); + Check(!like.Notes.Any(n => n.Contains("more than 4 spells")), "attr: no 4-spell note once the player chooses"); + } + + private static void TestAttrSpellTiers() + { + Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellOrBetter), "^(Major|Epic|Legendary) Strength$", "spell: cantrip or better"); + Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellAnyTier), "^(Minor|Major|Epic|Legendary) Strength$", "spell: cantrip any tier"); + Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellExact), "^Major Strength$", "spell: exact"); + Eq(LootItemAttributes.SpellPattern("Blood Drinker Self VI", LootItemAttributeOp.SpellOrBetter), "^Blood Drinker Self (VI|VII|VIII)$", "spell: level or better"); + Eq(LootItemAttributes.SpellPattern("Legendary Blood Thirst", LootItemAttributeOp.SpellOrBetter), "^(Legendary) Blood Thirst$", "spell: Legendary or better is Legendary"); + Eq(LootItemAttributes.SpellPattern("Aura of Defender", LootItemAttributeOp.SpellOrBetter), "^Aura of Defender$", "spell: no tier: exact"); + Eq(LootItemAttributes.SpellPattern("Major Strength (II)", LootItemAttributeOp.SpellOrBetter), "^(Major|Epic|Legendary) Strength \\(II\\)$", "spell: the rest is escaped"); + + string orBetter = LootItemAttributes.SpellPattern("Epic Heart Thirst", LootItemAttributeOp.SpellOrBetter); + Check(Regex.IsMatch("Legendary Heart Thirst", orBetter, RegexOptions.IgnoreCase), "spell: Legendary is better than Epic"); + Check(!Regex.IsMatch("Major Heart Thirst", orBetter, RegexOptions.IgnoreCase), "spell: Major is not"); + Check(!Regex.IsMatch("Epic Heart Thirsty", orBetter, RegexOptions.IgnoreCase), "spell: still the whole name"); + + List rows = BuildOk(Sword()).Attributes; + Eq(rows.Single(r => r.Id == "spell:Major Strength").Ops[0], LootItemAttributeOp.SpellOrBetter, "spell: a cantrip defaults to or better"); + Eq(rows.Single(r => r.Id == "spell:Blood Drinker Self VI").Ops[0], LootItemAttributeOp.SpellExact, "spell: a leveled spell defaults to exact (as before)"); + Eq(rows.Single(r => r.Id == "spell:Major Strength").ItemText, "Major cantrip", "spell: the tier is shown"); + + // Like with every spell ticked: no limit of four once chosen. + var many = new LootItemFacts { Name = "Robe", ObjectClass = (int)AcObjectClass.Clothing, Spells = { "Minor Focus", "Major Willpower", "Epic Strength", "Legendary Endurance", "Major Coordination" } }; + LootItemRuleDraft d = BuildOk(many, new() { Match = LootItemMatch.Like, Choices = Pick(("spell:Major Coordination", true, LootItemAttributeOp.SpellAnyTier, "")) }); + Eq(d.Rule.Conditions.Count(x => x.NodeType == VTankNodeTypes.SpellNameMatch), 5, "spell: a fifth spell can be ticked"); + Check(d.Rule.Conditions.Any(x => Lines(x) == "0:^(Minor|Major|Epic|Legendary) Coordination$"), "spell: any tier pattern in the rule"); + } + + private static void TestAttrCantripCounts() + { + List rows = BuildOk(Sword()).Attributes; + Eq(string.Join(",", rows.Where(r => r.Id.StartsWith("cantrips:")).Select(r => r.Label + "=" + r.ItemText)), + "Legendary cantrips=1,Epic-or-better cantrips=2,Major-or-better cantrips=3", "cantrips: a row per tier the item has, highest first"); + Check(rows.Any(r => r.Id == "spellcount" && r.ItemText == "4"), "cantrips: spell count"); + + LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = Pick(("cantrips:Epic", true, LootItemAttributeOp.AtLeast, "2"), ("spellcount", true, LootItemAttributeOp.AtLeast, "3")) }); + Check(d.Rule.Conditions.Any(x => Lines(x) == "9:^(Epic|Legendary) ||2"), "cantrips: Spell Match, Epic or Legendary, at least 2"); + Check(d.Rule.Conditions.Any(x => Lines(x) == "8:3"), "cantrips: spell count >= 3"); + Check(LootItemRules.PreviewLines(d.Rule).Any(l => l.Contains(">= 2 spells matching")), "cantrips: preview in words"); + } + + private static void TestAttrPetEssence() + { + var wolf = new LootItemFacts + { + Id = 20, Name = "Fire Wolf Essence", ObjectClass = (int)AcObjectClass.Misc, + Ints = { [9053] = 12, [369] = 180, [9056] = 40, [362] = 1, [9075] = 2, [9070] = 1, [9054] = 16, [370] = 5, [92] = 30, [91] = 50 }, + }; + List rows = BuildOk(wolf).Attributes; + Check(rows.Any(r => r.Group == LootItemAttributes.GroupPet), "pet: bond makes it an essence"); + Eq(rows.Single(r => r.Id == "L:362").ItemText, "Primalist", "pet: mastery by name"); + Eq(rows.Single(r => r.Id == "L:9054").ItemText, "Fire", "pet: captured damage type by name"); + Check(rows.Any(r => r.Id == "L:92" && r.Label == "Uses left"), "pet: uses (Item group)"); + + LootItemRuleDraft like = BuildOk(wolf, new() { Match = LootItemMatch.Like }); + string conds = string.Join(" ; ", like.Rule.Conditions.Select(Lines)); + Eq(conds, "7:8 ; 2007:5 ; 3:12|9053 ; 3:180|369 ; 3:40|9056 ; 12:1|362 ; 3:2|9075", + "pet: like = class, ratings, bond, level, potency, mastery, mutations"); + + var flagged = new LootItemFacts { Name = "Odd Essence", ObjectClass = (int)AcObjectClass.Misc, IsPetEssence = true, Ints = { [9073] = 1 } }; + Check(BuildOk(flagged).Attributes.Any(r => r.Id == "L:9073"), "pet: the plugin's IsPetEssence shows the group"); + var notPet = new LootItemFacts { Name = "Jibril's Essence", ObjectClass = (int)AcObjectClass.Misc, Ints = { [9073] = 1 } }; + Check(!BuildOk(notPet).Attributes.Any(r => r.Group == LootItemAttributes.GroupPet), "pet: a name alone isn't an essence"); + } + + private static void TestAttrNativeAndWire() + { + LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = Pick(("L:5", true, LootItemAttributeOp.AtMost, ""), ("spell:Major Strength", true, LootItemAttributeOp.SpellOrBetter, ""), ("cantrips:Legendary", true, LootItemAttributeOp.AtLeast, "")) }); + var dropped = new List(); + LootRule? n = LootItemRules.ToNative(d.Rule, dropped); + Check(n != null && n.Conditions.Any(c => c.ToString().Contains("LongValKey") || c.ToString().Contains("[5]")), "native: burden converts"); + Eq(dropped.Count, 2, "native: the two spell conditions are named as left out"); + + var st = new LootEditState { ItemDraft = new LootEditItemDraft { Seq = 4, AttributesSupported = true } }; + foreach (LootItemAttribute r in d.Attributes) st.ItemDraft.Attributes.Add(r.ToWire()); + string json = System.Text.Json.JsonSerializer.Serialize(st, LootEditJsonContext.Default.LootEditState); + LootEditState? back = System.Text.Json.JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditState); + LootEditItemAttribute? spell = back?.ItemDraft?.Attributes.FirstOrDefault(a => a.Id == "spell:Major Strength"); + Check(back?.ItemDraft?.AttributesSupported == true, "wire: attributes supported round-trips"); + Check(spell != null && spell.On && spell.Op == (int)LootItemAttributeOp.SpellOrBetter && spell.Ops.Count == 3, "wire: a row round-trips"); + + var cmd = new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { Choices = Pick(("L:5", true, LootItemAttributeOp.AtMost, "9")) } }; + string cj = System.Text.Json.JsonSerializer.Serialize(cmd, LootEditJsonContext.Default.LootEditCommand); + LootEditCommand? cb = System.Text.Json.JsonSerializer.Deserialize(cj, LootEditJsonContext.Default.LootEditCommand); + Eq(cb?.Item?.Choices?.Single().Value, "9", "wire: choices round-trip"); + LootEditCommand? old = System.Text.Json.JsonSerializer.Deserialize("{\"Op\":\"item_preview\",\"Item\":{\"Match\":2}}", LootEditJsonContext.Default.LootEditCommand); + Check(old?.Item != null && old.Item.Choices == null, "wire: an older engine's ask has no choices (defaults)"); + } + + private static void TestAttrVocab() + { + Eq(LootRuleText.ValueName(353, "4"), "Armor Rending", "vocab: imbue names"); + Eq(LootRuleText.ValueName(362, "3"), "Naturalist", "vocab: summoning mastery"); + Check(LootRuleText.LongKeys.Any(k => k.Id == 9053) && LootRuleText.LongKeys.Any(k => k.Id == 9075), "vocab: pet keys named"); + Check(LootRuleText.LongKeys.Any(k => k.Id == 92 && k.Name.StartsWith("UsesRemaining")), "vocab: 92 is uses remaining"); + Check(LootRuleText.LongKeys.Any(k => k.Id == 107 && k.Name == "ItemCurMana") && LootRuleText.LongKeys.Any(k => k.Id == 108 && k.Name == "ItemMaxMana"), "vocab: current and max mana"); + var ids = LootRuleText.LongKeys.Select(k => k.Id).ToList(); + Eq(ids.Count, ids.Distinct().Count(), "vocab: no long key named twice"); + } +} diff --git a/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs b/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs index f65f912..30e365a 100644 --- a/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs +++ b/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs @@ -39,12 +39,19 @@ internal static partial class Program { ("skills", LootRuleText.Skills), ("wield requirements", LootRuleText.WieldRequirements), ("materials", LootRuleText.Materials), ("damage types", LootRuleText.DamageTypes), + ("creature types", LootRuleText.CreatureTypes), }) { Eq(table.Select(t => t.Id).Distinct().Count(), table.Length, $"{label}: ids unique"); Check(table.All(t => t.Name.Length > 0 && t.Name.All(ch => ch >= 32 && ch < 128)), $"{label}: names ASCII"); Eq(table.Select(t => t.Name).Distinct().Count(), table.Length, $"{label}: names unique"); } + Check(ReferenceEquals(LootRuleText.ValueTableFor(166), LootRuleText.CreatureTypes), "166 Slayer Type -> creature types"); + Eq(LootRuleText.LongKeys.First(k => k.Id == 166).Name, "Slayer Type", "166 player-facing name"); + Eq(LootRuleText.ValueName(166, "1"), "Olthoi", "ValueName 166/1 Olthoi"); + Check(LootRuleText.CreatureTypes.Select(t => t.Name) + .SequenceEqual(LootRuleText.CreatureTypes.Select(t => t.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase)), + "creature types listed alphabetically"); // Retail / ACE numbering (the old table had Light Weapons at 47, which is Missile Weapons). string Skill(int id) => LootRuleText.Skills.First(s => s.Id == id).Name; diff --git a/Tools/RynthCore.LootSdkTests/Program.cs b/Tools/RynthCore.LootSdkTests/Program.cs index aa41afa..4c464ca 100644 --- a/Tools/RynthCore.LootSdkTests/Program.cs +++ b/Tools/RynthCore.LootSdkTests/Program.cs @@ -46,6 +46,7 @@ internal static partial class Program RunLootAddTests(args); RunT11Tests(); RunLootAddT11Tests(); + RunLootAddAttributeTests(); RunUnknownNodeTests(); Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed."); diff --git a/Tools/RynthCore.MonsterEditor/MainWindow.axaml b/Tools/RynthCore.MonsterEditor/MainWindow.axaml index b029036..e56c021 100644 --- a/Tools/RynthCore.MonsterEditor/MainWindow.axaml +++ b/Tools/RynthCore.MonsterEditor/MainWindow.axaml @@ -255,6 +255,18 @@ + + + + + + + + + + diff --git a/Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs b/Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs index c7b6c49..7b73c80 100644 --- a/Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs +++ b/Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs @@ -29,6 +29,9 @@ public partial class MainWindow : Window { "None", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; public string[] PetOptions { get; } = { "PAuto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + /// RynthAi KiteModes: Default follows the DEFAULT row; PullAway tags then runs clear. + public string[] KiteOptions { get; } = + { "Default", "Off", "PullAway" }; private string _charFolder = string.Empty; private string _monstersPath = string.Empty; diff --git a/Tools/RynthCore.MonsterEditor/Models.cs b/Tools/RynthCore.MonsterEditor/Models.cs index a7fdd0d..02fe9df 100644 --- a/Tools/RynthCore.MonsterEditor/Models.cs +++ b/Tools/RynthCore.MonsterEditor/Models.cs @@ -23,6 +23,7 @@ public class MonsterRule : INotifyPropertyChanged private int _offhandId; private int _preferredAmmoItemId; private string _petDamage = "PAuto"; + private string _kite = "Default"; public string Name { get => _name; set { _name = value; OnPropertyChanged(); } } /// The plugin's rule group label. Kept and editable here (before 2026-10-05 an @@ -58,6 +59,8 @@ public class MonsterRule : INotifyPropertyChanged /// Optional loose ammo stack id for missile combat while this rule matches (0 = auto). public int PreferredAmmoItemId { get => _preferredAmmoItemId; set { _preferredAmmoItemId = value; OnPropertyChanged(); } } public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } } + /// Pull-away kite: Default (follow DEFAULT row), Off, or PullAway. RynthAi KiteModes. + public string Kite { get => _kite; set { _kite = value ?? "Default"; OnPropertyChanged(); } } /// Every field in the file this class doesn't know (e.g. the plugin's CustomDebuffs, /// or one added later), written back unchanged. @@ -94,6 +97,7 @@ public class MonsterRule : INotifyPropertyChanged OffhandId = _offhandId, PreferredAmmoItemId = _preferredAmmoItemId, PetDamage = _petDamage, + Kite = _kite, }; } @@ -122,6 +126,7 @@ public class MonsterRule : INotifyPropertyChanged OffhandId = src.OffhandId; PreferredAmmoItemId = src.PreferredAmmoItemId; PetDamage = src.PetDamage; + Kite = src.Kite; } public event PropertyChangedEventHandler? PropertyChanged; diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 005e620..5dfbb05 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -113,10 +113,16 @@ internal static unsafe class FakeHost /// 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; + /// Optional: runs for every give instead of the default landing (a test's own server: NPC takes one per give, busy, ...). + public static Action? GiveHandler; /// Opt-in: wires StopCompletely (off by default so no other test sees it). public static bool StopCalls; /// StopCompletely calls (opt-in with ). public static int Stops; + /// Opt-in: wires MeleeAttack and MissileAttack; calls land in . + public static bool AttackSendCalls; + /// Every melee or missile attack (kind, target, height, power), in order (opt-in with ). + public static readonly List<(string Kind, uint Target, int Height, float Power)> AttackCalls = new(); /// Opt-in: wires SetMotion; calls land in . public static bool SetMotionCalls; /// Every SetMotion (motion, on), in order (opt-in with ). @@ -139,6 +145,8 @@ internal static unsafe class FakeHost /// and is counted in , not in . public static bool RequestIdAccepts = true; public static int RefusedIdRequests; + /// False = UseObject returns 0 (the engine did not send it); the use is still recorded in . + public static bool UseObjectAccepts = true; /// Opt-in (set before Create): UseObject, RequestId, HasAppraisalData and /// GetCurrentCombatMode (answering ). Tests written without /// them keep seeing those calls as absent. @@ -261,7 +269,9 @@ internal static unsafe class FakeHost public static void Reset() { EquippedCalls = false; EquippedNotReady = false; Equipped.Clear(); +#if !RYNTHILT_TESTS RynthCore.Plugin.RynthAi.EquippedState.Invalidate(); +#endif Nav3DCalls = false; Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear(); Names.Clear(); Positions.Clear(); ItemTypes.Clear(); Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear(); @@ -272,9 +282,9 @@ 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(); AfterCastSpell = null; - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1; - RequestIdAccepts = true; RefusedIdRequests = 0; + RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false; WeenieErrorCalls = false; WeenieErrSeq = 0; WeenieErrCode = WeenieErrEvent = WeenieErrObject = 0; @@ -349,6 +359,11 @@ internal static unsafe class FakeHost api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl])&StopCompletely; if (SetMotionCalls) api.SetMotionFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetMotion; + if (AttackSendCalls) + { + api.MeleeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl])&MeleeAttack; + api.MissileAttackFn = (IntPtr)(delegate* unmanaged[Cdecl])&MissileAttack; + } if (Nav3DCalls) { api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DClear; @@ -778,6 +793,12 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); Sent.Add(AutoRun ? "autorun on" : "autorun off"); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int MeleeAttack(uint target, int height, float power) { AttackCalls.Add(("melee", target, height, power)); return 1; } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int MissileAttack(uint target, int height, float power) { AttackCalls.Add(("missile", target, height, power)); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SetMotion(uint motion, int on) { MotionCalls.Add((motion, on != 0)); Sent.Add($"motion 0x{motion:X8} {(on != 0 ? "on" : "off")}"); return 1; } @@ -803,7 +824,10 @@ internal static unsafe class FakeHost private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); - if (GiveLands && amount == 0) Containers[item] = target; + if (GiveHandler != null) { GiveHandler(item, target, amount); return 1; } + // The server takes the whole object for amount 0, or for an amount that covers the stack (a single + // item has no StackCount: its stack is 1, so an explicit 1 takes it whole). + if (GiveLands && (amount == 0 || amount >= (Ints.TryGetValue((item, 12), out int stack) ? stack : 1))) Containers[item] = target; return 1; } @@ -813,7 +837,7 @@ internal static unsafe class FakeHost private static int ChangeCombatMode(int mode) { if (CombatModeRefuse) { CombatModeRefusals++; return 0; } CombatModeRequests.Add(mode); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int UseObject(uint id) { Uses.Add(id); OnUseObject?.Invoke(id); return 1; } + private static int UseObject(uint id) { Uses.Add(id); OnUseObject?.Invoke(id); return UseObjectAccepts ? 1 : 0; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectState(uint id, uint* state) { diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 20bfc46..ec50861 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -92,10 +92,13 @@ internal static class Program TargetingTests.Register(runner); LootAddItemTests.Register(runner); GiveTests.Register(runner); + IdRefusalTests.Register(runner); DungeonMapBakeTests.Register(runner); MonsterEditorTests.Register(runner); InstallPathsTests.Register(runner); PetRefillTests.Register(runner); + AutoStackTests.Register(runner); + RingEvadeTests.Register(runner); IgnoreMonsterTests.Register(runner); WorldCacheTypedTests.Register(runner); NavOverlayTests.Register(runner); @@ -128,12 +131,15 @@ internal static class Program VTankHotkeyTests.Register(runner); OneTouchHealTests.Register(runner); SaveFailureTests.Register(runner); + EnvironmentImpactTests.Register(runner); + SkCombatAddonTests.Register(runner); DoorTests.Register(runner); ServerPolicyTests.Register(runner); BlankLoadTests.Register(runner); GiveProfileTests.Register(runner); TinkerTests.Register(runner); LauncherSwapTests.Register(runner); + MissileCraftingTests.Register(runner); SelfRatingsTests.Register(runner); IltClientLookupTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs index 18310e5..2a53cef 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs @@ -66,7 +66,8 @@ internal static class ActionPacingTests r.Add("refusal: missile crafting asks for peace until accepted, and combines after the 2.5 s ceiling; already in peace it combines on the first tick with no mode request", CraftingPeaceRefusal); r.Add("pacing (stance): a refused ChangeCombatMode burns no try and no backoff step, and the next tick asks again (pacing on and off)", RefusedStanceBurnsNothing); r.Add("corpse id: a refused RequestId is not recorded as asked - the next evaluation asks again and the accepted one goes out", CorpseIdRefusedRetried); - r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, with no give-up cap", CorpseIdReaskedWithoutData); + r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, at most 3 re-asks per corpse", CorpseIdReaskedWithoutData); + r.Add("corpse id: Loot From All Corpses needs no killer name - the first request goes out, no re-ask ever follows; My Kills Only gives up after 3 re-asks, a new corpse starts over", CorpseIdAllCorpsesNoReask); r.Add("corpse id: two corpses in range, no data for either - only the targeted one re-asks; the other stays at one accepted request (a refused one is still retried)", CorpseIdOnlyCandidateReasks); r.Add("corpse id: 20 uncached corpses, a refusal window, then accept - at most 2 requests in the first accepted tick, the target among them; refused retries are 250 ms apart", CorpseIdBurstCapped); r.Add("corpse id: the open container is a candidate and re-asks; delete and the >200 prune clear every id map", CorpseIdOpenContainerAndCleanup); @@ -871,13 +872,46 @@ internal static class ActionPacingTests Check.Eq(Asked(), 2, "1 s after the re-ask: waits"); _t += 2_000; bot.Call("EvaluateCorpseLootDecision", obj); - Check.Eq(Asked(), 3, "one re-ask per 3 s, and no cap"); + Check.Eq(Asked(), 3, "one re-ask per 3 s"); + _t += 3_000; + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 4, "the third re-ask is the last"); for (int i = 0; i < 10; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); } - Check.Eq(Asked(), 13, "ten more 3 s periods, ten more asks"); + Check.Eq(Asked(), 4, "ten more 3 s periods, no more asks: the corpse is given up on"); FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}."; _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); - Check.Eq(Asked(), 13, "once the data has arrived nothing more is asked"); + Check.Eq(Asked(), 4, "and once the data has arrived nothing is asked either"); + }); + + private static void CorpseIdAllCorpsesNoReask() => Paced(() => + { + // All Corpses: the killer name decides nothing, so no stream of requests (each accepted one + // raises the client's busy count). The one first request still goes out: the radar colours + // your own kills from the LongDesc it brings. + var (bot, obj) = CorpseIdRig(); + bot.S.LootOwnership = 2; + int Asked() => FakeHost.IdRequests.Count(i => i == Corpse); + bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 1, "All Corpses: the first request goes out"); + for (int i = 0; i < 6; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); } + Check.Eq(Asked(), 1, "All Corpses: no re-ask in 18 s without data"); + object dec = bot.Call("EvaluateCorpseLootDecision", obj)!; + Check.True((bool)dec.GetType().GetProperty("ShouldLoot")!.GetValue(dec)!, "the corpse is looted either way"); + + // The same corpse in My Kills Only: the cap applies, the count is per corpse and a deleted + // corpse starts over. + bot.S.LootOwnership = 0; + _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 2, "My Kills Only: the name is needed, so it re-asks"); + for (int i = 0; i < 10; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); } + Check.Eq(Asked(), 4, "and stops after the third re-ask"); + bot.Call("HandleCorpseObjectDeleted", Corpse); + _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); + Check.Eq(Asked(), 5, "a corpse that comes back (deleted and created again) starts over"); + var counts = bot.Get>("_corpseIdAskCount"); + bot.Call("HandleCorpseObjectDeleted", Corpse); + Check.False(counts.ContainsKey(unchecked((int)Corpse)), "delete clears _corpseIdAskCount"); }); private static void CorpseIdOnlyCandidateReasks() => Paced(() => { @@ -900,7 +934,7 @@ internal static class ActionPacingTests Check.Eq(Asked(Corpse), 1, "the candidate: refused once, then one accepted request"); Check.Eq(Asked(CorpseB), 1, "the other corpse: a refused request is retried, one accepted request"); for (int i = 0; i < 4; i++) { _t += 3_000; Both(); } - Check.Eq(Asked(Corpse), 5, "no data: the candidate re-asks once per 3 s"); + Check.Eq(Asked(Corpse), 4, "no data: the candidate re-asks once per 3 s, three times at most"); Check.Eq(Asked(CorpseB), 1, "the other corpse never asks a second time"); bot.Set("_targetCorpseId", unchecked((int)CorpseB)); _t += 3_000; Both(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AutoStackTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AutoStackTests.cs new file mode 100644 index 0000000..0b917ae --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AutoStackTests.cs @@ -0,0 +1,38 @@ +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// AutoStack (Loot/InventoryManager.cs): the group key and the merge-progress rule. From Silentkelpie's +// PR 12 (group by WCID: two stacks with the same name but different weenies never merge, and AutoStack +// retried them forever), plus the partial fill: a pair whose total is over the max is still merged +// (the server fills the target, the source survives smaller) and that counts as progress. +internal static class AutoStackTests +{ + public static void Register(Runner r) + { + r.Add("autostack: stacks group by WCID; the name is only the fallback while the WCID is unknown", GroupKey); + r.Add("autostack: a partial fill (target grew, source shrank) is progress; an untouched pair is not", Progress); + } + + private static void GroupKey() + { + Check.True(InventoryManager.StackGroupKey(42517, "Coalesced Mana") != InventoryManager.StackGroupKey(42518, "Coalesced Mana"), + "same name, different WCIDs: separate groups"); + Check.Eq(InventoryManager.StackGroupKey(42517, "Coalesced Mana"), InventoryManager.StackGroupKey(42517, "Coalesced Mana (renamed)"), + "same WCID: one group whatever the label says"); + Check.Eq(InventoryManager.StackGroupKey(0, "Taper"), InventoryManager.StackGroupKey(0, "Taper"), "no WCID: the name groups"); + Check.True(InventoryManager.StackGroupKey(0, "Taper") != InventoryManager.StackGroupKey(5, "Taper"), "known and unknown WCID do not mix"); + Check.True(InventoryManager.StackGroupKey(7, null).Length > 0, "a null name is safe"); + } + + private static void Progress() + { + // 90 + 20 over a max of 100: the server fills the target to 100 and leaves 10 in the source. + Check.True(InventoryManager.MergeProgressed(90, 20, 100, 10), "partial fill"); + Check.True(InventoryManager.MergeProgressed(30, 20, 50, 20), "target grew (source count read late)"); + Check.True(InventoryManager.MergeProgressed(30, 20, 30, 0), "source emptied"); + Check.False(InventoryManager.MergeProgressed(30, 20, 30, 20), "nothing changed: not progress"); + Check.False(InventoryManager.MergeProgressed(0, 20, 30, 20), "no recorded counts: not progress"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs index 8414bac..1b15121 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs @@ -70,6 +70,7 @@ internal static class BuffTests r.Add("buff filter: the skip line groups by reason, is capped, and repeats only when it changes", SkipLineGroupedAndCapped); r.Add("buff filter: the weapon kit is cached for a second, and rebuilt when its inputs change", KitCached); r.Add("buff filter: skipped buffs are named, once per run", FilterVisibility); + r.Add("buff filter: untrained skills alone never print a chat line (log, page and /ra buff skipped keep them)", UntrainedSkillIsQuiet); r.Add("buff filter: SkipUnusableBuffs defaults on, loads, saves, bridges, is in the settings map", SkipUnusableSetting); 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 @@ -93,6 +94,11 @@ internal static class BuffTests r.Add("buff upgrade: a late line the cast tracker credits to an earlier send does not confirm the pending cast", UpgradeLateLineFromEarlierSend); r.Add("buff upgrade: two upgrade no-shows do not park the family; its lower level running low is recast", UpgradeNoShowsDoNotPark); r.Add("buff upgrade: two item spell upgrades with no chat do not park the family; its lower level running low is recast", UpgradeArmorNoChatDoesNotPark); + r.Add("buff upgrade: an upgrade an item spell never lands is parked, not looped; the lower level is still refreshed and the park ends", UpgradeArmorNoChatParksUpgrade); + r.Add("buff upgrade: three silent self-buff no-shows park the upgrade only; the lower level is still refreshed", UpgradeNoShowsParkUpgrade); + r.Add("buff upgrade: an in-run upgrade the server never answers is parked and the force run ends", UpgradeNoShowInRunEnds); + r.Add("buff upgrade: a confirmed upgrade resets the no-show count", UpgradeConfirmedResetsNoShows); + r.Add("buff upgrade: Cancel Buffing ends the pending upgrade", UpgradeCancelEndsPending); r.Add("buff upgrade: an upgrade that would leave mana under the reserve waits for Stamina to Mana, then goes", UpgradeWaitsForManaReserve); } @@ -1389,10 +1395,12 @@ internal static class BuffTests /// Lets the pending reach its give-up unanswered twice (it is resent /// in between); returns the give-ups done. Every other cast is confirmed. - private static int FailTwice(BeatRig h, int id) + private static int FailTwice(BeatRig h, int id) => FailTimes(h, id, 2); + + private static int FailTimes(BeatRig h, int id, int times) { int gaveUp = 0; - for (int k = 0; k < 20 && gaveUp < 2; k++) + for (int k = 0; k < 20 && gaveUp < times; k++) { if (h.R.B.PendingSpellId != id) { if (h.Beats(40, x => x == id) == 0) break; continue; } h.SendLongAgo(6); @@ -1448,6 +1456,133 @@ internal static class BuffTests Check.True(h.Beats(40, id => FamilyOf(id) == fam) != 0, "running low: recast"); } + private static bool Has(BuffManager b, string field, int key) => ((System.Collections.IDictionary)Fld(b, field)).Contains(key); + + /// The registry as the first run left it (every player buff of the suite at tier 6), CEM with s left. + private static (string, double)[] SixRegistry(int cem, double cemLeft) => + FakeHost.Casts.Select(c => c.SpellId).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).Distinct() + .Select(id => (NameOf(id), FamilyOf(id) == cem ? cemLeft : 3000.0)).ToArray(); + + // Review finding (PR 15): an upgrade that is a SILENT no-show was never struck, parked or counted, so it + // was recast at every give-up forever (12x/minute), and a force/batch run never ended. Now: after three in + // a row the upgrade alone is parked; the family is not blacklisted and its lower level still refreshes. + private static void UpgradeNoShowsParkUpgrade() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var h = new BeatRig(300); + h.FirstRun(); + FakeHost.Skills[(Player, STypeCreature)] = (340, 2); + h.R.Live(SixRegistry(cem, 3000)); + int seven = h.Beats(60, id => FamilyOf(id) == cem && LevelOf(id) == 7); + Check.True(seven != 0, "CEM 7 is sent over the live VI"); + Check.Eq(FailTimes(h, seven, 3), 3, "three no-shows"); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 3, "sent three times, not a fourth: the upgrade is parked"); + Check.False(Parked(h.R, cem), "the family itself is not parked"); + + // Nothing more goes out for it, and the run (the batch the upgrade started) ends. + h.Beats(150, _ => false); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 3, "still three after 150 more beats"); + Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the run ends"); + Check.Eq(h.R.B.PendingSpellId, 0, "nothing pending"); + + // The level it was cast over runs low: a normal refresh goes out (not counted as an upgrade). + int upgrades = h.R.B.BuffUpgrades; + h.R.Live(SixRegistry(cem, 100)); + Check.True(h.Beats(150, id => FamilyOf(id) == cem) != 0, "the lower level running low is recast while the upgrade is parked"); + Check.Eq(h.R.B.BuffUpgrades, upgrades, "and that cast is not an upgrade"); + Check.False(Parked(h.R, cem), "the family is still not parked"); + } + + // The item spell twin (armor lost on death / weapon swapped, its lower record still unexpired). + private static void UpgradeArmorNoChatParksUpgrade() + { + var h = new BeatRig(300); + h.FirstRun(); + FakeHost.Skills[(Player, STypeItem)] = (340, 2); + int item7 = h.Beats(80, id => BuffManager.IsItemEnchantment(NameOf(id)) && LevelOf(id) == 7); + Check.True(item7 != 0, "an item spell is upgraded to 7: " + NameOf(item7)); + int fam = FamilyOf(item7); + Check.Eq(FailTimes(h, item7, 3), 3, "three no-chat give-ups"); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), 3, "sent three times, not a fourth"); + Check.False(Parked(h.R, fam), "the family itself is not parked"); + h.Beats(150, _ => false); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), 3, "still three after 150 more beats"); + Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the run ends"); + + // Its VI record runs low: the family is recast (a normal refresh, not an upgrade). + int upgrades = h.R.B.BuffUpgrades; + object rec = ((System.Collections.IDictionary)Fld(h.R.B, "_itemSpellTimers"))[fam]!; + rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(100)); + Check.True(h.Beats(60, id => FamilyOf(id) == fam) != 0, "running low: recast while the upgrade is parked"); + Check.Eq(h.R.B.BuffUpgrades, upgrades, "not an upgrade"); + Check.False(Parked(h.R, fam), "the family is not parked"); + + // The park is time-boxed: once it ends the upgrade is tried again. + h.R.B.CancelBuffing(); + rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(3000)); + ((System.Collections.IDictionary)Fld(h.R.B, "_upgradeParkedUntil"))[fam] = DateTime.Now.AddSeconds(-1); + Check.True(h.Beats(80, id => id == item7) != 0, "after the park ends the upgrade is cast again"); + } + + // An explicit force run with an upgrade the server never answers: parked after three, the run ends. + private static void UpgradeNoShowInRunEnds() + { + int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI"); + var h = new BeatRig(300); + h.R.Live(("Strength Self I", 3000)); + h.R.B.ForceFullRebuff(); + int n = 0; + int seven = h.Beats(150, id => { if (++n == 3) FakeHost.Skills[(Player, STypeCreature)] = (340, 2); return FamilyOf(id) == cem && LevelOf(id) == 7; }); + Check.True(seven != 0, "CEM 7 is sent in the run, over the VI it cast"); + Check.Eq(FailTimes(h, seven, 3), 3, "three no-shows"); + h.Beats(200, _ => false); + // The registry here never shows the run's VIs, so once the upgrade is parked CEM is cast as an ordinary + // buff with no timer, and the usual two-strike no-show park ends that: three upgrade sends + at most two. + int sends = FakeHost.Casts.Count(c => c.SpellId == seven); + Check.True(sends <= 3 + 2, $"bounded: {sends} sends of CEM 7"); + Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the force run ends (it kept buffing's priority for good)"); + Check.Eq(h.R.B.PendingSpellId, 0, "nothing pending"); + } + + // Confirmed upgrades are unchanged: they land, and they reset the count (the next upgrade starts from zero). + private static void UpgradeConfirmedResetsNoShows() + { + var h = new BeatRig(300); + h.FirstRun(); + FakeHost.Skills[(Player, STypeItem)] = (340, 2); + int item7 = h.Beats(80, id => BuffManager.IsItemEnchantment(NameOf(id)) && LevelOf(id) == 7); + Check.True(item7 != 0, "an item spell is upgraded to 7"); + int fam = FamilyOf(item7); + Check.Eq(FailTimes(h, item7, 2), 2, "two no-chat give-ups"); + Check.Eq(h.R.B.PendingSpellId, item7, "sent again"); + Check.True(Has(h.R.B, "_upgradeNoShowCounts", fam), "two are counted"); + h.R.B.OnChatWindowText($"You cast {NameOf(item7)} on Rune Robe", 7); // it lands + Check.False(Has(h.R.B, "_upgradeNoShowCounts", fam), "the count is reset by the landing"); + Check.False(Has(h.R.B, "_upgradeParkedUntil", fam), "nothing parked"); + int sends = FakeHost.Casts.Count(c => c.SpellId == item7); + h.Beats(60, _ => false); + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), sends, "landed at 7: not cast again"); + + // The record falls back to VI (armor swapped): the upgrade gets a full three tries again. + object rec = ((System.Collections.IDictionary)Fld(h.R.B, "_itemSpellTimers"))[fam]!; + rec.GetType().GetField("SpellLevel")!.SetValue(rec, 6); + Check.True(h.Beats(80, id => id == item7) != 0, "the upgrade is cast again"); + Check.Eq(FailTimes(h, item7, 2), 2, "two more no-shows"); + Check.Eq(h.R.B.PendingSpellId, item7, "not parked: sent again after the second"); + Check.False(Has(h.R.B, "_upgradeParkedUntil", fam), "the count started from zero"); + } + + // Cancelling the buff step left the pending upgrade behind. + private static void UpgradeCancelEndsPending() + { + var (rig, seven) = PendingCem7(); + Check.True(seven != 0 && rig.B.PendingSpellId == seven, "CEM 7 is pending"); + Check.Eq(Fld(rig.B, "_pendingUpgradeSpellId"), seven, "as an upgrade"); + rig.B.CancelBuffing(); + Check.Eq(rig.B.PendingSpellId, 0, "cancelled"); + Check.Eq(Fld(rig.B, "_pendingUpgradeSpellId"), 0, "the upgrade is no longer pending"); + } + // No limit and no rest, through OnHeartbeat: an always-fizzling CEM 7 is sent on // every beat (one per answer), the late VI line confirms nothing, and nothing goes out unanswered. private static void UpgradeCapViaHeartbeat() @@ -1637,8 +1772,15 @@ internal static class BuffTests Check.False(rig.B.GetStateSnapshot().IsForceRebuffing, "/ra buff cancel ends it"); FakeHost.Chat.Clear(); + int kitRuns = rig.B.KitComputations; Cmd("skipped"); - Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter")), "/ra buff skipped answers"); + Check.Eq(FakeHost.Chat.Count, 0, "/ra buff skipped only queues the report: the command thread builds nothing and says nothing"); + Check.Eq(rig.B.KitComputations, kitRuns, "and never touches the pump's weapon-kit state"); + rig.B.OnHeartbeat(); + Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter")), "/ra buff skipped answers from the next heartbeat"); + FakeHost.Chat.Clear(); + rig.B.OnHeartbeat(); + Check.Eq(FakeHost.Chat.Count, 0, "once per request"); FakeHost.Chat.Clear(); Cmd(); Check.True(FakeHost.Chat.Any(c => c.Contains("/ra buff force")), "no word: the help"); @@ -1751,7 +1893,8 @@ internal static class BuffTests Check.True(lines[0].Contains("skill untrained: ") && lines[0].Contains("Heavy Weapon"), "it names the untrained mastery and why: " + lines[0]); Check.True(lines[0].Contains("no melee or missile weapon listed: Blood Drinker"), "and the weapon aura and why: " + lines[0]); Check.False(lines[0].Contains("Spirit Drinker"), "but not what stays"); - Check.True(FakeHost.Chat.Any(c => c.Contains("Buff run skips")), "the same line goes to chat"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Buff run skips") && c.Contains("no melee or missile weapon listed")), "a line goes to chat for the aura"); + Check.False(FakeHost.Chat.Any(c => c.Contains("Buff run skips") && c.Contains("skill untrained")), "but the untrained skill stays out of the chat line"); Check.True(rig.B.FilterSkipSummary().Contains("Swift Killer"), "the settings page reads the same list"); // The automatic batch logs it too, once. @@ -1769,6 +1912,27 @@ internal static class BuffTests Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] filter skips:")), 0, "nothing skipped: no line"); } + // An untrained skill is the normal state of most characters. It must not print a chat line at every buff run. + private static void UntrainedSkillIsQuiet() + { + var rig = SuiteRig(MeleeItem, WandItem); + FakeHost.Skills[(Player, SkillHeavy)] = (10, 1); // untrained, and nothing else is skipped + rig.Live(("Strength Self I", 3000)); + rig.B.ForceFullRebuff(); + Check.True(rig.B.FilterSkips.Count > 0 && rig.B.FilterSkips.All(s => s.Reason == "skill untrained"), "only untrained skills are skipped"); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("Buff run skips")), 0, "no chat line for untrained skills alone"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] filter skips:") && l.Contains("skill untrained")), 1, "the log keeps it"); + Check.True(rig.B.FilterSkipSummary().Contains("skill untrained: ") && rig.B.FilterSkipSummary().Contains("Heavy Weapon"), "the Buffing page summary keeps it"); + rig.B.RequestSkipReport(); + rig.B.OnHeartbeat(); + Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter skips: ") && c.Contains("skill untrained")), "so does /ra buff skipped"); + + // A later run stays quiet in chat too. + FakeHost.Chat.Clear(); + rig.B.ForceFullRebuff(); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("Buff run skips")), 0, "still quiet"); + } + private static void KitEdgeCases() { // A listed item the cache keeps unclassified (a Misc-typed thing): nothing is filtered. diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs index a82cad0..6ea13d5 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs @@ -28,6 +28,8 @@ internal static class CombatHookTests public static void Register(Runner r) { r.Add("combat hook: the decided spell reaches the cast (hook off: RynthAi's bolt)", DecidedSpellIsCast); + r.Add("combat hook: a rule with no attack shapes enabled is not asked and not cast at, script or not", ScriptRespectsNoAttackShapes); + r.Add("combat hook: shutdown clears the UseDone reader (it captured the host)", ShutdownDropsUseDoneReader); r.Add("combat hook: a decline casts RynthAi's own spell the same tick", DeclineGoesNative); r.Add("combat hook: no answer by the deadline - RynthAi's spell, the timeout logged once a minute", TimeoutGoesNative); r.Add("combat hook: a lapsed lease is native; another owner is refused while the lease is live", LeaseExpiry); @@ -236,6 +238,45 @@ internal static class CombatHookTests Check.Eq((next.LastSeq, next.LastSpell, next.LastTarget), (req.Seq, (uint)drain, (uint)Target), "ctx.last is the previous cast"); }); + // A rule with every attack shape off means no offensive cast at that monster; a script's attack is no exception. + private static void ScriptRespectsNoAttackShapes() => Guard(() => + { + int drain = Id("Drain Health Other V"); + + var off = new AttackRig(); + off.S.MonsterRules.Clear(); + off.S.MonsterRules.Add(new MonsterRule { Name = "Default", DamageType = "Fire", UseBolt = false, UseArc = false, UseStreak = false, UseRing = false, UseBlast = false, UseWall = false }); + Claim(Atk); + off.Attack(); + Check.Eq(CombatHook.Attack.Opened, 0, "no shapes: the script is not even asked"); + Check.Eq(off.C.LastCombatSkipReason, "no-attack-shapes", "skipped for the rule"); + Check.False(off.C.ScriptHeld, "and not held for an answer"); + Check.Eq(FakeHost.Casts.Count, 0, "nothing cast"); + + // Control: the same script with a shape on is asked and its spell is cast. + var on = new AttackRig(); + Claim(Atk); + ScriptCast(on, drain); + Check.Eq(CombatHook.Attack.Opened, 1, "a shape on: the script is asked"); + Check.True(FakeHost.Casts.Any(c => c.SpellId == drain), "and its spell is cast"); + }); + + // The UseDone reader the plugin installs captures its host; a shut-down plugin must not keep it. + private static void ShutdownDropsUseDoneReader() => Guard(() => + { + CombatHook.LastUseDone = () => (1, 0u); + CombatHookInterface.Shutdown(); // PluginExports.Shutdown calls it for every unload + Check.Null(CombatHook.LastUseDone, "the exported shutdown clears the reader"); + + FakeHost.Reset(); + var host = FakeHost.Create(Player); + var plugin = new RynthAiPlugin(); + PacerEdgeTests.SetHost(plugin, host); + CombatHook.LastUseDone = () => (1, 0u); + plugin.Shutdown(); + Check.Null(CombatHook.LastUseDone, "and so does the plugin's own Shutdown"); + }); + private static void DeclineGoesNative() => Guard(() => { var rig = new AttackRig(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CorpseCloseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CorpseCloseTests.cs index ec12d6b..c0ed1b4 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CorpseCloseTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CorpseCloseTests.cs @@ -7,6 +7,7 @@ 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; @@ -41,6 +42,9 @@ internal static class CorpseCloseTests r.Add("corpse close: the next corpse is opened without closing the finished one; its late close doesn't disturb the new open", NextCorpseWithoutClose); r.Add("corpse close: a held-back close is sent when no other corpse is opened in time, and when the macro stops", DeferredCloseFallback); r.Add("loot pickup: a pickup that merges into a pack stack is confirmed when the stack grows, not after 4 s", StackMergeConfirmed); + r.Add("loot timeout: a pickup held for a cast's answer does not time the corpse out; the pickup goes on the answer", HeldPickupKeepsCorpseClock); + r.Add("loot timeout: an unheld stall (nothing to take, nothing held) still times the corpse out", UnheldStallStillTimesOut); + r.Add("corpse close: the close is held back only when the next corpse can be claimed now (not while buffing), and a hold that starts later ends the wait", DeferredCloseNeedsClaimableCorpse); } private static long _now; @@ -54,6 +58,21 @@ internal static class CorpseCloseTests finally { RynthAiPlugin.CorpseClock = old; } } + /// The pacer (and the audits whose stop / use times it reads) on the same hand-moved clock as the loot. + private static void PacerOn() + { + ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _now; + MoveAudit.Reset(); MoveAudit.NowMs = () => _now; + UseAudit.NowMs = () => _now; + } + + private static void PacerOff() + { + ActionPacer.Enabled = false; ActionPacer.Reset(); ActionPacer.NowMs = () => Environment.TickCount64; + MoveAudit.Reset(); MoveAudit.NowMs = () => Environment.TickCount64; + UseAudit.NowMs = () => Environment.TickCount64; + } + private static void Corpse(uint id, float dx) { FakeHost.Names[id] = "Corpse of Olthoi Swarm Drone"; @@ -227,6 +246,101 @@ internal static class CorpseCloseTests Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "the last corpse is closed at once"); }); + // A pickup is refused (ACE: YoureTooBusy) while the server owes an answer to a cast, so it waits + // (ActionPacer.Outstanding). The corpse's own clock (LootCorpseTimeoutMs) used to keep running + // through that wait, and the first tick after the answer abandoned an OPENED corpse, which gets + // the 30-minute completed mark: its loot was skipped. + private static void HeldPickupKeepsCorpseClock() => Clocked(() => + { + World(twoCorpses: false); + FakeHost.ServerGates = true; // GetUseDoneSeq, GetCastBusyState + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.LootCorpseTimeoutMs = 2000; + PacerOn(); + try + { + bot.Create(CorpseA, GemA); + bot.Tick(); + Check.True(FakeHost.Uses.Contains(CorpseA), "corpse A is opened"); + FakeHost.UseDone(0); + FakeHost.GroundContainer = CorpseA; + bot.P.OnViewObjectContents(CorpseA); + + // A cast goes out and has no answer yet when the contents arrive: the pickup waits for it, + // two and a half corpse timeouts, still inside the pacer's own limit (CastMaxMs, 7 s). + ActionPacer.Begin(host, PacedKind.Cast, 0, "Bloodstone Bolt VII", "Combat", FakeHost.UseDoneSeq); + bot.TickFor(5_000); + Check.False(FakeHost.ExternalMoves.Any(m => m.Id == GemA), "no pickup while the cast is unanswered"); + Check.True(Logged("pickup waits - the server still owes an answer"), "the hold is logged"); + Check.False(Logged("abandoning corpse"), "the corpse is not abandoned while the pickup is held"); + Check.Eq(bot.Get("_openedContainerId"), unchecked((int)CorpseA), "and stays the open corpse"); + + FakeHost.UseDone(0); // the cast is answered + for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == GemA); i++) { _now += 20; bot.Tick(); } + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == GemA), "the pickup goes on the answer"); + FakeHost.Containers[GemA] = Player; + for (int i = 0; i < 200 && !bot.Completed(CorpseA); i++) { _now += 20; bot.Tick(); } + Check.True(bot.Completed(CorpseA), "and the corpse is completed by its loot, not by the timeout"); + Check.False(Logged("abandoning corpse"), "never abandoned"); + } + finally { PacerOff(); } + }); + + private static void UnheldStallStillTimesOut() => Clocked(() => + { + World(twoCorpses: false); + FakeHost.ServerGates = true; + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.LootCorpseTimeoutMs = 2000; + bot.S.LootEmptyCorpseMs = 60_000; // the corpse neither shows items nor is called empty: a stall + PacerOn(); + try + { + bot.Create(CorpseA); // the gem is never seen + bot.Tick(); + Check.True(FakeHost.Uses.Contains(CorpseA), "corpse A is opened"); + FakeHost.UseDone(0); + FakeHost.GroundContainer = CorpseA; + bot.P.OnViewObjectContents(CorpseA); + bot.TickFor(1_500); + Check.False(Logged("abandoning corpse"), "inside the timeout"); + bot.TickFor(1_000); + Check.True(Logged("abandoning corpse") && Logged("(timeout)"), "an unheld stall is still abandoned on the timeout"); + } + finally { PacerOff(); } + }); + + private static void DeferredCloseNeedsClaimableCorpse() => Clocked(() => + { + // The next-corpse test itself: B is in range and A is done. Buffing holds every claim, so + // there is nothing to wait for. + World(twoCorpses: true); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.Create(CorpseA, CorpseB, GemA, GemB); + bot.Get>("_completedCorpses")[unchecked((int)CorpseA)] = _now; + bool Other() => (bool)typeof(RynthAiPlugin).GetMethod("OtherCorpseToLoot", Any)!.Invoke(bot.P, new object[] { unchecked((int)CorpseA) })!; + Check.True(Other(), "B is in range and claimable: the close is worth deferring"); + bot.S.BotAction = "Buffing"; + Check.False(Other(), "buffing holds every claim: no deferral"); + bot.S.BotAction = "Default"; + Check.True(Other(), "and it is back once the hold ends"); + + // A hold that starts while the close is deferred ends the wait at once (not after 3 s). + World(twoCorpses: true); + var host2 = FakeHost.Create(Player); + var bot2 = new Bot(host2); + bot2.Create(CorpseA, CorpseB, GemA, GemB); + LootCorpseA(bot2); + Check.Eq(FakeHost.Closes.Count, 0, "held back while B can be claimed"); + bot2.S.BotAction = "Buffing"; + _now += 20; bot2.Tick(BotActivity.Looting); + Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "buffing began: A is closed at once, once"); + Check.True(Logged("the next corpse can't be claimed now"), "and the reason is logged"); + }); + private static void StackMergeConfirmed() => Clocked(() => { World(twoCorpses: false); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/EnvironmentImpactTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/EnvironmentImpactTests.cs new file mode 100644 index 0000000..9eee10d --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/EnvironmentImpactTests.cs @@ -0,0 +1,514 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Environment-impact throttle and per-monster attack power (2026-10-12). Arrows into a wall +// ("Your missile attack hit the environment.") or war bolts stopping short of the target count +// against that target; at the limit within the window, combat stops attacking it and moves closer, +// switches target (this one skipped for a while), or moves closer once and then switches, as chosen +// separately for missile and magic combat. The only monster in reach is never skipped. A monster +// rule's Power picks High / Reckless / Variable / Reckless + Variable per monster. +internal static class EnvironmentImpactTests +{ + private const uint Player = 0x50000F01; + private const uint Lb = 0xA9B40000; + private const uint A = 0x80000401, B = 0x80000402, Bolt = 0x80000499; + + public static void Register(Runner r) + { + r.Add("env impact: the response decision (move closer, new target, closer then new, the only monster)", Decide); + r.Add("env impact: hits count per target inside the window; approaches are remembered", Throttle); + r.Add("env impact: a projectile is short only when it stopped away from the target and nearer the caster", Judge); + r.Add("env impact: missile lines trip New target: the attack stops, the target is skipped, the next is picked", MissileNewTarget); + r.Add("env impact: Move closer runs toward the target and stops at the goal; the only monster is never skipped", MissileApproach); + r.Add("env impact: Off, or not in Missile mode: the line is ignored", MissileOff); + r.Add("env impact: a player's copy of the missile line (their chat type, or their name in front) is not a hit", MissileSpoof); + r.Add("env impact: a bolt stopping short with no hit counts; one with a hit line, or reaching the target, doesn't", MagicShort); + r.Add("env impact: an approach Think stops driving lets go of autorun", ApproachOrphan); + r.Add("env impact (flight 63260): 3 magic casts landing nothing -> one short real sidestep; a hit resets; 30 s apart", ResyncSidestep); + r.Add("env impact: the throttle switching target restarts the re-sync's miss count", ResyncCountResetByThrottle); + r.Add("env impact: moving closer drops a wanted re-sync sidestep", ResyncDroppedByApproach); + r.Add("env impact: a re-sync sidestep holding its key finishes before the throttle runs", ResyncStepFinishesFirst); + r.Add("env impact: a re-sync sidestep Think stops driving, or a macro stop, lets go of the key", ResyncKeyReleased); + r.Add("attack power: Default/High/Reckless/Variable/Reckless + Variable, the DEFAULT line, untrained Recklessness", Power); + r.Add("attack power: an engine without the Power column keeps each rule's power", PowerCarriedOver); + } + + // ── Pure rules ─────────────────────────────────────────────────────────── + + private static void Decide() + { + var M = EnvironmentResponse.MoveCloser; var N = EnvironmentResponse.NewTarget; var C = EnvironmentResponse.CloserThenNewTarget; + EnvironmentAction D(EnvironmentResponse r, int done, double dist, bool alt) => EnvironmentImpactPlanner.Decide(r, done, dist, 3, alt); + + Check.Eq(D(EnvironmentResponse.Off, 0, 20, true), EnvironmentAction.None, "Off: nothing"); + Check.Eq(D(M, 0, 20, true), EnvironmentAction.Approach, "Move closer, far: approach"); + Check.Eq(D(M, 3, 20, false), EnvironmentAction.Approach, "Move closer approaches every time it trips"); + Check.Eq(D(M, 0, 3.2, true), EnvironmentAction.NewTarget, "Move closer, already at the closest: new target"); + Check.Eq(D(M, 0, 3.2, false), EnvironmentAction.None, "... but not the only monster: keep attacking"); + Check.Eq(D(N, 0, 20, true), EnvironmentAction.NewTarget, "New target with another in reach: switch"); + Check.Eq(D(N, 0, 20, false), EnvironmentAction.Approach, "New target, nothing else: approach instead of idling"); + Check.Eq(D(N, 0, 2, false), EnvironmentAction.None, "New target, nothing else, already close: keep attacking"); + Check.Eq(D(C, 0, 20, true), EnvironmentAction.Approach, "Closer then new: the first trip approaches"); + Check.Eq(D(C, 1, 14, true), EnvironmentAction.NewTarget, "... the second switches"); + Check.Eq(D(C, 1, 14, false), EnvironmentAction.Approach, "... unless it's the only monster"); + Check.Eq(D(M, 0, double.NaN, true), EnvironmentAction.NewTarget, "unknown distance: no approach"); + + Check.Near(EnvironmentImpactPlanner.ApproachGoal(20, 6, 3), 14, 1e-9, "goal: 6 m nearer"); + Check.Near(EnvironmentImpactPlanner.ApproachGoal(7, 6, 3), 3, 1e-9, "goal: never inside the closest distance"); + Check.Eq(EnvironmentImpactPlanner.Parse(9), EnvironmentResponse.Off, "an out-of-range saved value is Off"); + Check.Eq(EnvironmentImpactPlanner.Name(3), "Move closer, then new target", "labels follow the enum"); + } + + private static void Throttle() + { + var t = new EnvironmentImpactThrottle(); + var t0 = new DateTime(2026, 10, 12, 12, 0, 0); + Check.Eq(t.Record(1, t0, 20), 1, "first hit"); + Check.Eq(t.Record(2, t0, 20), 1, "per target"); + Check.Eq(t.Record(1, t0.AddSeconds(5), 20), 2, "second hit inside the window"); + Check.Eq(t.Count(1, t0.AddSeconds(21), 20), 1, "the first hit ages out"); + Check.Eq(t.Count(1, t0.AddSeconds(30), 20), 0, "both aged out"); + t.Record(1, t0.AddSeconds(31), 20); + t.ResetHits(1); + Check.Eq(t.Count(1, t0.AddSeconds(31), 20), 0, "reset after acting"); + t.NoteApproach(1); + Check.Eq(t.Approaches(1), 1, "approach remembered"); + t.Forget(1); + Check.Eq(t.Approaches(1), 0, "a deleted id forgets everything"); + Check.Eq(t.Record(0, t0, 20), 0, "no target: not counted"); + } + + private static void Judge() + { + Check.True(ProjectileImpactJudge.StoppedShort(impactToTarget: 10, casterToImpact: 10, casterToTarget: 20), "into a wall halfway"); + Check.False(ProjectileImpactJudge.StoppedShort(1.5, 18.5, 20), "at the target's surface"); + Check.False(ProjectileImpactJudge.StoppedShort(3.5, 17, 20), "a big monster's surface (within 4 m)"); + Check.False(ProjectileImpactJudge.StoppedShort(6, 21, 20), "past the target (a miss beyond, not a wall in front)"); + Check.False(ProjectileImpactJudge.StoppedShort(double.NaN, 10, 20), "unknown: never short"); + } + + // ── Through CombatManager ──────────────────────────────────────────────── + + private sealed class Rig + { + public readonly LegacyUiSettings S; + public readonly CombatManager C; + public readonly WorldObjectCache Cache; + public DateTime Now = new(2026, 10, 12, 12, 0, 0); + + /// The player at (96, 96) facing north; placed after the reset. + public Rig(int mode, Action set, params (uint Id, string Name, float X, float Y)[] mobs) + : this(mode, set, setMotion: false, mobs) { } + + /// As above; installs SetMotion (the re-sync sidestep needs it). + public Rig(int mode, Action set, bool setMotion, params (uint Id, string Name, float X, float Y)[] mobs) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.SetMotionCalls = setMotion; + FakeHost.CombatModeValue = mode; + Place(Player, "Me", 96, 96, creature: false); + foreach (var m in mobs) Place(m.Id, m.Name, m.X, m.Y); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + FakeHost.HeadingDeg = 0; + S = new LegacyUiSettings { MonsterRange = 50, IsMacroRunning = true, EnableCombat = true }; + set(S); + var host = FakeHost.Create(Player); // Think measures distances from GetPlayerId + Cache = FakeHost.MakeCache(host, Player, mobs.Select(m => m.Id)); + C = new CombatManager(host, S, Cache); + C.SetPlayerId(Player); + C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore()); + C.EnvClock = () => Now; + C.ScanNearbyTargets(); + C.HandleCombatTrigger(); + FakeHost.MotionCalls.Clear(); // the trigger's turn-motion clear-out isn't under test + } + + public double Dist(uint id) + { + var p = FakeHost.Positions[id]; + double dx = p.X - FakeHost.PlayerPose.X, dy = p.Y - FakeHost.PlayerPose.Y; + return Math.Sqrt(dx * dx + dy * dy); + } + + public bool Run() => C.RunEnvironmentImpact(Cache[C.activeTargetId]!, Dist((uint)C.activeTargetId)); + + public void MovePlayer(float x, float y) + { + FakeHost.PlayerPose = (Lb | 0x1C, x, y, 0f); + FakeHost.Positions[Player] = FakeHost.PlayerPose; + } + } + + private const string MissileLine = "Your missile attack hit the environment."; + // 20 m north of the player (the pick), and 24 m east. + private static readonly (uint, string, float, float) Skulker = (A, "Drudge Skulker", 96f, 116f); + private static readonly (uint, string, float, float) Slinker = (B, "Drudge Slinker", 120f, 96f); + + private static void MissileNewTarget() + { + var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; s.EnvironmentSkipSec = 30; }, Skulker, Slinker); + Check.Eq((uint)r.C.activeTargetId, A, "the nearer Skulker is locked"); + + r.C.HandleChatForDamage(MissileLine); + Check.False(r.Run(), "one hit: attacking on"); + r.Now = r.Now.AddSeconds(3); + r.C.HandleChatForDamage(MissileLine); + Check.True(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] missile") && l.Contains("2/2")), "both hits logged against the target"); + + Check.True(r.Run(), "the limit: this tick belongs to the response"); + Check.Eq(r.C.activeTargetId, 0, "the Skulker is dropped"); + Check.True(FakeHost.Logs.Any(l => l.Contains("leaving") && l.Contains("skipping it 30s")), "logged with the skip"); + Rescan(r); + Check.False(r.C.ScannedTargets.Any(t => (uint)t.Id == A), "the skipped Skulker is out of the scan"); + r.C.HandleCombatTrigger(); + Check.Eq((uint)r.C.activeTargetId, B, "the Slinker is fought next"); + + r.Now = r.Now.AddSeconds(31); + Rescan(r); + Check.True(r.C.ScannedTargets.Any(t => (uint)t.Id == A), "after the skip the Skulker is back"); + } + + /// The scan runs at most every 50 ms of real time (SCAN_INTERVAL_MS). + private static void Rescan(Rig r) + { + System.Threading.Thread.Sleep(60); + r.C.ScanNearbyTargets(); + } + + private static void MissileApproach() + { + // The Skulker is the only monster. + var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; s.EnvironmentApproachMeters = 6; s.EnvironmentMinDistance = 3; }, Skulker); + r.C.HandleChatForDamage(MissileLine); + r.C.HandleChatForDamage(MissileLine); + + Check.True(r.Run(), "New target with nothing else in reach: moves closer instead"); + Check.Eq((uint)r.C.activeTargetId, A, "the only monster is kept"); + Check.True(FakeHost.AutoRun, "running toward it"); + Check.True(r.C.EnvironmentApproachActive, "approach under way"); + Check.True(FakeHost.Logs.Any(l => l.Contains("moving closer") && l.Contains("stopping at 14.0m")), "goal: 6 m nearer"); + + r.Now = r.Now.AddMilliseconds(500); + r.MovePlayer(96, 99); // 17 m + Check.True(r.Run(), "still short of the goal: no attack"); + r.Now = r.Now.AddMilliseconds(500); + r.MovePlayer(96, 102.5f); // 13.5 m + Check.False(r.Run(), "reached: attacking again this tick"); + Check.False(FakeHost.AutoRun, "autorun off"); + Check.False(r.C.EnvironmentApproachActive, "approach over"); + + // Two more hits: already approached once, still far enough: Move closer goes again. + r.S.MissileEnvironmentResponse = 1; + r.C.HandleChatForDamage(MissileLine); + r.C.HandleChatForDamage(MissileLine); + Check.True(r.Run(), "Move closer trips again"); + Check.True(FakeHost.AutoRun, "running again"); + + // Blocked: no ground gained for 2.5 s. + r.Now = r.Now.AddSeconds(3); + Check.False(r.Run(), "no progress: the approach gives up and combat attacks"); + Check.False(FakeHost.AutoRun, "autorun off when blocked"); + Check.True(FakeHost.Logs.Any(l => l.Contains("ended: no progress")), "logged as blocked"); + + // At the closest distance with nothing else: keep attacking. + r.MovePlayer(96, 113.2f); // 2.8 m + r.C.HandleChatForDamage(MissileLine); + r.C.HandleChatForDamage(MissileLine); + Check.False(r.Run(), "already close and the only monster: attacking on"); + Check.Eq((uint)r.C.activeTargetId, A, "not dropped"); + } + + private static void MissileOff() + { + var off = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 0; s.EnvironmentImpactLimit = 1; }, Skulker); + off.C.HandleChatForDamage(MissileLine); + Check.False(off.Run(), "Off: nothing happens"); + Check.False(FakeHost.Logs.Any(l => l.Contains("[EnvImpact]")), "Off: not even counted"); + + var melee = new Rig(CombatMode.Melee, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 1; }, Skulker); + melee.C.HandleChatForDamage(MissileLine); + Check.False(melee.Run(), "not in Missile mode: ignored"); + } + + private static void MissileSpoof() + { + var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 1; }, Skulker); + r.C.HandleChatForDamage("Bob says, \"" + MissileLine + "\"", 2); + r.C.HandleChatForDamage(MissileLine, 3); // a tell, whatever its text + r.C.HandleChatForDamage("Bob " + MissileLine, 12); // an emote + r.C.HandleChatForDamage("[Allegiance] Bob says, \"" + MissileLine + "\""); // type unknown: the anchor + Check.False(r.Run(), "no spoofed line counts"); + Check.False(FakeHost.Logs.Any(l => l.Contains("[EnvImpact]")), "nothing recorded"); + + r.C.HandleChatForDamage(MissileLine, 0); // ACE's own line is a Broadcast + Check.True(r.Run(), "the server's line still trips the limit"); + } + + private static void MagicShort() + { + var r = new Rig(CombatMode.Magic, s => { s.MagicEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; }, Skulker, Slinker); + Check.Eq((uint)r.C.activeTargetId, A, "the Skulker is locked"); + + void Cast(float stopY, bool hitLine = false) => CastBolt(r, stopY, hitLine); + + Cast(105); + Check.True(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] magic") && l.Contains("1/2")), "a bolt stopping 9 m out, no hit: one environment hit"); + Cast(115); + Check.False(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] magic") && l.Contains("2/2")), "a bolt reaching the target: not counted"); + Cast(105, hitLine: true); + Check.False(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] magic") && l.Contains("2/2")), "a hit line for the cast: not counted"); + Cast(105); + Check.True(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] magic") && l.Contains("2/2")), "a second short bolt: the limit"); + Check.True(r.Run(), "the response runs"); + Check.Eq(r.C.activeTargetId, 0, "the Skulker is left for the Slinker"); + + // Rings and other casters' projectiles aren't ours to judge. + Check.False(CombatManager.IsWatchedProjectileName("Flame Ring"), "a ring isn't watched"); + Check.True(CombatManager.IsWatchedProjectileName("Nether Bolt"), "void bolts are"); + Check.False(CombatManager.IsWatchedProjectileName("Drudge Skulker"), "a monster isn't"); + } + + private static void ApproachOrphan() + { + var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 1; s.EnvironmentImpactLimit = 1; }, Skulker); + r.C.HandleChatForDamage(MissileLine); + Check.True(r.Run(), "approach starts"); + Check.True(FakeHost.AutoRun, "running"); + r.Now = r.Now.AddSeconds(2); // Think stopped calling (buffing took over) + r.C.PollEnvironmentImpact(); + Check.False(FakeHost.AutoRun, "the heartbeat lets go of autorun"); + Check.False(r.C.EnvironmentApproachActive, "approach over"); + + r.C.HandleChatForDamage(MissileLine); + Check.True(r.Run(), "a new approach"); + r.C.OnHeartbeat(); // a heartbeat sees the macro running + Check.True(FakeHost.AutoRun, "still running while Think drives it"); + r.S.IsMacroRunning = false; + r.C.OnHeartbeat(); + Check.False(FakeHost.AutoRun, "a macro stop ends it too"); + } + + // ── Attack power ───────────────────────────────────────────────────────── + + private static void Power() + { + float R(string mode, int global = -1, bool reck = false, bool trained = true, int min = 50, int max = 100, double rnd = 0.5) + => AttackPowerModes.Resolve(mode, global, reck, trained, min, max, () => rnd); + + Check.Near(R("Default"), 1.0, 1e-6, "Default, Auto, no Recklessness: 100%"); + Check.Near(R("Default", reck: true), 0.8, 1e-6, "Default, Auto + Use Recklessness, trained: 80%"); + Check.Near(R("Default", reck: true, trained: false), 1.0, 1e-6, "... untrained: 100%"); + Check.Near(R("Default", global: 65), 0.65, 1e-6, "Default, a set power: that power"); + Check.Near(R("High", global: 40), 1.0, 1e-6, "High: 100% whatever the global"); + Check.Near(R("Reckless"), 0.8, 1e-6, "Reckless: 80%"); + Check.Near(R("Reckless", trained: false), 1.0, 1e-6, "Reckless untrained: High"); + Check.Near(R("Variable", rnd: 0), 0.5, 1e-6, "Variable: the min"); + Check.Near(R("Variable", rnd: 0.999), 1.0, 1e-6, "Variable: up to the max"); + Check.Near(R("Variable", min: 90, max: 30, rnd: 0), 0.3, 1e-6, "Variable: a reversed range is put in order"); + Check.Near(R("Reckless + Variable", rnd: 0), 0.5, 1e-6, "Reckless + Variable: the Variable min (inside the band)"); + Check.Near(R("Reckless + Variable", rnd: 0.999), 0.8, 1e-6, "... capped at the band's 80%"); + Check.Near(R("Reckless + Variable", min: 85, max: 100, rnd: 0), 0.2, 1e-6, "no overlap with the band: the whole band"); + Check.Near(R("Reckless + Variable", trained: false, rnd: 0.999), 1.0, 1e-6, "untrained: plain Variable"); + var seen = new HashSet(); + foreach (double d in new[] { 0.1, 0.4, 0.7 }) seen.Add(R("Variable", rnd: d)); + Check.Eq(seen.Count, 3, "Variable changes with each draw"); + + Check.Eq(AttackPowerModes.Normalize("reckless+variable"), AttackPowerModes.RecklessVariable, "hand-typed spelling"); + Check.Eq(AttackPowerModes.Normalize(null), AttackPowerModes.Default, "missing: Default"); + Check.Eq(AttackPowerModes.Normalize("Huge"), AttackPowerModes.Default, "unknown: Default"); + var def = new MonsterRule { Name = "Default", AttackPower = "Reckless" }; + Check.Eq(AttackPowerModes.Effective(new MonsterRule { Name = "Drudge" }, def), "Reckless", "a Default rule follows the DEFAULT line"); + Check.Eq(AttackPowerModes.Effective(new MonsterRule { Name = "Drudge", AttackPower = "High" }, def), "High", "its own choice wins"); + Check.Eq(AttackPowerModes.Effective(null, null), "Default", "no rules: the global settings"); + Check.Eq(new MonsterRule().AttackPower, "Default", "a new rule (and an old file) is Default"); + + // Pull-away kite (2026-10-16): Default → DEFAULT row → Off on that row. + Check.Eq(KiteModes.Normalize("pull away"), KiteModes.PullAway, "hand-typed PullAway"); + Check.Eq(KiteModes.Normalize(null), KiteModes.Default, "missing kite: Default"); + var kiteDef = new MonsterRule { Name = "Default", Kite = KiteModes.PullAway }; + Check.Eq(KiteModes.Effective(new MonsterRule { Name = "Drudge" }, kiteDef), KiteModes.PullAway, "a Default rule follows the DEFAULT kite"); + Check.Eq(KiteModes.Effective(new MonsterRule { Name = "Drudge", Kite = KiteModes.Off }, kiteDef), KiteModes.Off, "its own kite wins"); + Check.Eq(KiteModes.Effective(kiteDef, kiteDef), KiteModes.PullAway, "DEFAULT row PullAway is PullAway"); + Check.Eq(KiteModes.Effective(new MonsterRule { Name = "Default" }, new MonsterRule { Name = "Default" }), KiteModes.Off, "DEFAULT Default means Off"); + Check.True(KiteModes.WantsPullAway(new MonsterRule { Name = "X" }, kiteDef), "WantsPullAway follows DEFAULT"); + Check.Eq(new MonsterRule().Kite, "Default", "a new rule (and an old file) is Default kite"); + } + + private static void PowerCarriedOver() + { + var current = new List + { + new() { Name = "Default", AttackPower = "High" }, + new() { Name = "Drudge", AttackPower = "Variable" }, + new() { Name = "Drudge", MatchExpression = "x", AttackPower = "Reckless" }, + }; + var incoming = new List + { + new() { Name = "Default" }, new() { Name = "drudge" }, new() { Name = "Drudge", MatchExpression = "x" }, new() { Name = "Mosswart" }, + }; + LegacyDashboardRenderer.CarryAttackPower(current, incoming); + Check.Eq(incoming[0].AttackPower, "High", "Default keeps its power"); + Check.Eq(incoming[1].AttackPower, "Variable", "matched by name, any case"); + Check.Eq(incoming[2].AttackPower, "Reckless", "and by expression"); + Check.Eq(incoming[3].AttackPower, "Default", "a new rule stays Default"); + } + + // ── Magic position re-sync (upstream 2026.10.12.1) and the throttle ────── + + private const uint StepRight = 0x6500000F, StepLeft = 0x65000010; + + /// Upstream's CastNoDamageTests.ResyncSidestep, on this file's rig. + private static void ResyncSidestep() + { + var r = new Rig(CombatMode.Magic, s => { }, setMotion: true, Skulker, Slinker); + var c = r.C; + c.TargetClock = () => r.Now; + MoveAudit.Reset(); + + c.MagicMissForTest(unchecked((int)A)); + c.MagicMissForTest(unchecked((int)B)); // a swap to the other monster doesn't reset the count + Check.False(c.ResyncActive, "two misses: nothing yet"); + c.ReportDamageOnTarget(unchecked((int)A)); + c.MagicMissForTest(unchecked((int)A)); + c.MagicMissForTest(unchecked((int)A)); + Check.False(c.ResyncActive, "a hit reset the count"); + c.MagicMissForTest(unchecked((int)A)); + Check.True(c.ResyncActive, "three in a row: a re-sync is wanted"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("one short sidestep to re-sync")), 1, "said once"); + + Check.True(c.TickResyncStep(), "first tick: the step starts, no cast"); + Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true) }), "sidestep right key down"); + r.Now = r.Now.AddMilliseconds(200); + Check.True(c.TickResyncStep(), "still stepping at 200 ms"); + r.Now = r.Now.AddMilliseconds(100); + Check.True(c.TickResyncStep(), "300 ms: key up, settling"); + Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true), (StepRight, false) }), "key up"); + r.Now = r.Now.AddMilliseconds(400); + Check.False(c.TickResyncStep(), "settled: casting may go on"); + Check.Eq(c.ResyncSteps, 1, "one step"); + + for (int i = 0; i < 3; i++) c.MagicMissForTest(unchecked((int)A)); + Check.False(c.ResyncActive, "within 30 s: no second step"); + r.Now = r.Now.AddSeconds(30); + for (int i = 0; i < 3; i++) c.MagicMissForTest(unchecked((int)A)); + Check.True(c.ResyncActive, "30 s later: another one"); + c.TickResyncStep(); + Check.True(FakeHost.MotionCalls[2] == (StepLeft, true), "the other side this time"); + } + + private static void ResyncCountResetByThrottle() + { + var r = new Rig(CombatMode.Magic, s => { s.MagicEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; }, setMotion: true, Skulker, Slinker); + r.C.TargetClock = () => r.Now; + r.C.MagicMissForTest(unchecked((int)A)); + r.C.MagicMissForTest(unchecked((int)A)); + CastBolt(r, 105); + CastBolt(r, 105); + Check.True(r.Run(), "two short bolts: the throttle switches target"); + Check.Eq(r.C.activeTargetId, 0, "the Skulker is left"); + + r.C.MagicMissForTest(unchecked((int)B)); + r.C.MagicMissForTest(unchecked((int)B)); + Check.False(r.C.ResyncActive, "the misses the wall explained no longer count toward a sidestep"); + r.C.MagicMissForTest(unchecked((int)B)); + Check.True(r.C.ResyncActive, "three fresh misses on the new target still ask for one"); + } + + private static void ResyncDroppedByApproach() + { + var r = new Rig(CombatMode.Magic, s => { s.MagicEnvironmentResponse = 1; s.EnvironmentImpactLimit = 1; }, setMotion: true, Skulker); + r.C.TargetClock = () => r.Now; + for (int i = 0; i < 3; i++) r.C.MagicMissForTest(unchecked((int)A)); + Check.True(r.C.ResyncActive, "a sidestep is wanted"); + + CastBolt(r, 105); + Check.True(r.Run(), "the throttle moves closer"); + Check.True(FakeHost.AutoRun, "running toward the Skulker"); + Check.False(r.C.ResyncActive, "the wanted sidestep is dropped: the run moves us anyway"); + Check.True(FakeHost.Logs.Any(l => l.Contains("re-sync sidestep dropped: moving closer")), "logged"); + Check.Eq(FakeHost.MotionCalls.Count, 0, "no sidestep key was sent"); + } + + private static void ResyncStepFinishesFirst() + { + var r = new Rig(CombatMode.Magic, s => { s.MagicEnvironmentResponse = 1; s.EnvironmentImpactLimit = 1; }, setMotion: true, Skulker); + r.C.TargetClock = () => r.Now; + for (int i = 0; i < 3; i++) r.C.MagicMissForTest(unchecked((int)A)); + CastBolt(r, 105); // the throttle trips (its response waits for Think) + Check.True(r.C.TickResyncStep(), "the sidestep key goes down"); + + Check.True(r.Run(), "the throttle's tick: no attack"); + Check.False(r.C.EnvironmentApproachActive, "but no run while the sidestep key is held"); + Check.False(FakeHost.AutoRun, "autorun not sent"); + + r.Now = r.Now.AddMilliseconds(300); + Check.True(r.C.TickResyncStep(), "the sidestep key comes up"); + Check.True(r.Run(), "now the approach runs"); + Check.True(r.C.EnvironmentApproachActive, "approach under way"); + Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true), (StepRight, false) }), "the key went up before the run"); + } + + private static void ResyncKeyReleased() + { + var r = new Rig(CombatMode.Magic, s => { }, setMotion: true, Skulker); + r.C.TargetClock = () => r.Now; + for (int i = 0; i < 3; i++) r.C.MagicMissForTest(unchecked((int)A)); + r.C.TickResyncStep(); + Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true) }), "key down"); + + r.Now = r.Now.AddSeconds(2); // Think stopped ticking it (left magic mode) + r.C.PollEnvironmentImpact(); + Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true), (StepRight, false) }), "the heartbeat lets go of the key"); + Check.False(r.C.ResyncActive, "the sidestep is over"); + Check.True(FakeHost.Logs.Any(l => l.Contains("re-sync sidestep stopped: combat stopped driving it")), "logged"); + + r.C.OnHeartbeat(); // a heartbeat sees the macro running + r.C.MagicMissForTest(unchecked((int)A)); + int before = FakeHost.MotionCalls.Count; + r.C.TickResyncStep(); + Check.True(FakeHost.MotionCalls.Count == before + 1 && FakeHost.MotionCalls[^1] == (StepLeft, true), "a new sidestep, key down"); + r.S.IsMacroRunning = false; + r.C.OnHeartbeat(); + Check.True(FakeHost.MotionCalls[^1] == (StepLeft, false), "a macro stop lets go of it too"); + Check.False(r.C.ResyncActive, "and ends it"); + } + + // ── Helpers ────────────────────────────────────────────────────────────── + + /// One cast at the active target whose bolt flies from the caster north to and stops. + private static void CastBolt(Rig r, float stopY, bool hitLine = false) + { + r.C.RegisterCastWatch(r.C.activeTargetId, "Flame Bolt VI"); + r.Now = r.Now.AddMilliseconds(800); // the windup + FakeHost.Names[Bolt] = "Flame Bolt"; + FakeHost.Positions[Bolt] = (Lb | 0x1C, 96f, 97f, 0f); // spawns at the caster + r.C.OnEnvironmentObjectCreated(Bolt); + r.C.PollEnvironmentImpact(); + for (float y = 99; y <= stopY; y += 2) + { + r.Now = r.Now.AddMilliseconds(100); + FakeHost.Positions[Bolt] = (Lb | 0x1C, 96f, y, 0f); + r.C.PollEnvironmentImpact(); + } + if (hitLine) r.C.HandleChatForDamage("You singe Drudge Skulker for 40 points of fire damage!"); + for (int i = 0; i < 15; i++) { r.Now = r.Now.AddMilliseconds(100); r.C.PollEnvironmentImpact(); } + r.C.OnObjectDeleted(Bolt); + FakeHost.Positions.Remove(Bolt); + } + + private static void Place(uint id, string name, float x, float y, bool creature = true) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f); + if (creature) FakeHost.ItemTypes[id] = 0x10; + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs index 8c117b5..7d89433 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs @@ -28,12 +28,36 @@ internal static class GiveTests 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); + r.Add("give: a whole stack to an NPC that takes one per give keeps giving until it is gone, one give per tick", NpcStackOneAtATime); + r.Add("give: the answer and the next give share one tick (the interval is only a minimum gap between sends)", NextGiveSameTick); + r.Add("give: busy refusals re-send with no cap", BusyResendsUncapped); + r.Add("give: a permanent refusal skips the stack at once and moves on", PermanentSkips); + r.Add("give: item not found after a re-send counts as given", ItemNotFoundAfterResendCounts); + r.Add("give: the summary counts items, not stacks", SummaryCountsItems); + r.Add("give: no answer at all re-sends once, then skips", NoAnswerSkips); + r.Add("give: an unreadable stack count is no information, not a shrink", UnreadableStackIsNotAShrink); + r.Add("give: an item unreadable for one tick is not gone; for two it is", OneTickUnreadableIsNotGone); + r.Add("give: speech lines never answer a give; item not found with the stack unchanged is a skip", SpeechIgnoredAndNotFoundNeedsGone); + r.Add("give: busy notice after 10 s, busy logging throttled, unclassified lines logged (max 10)", BusyNoticeAndLogThrottle); + r.Add("give: a counted give from one stack goes through the queue (NPC one per give, player split once)", CountedSingleStack); + r.Add("give: cancel in the middle of a busy wait stops everything", CancelMidBusy); + r.Add("give: an accept line does not shorten the two-tick rule for an unreadable item", AcceptLineDoesNotAbandon); + r.Add("give: a failed stack read on a stackable item sends nothing until it reads", FailedStackReadOnStackableWaits); + r.Add("give: a container we cannot place is unreadable, not gone", UnplaceableContainerIsUnreadable); + r.Add("give: a stack count that never reads holds the queue for 2 s, then the give goes out and the queue moves on", UnreadableStackFallsBackAfterTwoSeconds); + r.Add("give: an unreadable stack never turns a counted give into a whole-object give; only give-all goes out whole", UnreadableStackNeverGivesWholeForACount); + r.Add("give: a count-1 stackable whose count property is absent still gets through", CountOneStackableWithoutCountGetsThrough); + r.Add("give: /ub givea queues a give-all (0), so an unreadable count there sends the whole object", GiveAllQueuesWholeStack); + r.Add("give: a target that stays busy for a minute is skipped and counted", BusyGivesUpAfterAMinute); + r.Add("give: a no-answer re-send that could not go out still counts as a try", FailedResendCountsAsATry); } private sealed class World { public readonly RynthAiPlugin P = new(); public readonly LegacyUiSettings S = new() { GiveQueueIntervalMs = 0 }; + /// The queue's fake millisecond clock. + public long Now; public readonly WorldObjectCache Cache; public World() @@ -67,6 +91,7 @@ internal static class GiveTests Set("_playerId", Player); Set("_initialized", true); Set("_loginComplete", true); + Set("_giveClock", (Func)(() => Now)); foreach (uint id in new[] { Npc, Mote1, Mote2, Mote3, WornMote, Other }) Cache.OnCreateObject(id); Cache.Tick(); } @@ -82,6 +107,36 @@ internal static class GiveTests for (int i = 0; i < 20; i++) Call("DrainGiveQueue"); } + /// Advances the clock, then runs one tick of the give queue. + public void Tick(long advanceMs = 0) { Now += advanceMs; Call("DrainGiveQueue"); } + + public void Chat(string text, int chatType = 0) => Call("NoteGiveChat", text, chatType); + + /// Adds a carried stack the cache knows about. + public void AddStack(uint id, string name, int count) + { + FakeHost.Names[id] = name; + FakeHost.Containers[id] = Player; + FakeHost.ItemTypes[id] = 0x80; + FakeHost.Ints[(id, 12)] = count; // StackCount + Cache.OnCreateObject(id); + Cache.Tick(); + } + + /// An NPC with a Give emote: each give takes ONE item from the stack (ACE: acceptAll ? amount : 1). + public void NpcTakesOnePerGive() + { + FakeHost.GiveHandler = (item, target, amount) => + { + if (!FakeHost.Ints.TryGetValue((item, 12), out int n)) { FakeHost.Containers[item] = target; return; } // a single item goes whole + if (n <= 0) return; + FakeHost.Ints[(item, 12)] = n - 1; + if (n - 1 <= 0) FakeHost.Containers[item] = target; + }; + } + + public bool ChatHas(string part) => FakeHost.Chat.Any(c => c.Contains(part, StringComparison.Ordinal)); + public uint[] GivenItems => FakeHost.Gives.Select(g => g.Item).ToArray(); } @@ -135,4 +190,490 @@ internal static class GiveTests 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"); } + + private const uint Carapace = 0x80281301; + + // 2026-10-12: Olthoi Carapace stack of 100 to a Collector NPC: the server takes ONE per give, the + // stack stays in the pack, and the queue used to wait 3 s, re-send once and skip. + private static void NpcStackOneAtATime() + { + var w = new World(); + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + w.NpcTakesOnePerGive(); + w.Call("EnqueueGive", Carapace, Npc, 5); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "the first give goes out"); + for (int expected = 2; expected <= 5; expected++) + { + w.Tick(); // the stack shrank: the same item goes again, in this very tick + Check.Eq(FakeHost.Gives.Count, expected, $"give #{expected} sent on the tick that saw the shrink"); + } + Check.True(FakeHost.Gives.All(g => g.Item == Carapace && g.Target == Npc), "always the same stack, to the NPC"); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 5, "the stack is gone: nothing more is sent"); + Check.False(w.ChatHas("didn't take"), "never reported as not taken"); + } + + private static void NextGiveSameTick() + { + var w = new World(); + w.S.GiveQueueIntervalMs = 150; // a saved old default: only a minimum gap between SENDS + w.Run("/ub give Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 1, "one give out, the server not yet heard from at t=0"); + // The first landed at once in the fake. Less than the gap since the send: the next must wait. + w.Tick(100); + Check.Eq(FakeHost.Gives.Count, 1, "inside the minimum gap the next send waits"); + // A round trip longer than the gap: answer observed and the next give leaves in the same tick. + w.Tick(60); + Check.Eq(FakeHost.Gives.Count, 2, "answer seen and the next give sent on one tick"); + w.Tick(200); + Check.Eq(FakeHost.Gives.Count, 3, "and again for the third"); + } + + private static void BusyResendsUncapped() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + for (int busy = 1; busy <= 6; busy++) + { + int before = FakeHost.Gives.Count; + w.Chat("You're too busy!"); + w.Tick(100); + Check.Eq(FakeHost.Gives.Count, before, $"busy #{busy}: not re-sent before the short delay"); + w.Tick(300); + Check.Eq(FakeHost.Gives.Count, before + 1, $"busy #{busy}: re-sent after it"); + } + Check.False(w.ChatHas("didn't take"), "no cap: never skipped"); + FakeHost.GiveLands = true; + FakeHost.Containers[Mote1] = Npc; // finally taken + w.Tick(100); + Check.True(w.ChatHas("1 item(s) given"), "then it lands and counts"); + Check.Eq(FakeHost.Gives.Count, 7, "seven sends: the first plus six re-sends"); + } + + private static void PermanentSkips() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "first stack out"); + w.Chat("Town Crier is not accepting gifts right now."); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "refused for good: the next stack is sent on that same tick"); + Check.Eq(FakeHost.Gives[1].Item, Mote2, "the second stack, not a retry of the first"); + FakeHost.Containers[Mote2] = Npc; + w.Tick(); + Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "summary: one given, one skipped with its reason"); + } + + private static void ItemNotFoundAfterResendCounts() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + w.Tick(3001); // no answer: sent once more + Check.Eq(FakeHost.Gives.Count, 2, "re-sent after the confirm time"); + FakeHost.Containers[Mote1] = Npc; // the first send did land: the item is gone from the pack + w.Chat("Item not found!"); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "no third send"); + Check.True(w.ChatHas("1 item(s) given, 0 stack(s) skipped"), "the earlier send landed: counted as given, not skipped"); + } + + private static void SummaryCountsItems() + { + var w = new World(); + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + w.NpcTakesOnePerGive(); + w.Call("EnqueueGive", Carapace, Npc, 5); + w.Call("EnqueueGive", Mote1, Npc, 1); + for (int i = 0; i < 12; i++) w.Tick(50); + Check.True(w.ChatHas("Give queue complete: 6 item(s) given, 0 stack(s) skipped"), "5 carapaces + 1 mote = 6 items from 2 stacks"); + } + + private static void NoAnswerSkips() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + w.Tick(3001); + w.Tick(3001); + Check.Eq(FakeHost.Gives.Count, 2, "two tries, then it gives up"); + Check.True(w.ChatHas("didn't take"), "and says so"); + Check.True(w.ChatHas("1 stack(s) skipped"), "the summary counts it as skipped"); + } + + private static void UnreadableStackIsNotAShrink() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; // the server has not answered yet + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + w.Call("EnqueueGive", Carapace, Npc, 5); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "sent"); + FakeHost.Ints.Remove((Carapace, 12)); // the engine read fails for a tick + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "a failed read is not a shrink of 4: no second give while the first is in flight"); + FakeHost.Ints[(Carapace, 12)] = 5; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "read again, unchanged: still waiting"); + Check.False(w.ChatHas("item(s) given"), "nothing credited"); + FakeHost.Ints[(Carapace, 12)] = 4; // now a real shrink + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "a real shrink gives again"); + } + + private static void OneTickUnreadableIsNotGone() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + FakeHost.Containers[Mote1] = 0; // one unreadable tick + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "Container 0 for one tick is not gone"); + FakeHost.Containers[Mote1] = Player; + w.Tick(); + FakeHost.Containers[Mote1] = 0; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "the streak restarted after a good read"); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "unreadable on two ticks in a row: gone, the next stack goes"); + } + + private static void SpeechIgnoredAndNotFoundNeedsGone() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + w.Chat("Bob<\\Tell> says, \"Town Crier doesn't want that\"", 17); + w.Chat("Bob says, \"Town Crier doesn't want that\"", 0); // shape alone is enough + w.Chat("Bob tells you, \"not accepting gifts\"", 3); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "other players' words are no answer: still in flight, nothing skipped"); + Check.False(w.ChatHas("skipped"), "no summary yet"); + w.Tick(3001); // re-sent + w.Chat("Item not found!"); + w.Tick(); // the item is still carried, stack unchanged: a skip, not a delivery + Check.Eq(FakeHost.Gives.Count, 3, "item not found with the item still in the pack skips it; the next stack goes"); + FakeHost.Containers[Mote2] = Npc; + w.Tick(); + Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "one skipped as item not found, one given"); + } + + private static void BusyNoticeAndLogThrottle() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + w.Chat("You cast Inner Calm on yourself", 7); // magic lines never take a slot + for (int i = 0; i < 12; i++) w.Chat("Something odd " + i); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Give] unclassified chat:")), 10, "at most 10 unclassified lines logged per give"); + int busyCycles = 0; + long start = w.Now; + while (w.Now - start < 9000) + { + w.Chat("You're too busy!"); + w.Tick(0); + w.Tick(300); + busyCycles++; + } + Check.False(w.ChatHas("still retrying"), "no notice before 10 s of busy waiting"); + while (w.Now - start < 10700) + { + w.Chat("You're too busy!"); + w.Tick(0); + w.Tick(300); + busyCycles++; + } + Check.Eq(FakeHost.Chat.Count(c => c.Contains("Town Crier is busy - still retrying (/ra givea stop to cancel).")), 1, "one notice at about 10 s"); + int busyLogs = FakeHost.Logs.Count(l => l.Contains("Give answer: busy")); + Check.True(busyCycles >= 30 && busyLogs <= busyCycles / 10 + 1, $"busy logging throttled: {busyLogs} lines for {busyCycles} busy answers"); + Check.True(busyLogs >= 1, "the first busy is logged"); + } + + private static void CountedSingleStack() + { + var w = new World(); + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + w.NpcTakesOnePerGive(); + w.Run("/ub give 3 Olthoi Slayer Carapace to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 3, "3 of 5 to a one-per-give NPC: three gives"); + Check.Eq(FakeHost.Ints[(Carapace, 12)], 2, "two left in the pack"); + Check.Eq(FakeHost.Containers[Carapace], Player, "the stack stays"); + + var w2 = new World(); + const uint Friend = 0x50000F02; + FakeHost.Names[Friend] = "Friend"; + FakeHost.Positions[Friend] = (0x1048002Au, 101f, 101f, 0f); + FakeHost.ItemTypes[Friend] = 0x10; + w2.Cache.OnCreateObject(Friend); + w2.Cache.Tick(); + w2.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + FakeHost.GiveHandler = (item, target, amount) => + { + FakeHost.Ints[(item, 12)] -= amount == 0 ? FakeHost.Ints[(item, 12)] : amount; // a player takes what is asked + }; + w2.Run("/ub give 3 Olthoi Slayer Carapace to Friend"); + Check.Eq(FakeHost.Gives.Count, 1, "to a player: one give"); + Check.Eq(FakeHost.Gives[0].Amount, 3, "carrying the count (the server splits)"); + Check.Eq(FakeHost.Ints[(Carapace, 12)], 2, "two left"); + } + + private static void CancelMidBusy() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + w.Chat("You're too busy!"); + w.Tick(100); // busy seen, re-send armed + w.Call("CancelGiveQueue"); + for (int i = 0; i < 20; i++) w.Tick(500); + Check.Eq(FakeHost.Gives.Count, 1, "nothing is sent after the cancel: no re-send, no next stack"); + Check.True(w.ChatHas("Give queue cancelled"), "cancel reported"); + } + + private static void AcceptLineDoesNotAbandon() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + w.Chat("You give Town Crier Mana Mote."); + FakeHost.Containers[Mote1] = 0; // one unreadable tick + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "an accept line plus one unreadable tick does not abandon the stack"); + FakeHost.Containers[Mote1] = Player; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "read again, still carried"); + } + + private static void FailedStackReadOnStackableWaits() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100; + FakeHost.Ints.Remove((Carapace, 12)); // the stack read fails + w.Call("EnqueueGive", Carapace, Npc, 1); + w.Tick(); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 0, "a stackable item with an unreadable stack is not sent (amount 1 would hand over the whole stack)"); + FakeHost.Ints[(Carapace, 12)] = 5; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "sent on the first tick that reads it"); + Check.Eq(FakeHost.Gives[0].Amount, 1, "one item, not the whole object"); + } + + private static void UnplaceableContainerIsUnreadable() + { + const uint Pack = 0x80281F01, Stranger = 0x80281F02; + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + // In a side pack that itself reads as inside the player's pack: carried. + FakeHost.Containers[Pack] = Player; + FakeHost.Containers[Mote1] = Pack; + w.Tick(); w.Tick(); w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "a pack the player carries: still carried"); + // In a container whose own container reads 0: unreadable, needs two ticks. + FakeHost.Containers.Remove(Stranger); + FakeHost.Containers[Mote1] = Stranger; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "one tick of an unplaceable container is not gone"); + FakeHost.Containers[Mote1] = Pack; + w.Tick(); + FakeHost.Containers[Mote1] = Stranger; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "the streak restarts after a good read"); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "two unreadable ticks in a row: gone"); + } + + // Review of PR 18: a stackable item whose StackCount read stayed absent made SendGive return false on + // every tick, for ever, with nothing logged and nothing behind it in the queue ever sent. + private static void UnreadableStackFallsBackAfterTwoSeconds() + { + var w = new World(); + w.Now = 1000; + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100; + FakeHost.Ints.Remove((Carapace, 12)); // the stack read never succeeds + FakeHost.GiveHandler = (item, target, _) => FakeHost.Containers[item] = target; // the server takes it + w.Call("EnqueueGive", Carapace, Npc, 0); // a genuine give-all + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + w.Tick(1500); + Check.Eq(FakeHost.Gives.Count, 0, "inside the 2 s the unreadable stack still waits"); + w.Tick(600); // 2.1 s after the first failed read + Check.Eq(FakeHost.Gives.Count, 1, "after 2 s the give goes out anyway"); + Check.Eq(FakeHost.Gives[0].Item, Carapace, "the stack that would not read"); + Check.Eq(FakeHost.Gives[0].Amount, 0, "as a plain give (it was a give-all)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("unreadable for", StringComparison.Ordinal)), "and the log says why"); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "the queue moved on to the next item"); + Check.Eq(FakeHost.Gives[1].Item, Mote1, "the one behind it"); + + // A counted give keeps its explicit amount. + var w2 = new World(); + w2.Now = 1000; + w2.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100; + FakeHost.Ints.Remove((Carapace, 12)); + FakeHost.GiveHandler = (_, _, _) => { }; + w2.Call("EnqueueGive", Carapace, Npc, 3); + w2.Tick(); + w2.Tick(2001); + Check.Eq(FakeHost.Gives.Count, 1, "a counted give goes out after 2 s too"); + Check.Eq(FakeHost.Gives[0].Amount, 3, "with its explicit amount"); + } + + // Review of PR 18 (follow-up): after the 2 s fallback, an amount of 1 used to go out as a plain give, which hands + // over the WHOLE object: a "give 1" of a stack that is really 99 would have sent all 99. + private static void UnreadableStackNeverGivesWholeForACount() + { + var w = new World(); + w.Now = 1000; + w.AddStack(Carapace, "Olthoi Slayer Carapace", 99); + FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100; + FakeHost.Ints.Remove((Carapace, 12)); // really 99, but the count will not read + int sent = 0; + FakeHost.GiveHandler = (_, _, amount) => sent += amount; // the server hands over what is asked + w.Call("EnqueueGive", Carapace, Npc, 1); + w.Tick(); + w.Tick(1500); + Check.Eq(FakeHost.Gives.Count, 0, "still waiting inside 2 s"); + w.Tick(600); + Check.Eq(FakeHost.Gives.Count, 1, "after 2 s the give goes out"); + Check.Eq(FakeHost.Gives[0].Amount, 1, "as an explicit 1, never as a whole-object give (0)"); + Check.Eq(sent, 1, "one item reached the target, not the stack"); + + // A re-send (no answer) keeps the explicit amount too. + w.Tick(3001); + Check.Eq(FakeHost.Gives.Count, 2, "no answer: re-sent"); + Check.Eq(FakeHost.Gives[1].Amount, 1, "the re-send is still an explicit 1"); + + // A stackable the cache has no MaxStackSize for (unknown, so no wait): the explicit count still goes out as asked. + var w2 = new World(); + w2.AddStack(Carapace, "Olthoi Slayer Carapace", 99); + FakeHost.Ints.Remove((Carapace, 12)); + FakeHost.GiveHandler = (_, _, _) => { }; + w2.Call("EnqueueGive", Carapace, Npc, 1); + w2.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "unknown MaxStackSize: no wait"); + Check.Eq(FakeHost.Gives[0].Amount, 1, "and an explicit 1"); + + // A give-all with the count unreadable is the one that goes out whole, and a re-send of it stays whole. + var w3 = new World(); + w3.Now = 1000; + w3.AddStack(Carapace, "Olthoi Slayer Carapace", 99); + FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100; + FakeHost.Ints.Remove((Carapace, 12)); + FakeHost.GiveHandler = (_, _, _) => { }; + w3.Call("EnqueueGive", Carapace, Npc, 0); + w3.Tick(); + w3.Tick(2001); + Check.Eq(FakeHost.Gives.Count, 1, "give-all: out after 2 s"); + Check.Eq(FakeHost.Gives[0].Amount, 0, "as a whole-object give"); + w3.Tick(3001); + Check.Eq(FakeHost.Gives.Count, 2, "no answer: re-sent"); + Check.Eq(FakeHost.Gives[1].Amount, 0, "still a give-all, not an explicit 1"); + } + + private static void CountOneStackableWithoutCountGetsThrough() + { + var w = new World(); + w.Now = 1000; + w.AddStack(Carapace, "Olthoi Slayer Carapace", 1); + FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100; + FakeHost.Ints.Remove((Carapace, 12)); // a stack of one: the property is simply absent + FakeHost.GiveHandler = (item, target, _) => FakeHost.Containers[item] = target; // the server takes it + w.Call("EnqueueGive", Carapace, Npc, 1); + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + w.Tick(2100); + Check.Eq(FakeHost.Gives.Count, 1, "the lone stackable goes out after the read wait"); + Check.Eq(FakeHost.Gives[0].Item, Carapace, "it is the stack that would not read"); + Check.Eq(FakeHost.Gives[0].Amount, 1, "as an explicit 1"); + w.Tick(); w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "it left the pack: counted given, the queue moved on"); + Check.False(w.ChatHas("didn't take"), "and nothing was skipped"); + } + + private static void GiveAllQueuesWholeStack() + { + var w = new World(); + w.AddStack(Carapace, "Olthoi Slayer Carapace", 7); + FakeHost.GiveHandler = (item, target, _) => FakeHost.Containers[item] = target; + w.Run("/ub give Olthoi Slayer Carapace to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 1, "one give"); + Check.Eq(FakeHost.Gives[0].Amount, 0, "the whole stack"); + } + + // Review of PR 18: a target that is never free (a player in a trade) was re-sent every 300 ms for ever, + // printing the server's "too busy" line in that player's chat about three times a second. + private static void BusyGivesUpAfterAMinute() + { + var w = new World(); + w.Now = 1000; + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + long start = w.Now; + int guard = 0; + while (FakeHost.Gives.Count(g => g.Item == Mote2) == 0 && guard++ < 1000) + { + w.Chat("You're too busy!"); + w.Tick(0); + w.Tick(300); + } + long waited = w.Now - start; + Check.True(FakeHost.Gives.Any(g => g.Item == Mote2), "after the cap the next stack is sent"); + Check.True(waited >= 59000 && waited <= 61500, $"given up after about a minute of busy, not before ({waited} ms)"); + Check.True(FakeHost.Gives.Count(g => g.Item == Mote1) <= 210, "the first stack was not re-sent past the cap"); + Check.True(w.ChatHas("stayed busy"), "the player is told"); + FakeHost.Containers[Mote2] = Npc; + w.Tick(); + Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "the summary counts the busy skip"); + Check.True(w.ChatHas("busy too long"), "with its reason"); + } + + // Review of PR 18: when the no-answer re-send could not go out (unreadable stack) the try was not + // counted, so GiveMaxTries + 1 sends could happen. + private static void FailedResendCountsAsATry() + { + var w = new World(); + w.Now = 1000; + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100; + FakeHost.GiveHandler = (_, _, _) => { }; // never answers + w.Call("EnqueueGive", Carapace, Npc, 5); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "sent"); + FakeHost.Ints.Remove((Carapace, 12)); // the read fails when the re-send is due + w.Tick(3001); + Check.Eq(FakeHost.Gives.Count, 1, "the re-send could not go out"); + FakeHost.Ints[(Carapace, 12)] = 5; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "it goes out on the next tick that reads"); + w.Tick(3001); + Check.Eq(FakeHost.Gives.Count, 2, "two tries in all (GiveMaxTries), then it gives up"); + Check.True(w.ChatHas("didn't take"), "and says so"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs index cbd78c1..6d90919 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs @@ -12,7 +12,7 @@ namespace RynthCore.RynthAiHostTests.Tests; // HP failsafe: under Emergency Heal At with heals failing (here: every heal sent and never answered, // as in a client log's hung casts), the character must not sit and die. 3 rounds of 2.5 s with no // rise: a forced jump (ActionPacer.ForceBreak), then healing again; 3 more: the macro stops and -// "/lifestone" goes out (HpFailsafeRecall, default on). +// "/lifestone" goes out (HpFailsafeRecall, default off; the tests turn it on). internal static class HpFailsafeTests { private const uint Player = 0x50000B31; @@ -30,6 +30,10 @@ internal static class HpFailsafeTests r.Add("hp failsafe: a death drops the pending recall (0 health, and the plugin's death hold): no /lifestone, the macro stays off", DeathDropsRecall); r.Add("hp failsafe: a failed recall does not switch the macro back on past a VTank yield", VTankYieldRespected); r.Add("hp failsafe: our name unreadable: the recall line is taken as ours, and that is logged once", RecallNameUnreadable); + r.Add("hp failsafe: HP Failsafe Recall is off by default; a profile with no saved value loads off, one that saved true keeps it", RecallOffByDefault); + r.Add("hp failsafe: a character that cannot heal at all (no spell, kit or potion) never jumps or recalls", NoHealCapabilityNeverFires); + r.Add("hp failsafe: a character that can heal (a known Heal Self) and is stuck still jumps, then recalls when the option is on", CapableStuckStillRecalls); + r.Add("hp failsafe: a heal that went out proves the character can heal (a listed potion, no spell)", PotionSentProvesCapability); r.Add("vitals (L8):a heal the server leaves unanswered is not re-sent at the 2.5 s give-up after a 'too busy' answer", VitalResendObeysLatch); r.Add("vitals: under Emergency Heal At with a weapon out and no usable kit, a health potion before Heal Self's wand swap", EmergencyPotionBeforeWandSwap); r.Add("low components: tapers at 10, a scarab at 2 (not Diamond), kinds never carried ignored, a kind run out still counts", LowComponentsRule); @@ -132,7 +136,7 @@ internal static class HpFailsafeTests public readonly RynthCore.PluginSdk.RynthCoreHost Host; public int MacroStops; - public Rig(int healthPct = 20) + public Rig(int healthPct = 20, bool canHeal = true, bool recall = true) { FakeHost.Reset(); FakeHost.WeaponCalls = true; @@ -143,14 +147,24 @@ internal static class HpFailsafeTests FakeHost.Names[Player] = "Mira"; FakeHost.PlayerPose = (0x6347028Au, 100f, 100f, 0f); FakeHost.Positions[Player] = FakeHost.PlayerPose; - foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); - FakeHost.Skills[(Player, STypeLife)] = (400, 2); + if (canHeal) + { + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + } + else + { + // A warm spellbook that holds no heal (an empty one reads as "not loaded yet"). + FakeHost.Spellbook.Add((uint)SpellTable.Rows.First(row => !row.Name.Contains("Heal", StringComparison.OrdinalIgnoreCase) + && !row.Name.Contains("Health", StringComparison.OrdinalIgnoreCase)).Id); + } var host = Host = FakeHost.Create(Player); S = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 30, StaminaToHealthAt = 0, GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false, SpellCastIntervalMs = 100, + HpFailsafeRecall = recall, // off by default now; most tests here are about the recall }; var skills = new CharacterSkills(host); skills.SetPlayerId(Player); @@ -202,6 +216,113 @@ internal static class HpFailsafeTests MoveAudit.NowMs = () => Environment.TickCount64; } + private static void CopySettings(LegacyUiSettings src, LegacyUiSettings dst) => + typeof(RynthCore.Plugin.RynthAi.LegacyUi.LegacyDashboardRenderer).GetMethod("CopySettings", + System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)! + .Invoke(null, new object[] { src, dst }); + + private static void RecallOffByDefault() + { + Check.False(new LegacyUiSettings().HpFailsafeRecall, "a new settings object has the recall off"); + var ctx = RynthAiJsonContext.Default.LegacyUiSettings; + // A profile with no saved value for it: off. + var node = System.Text.Json.Nodes.JsonNode.Parse(System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings(), ctx))!.AsObject(); + Check.True(node.Remove("HpFailsafeRecall"), "the key is a serialized setting"); + var noKey = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!; + var live = new LegacyUiSettings { HpFailsafeRecall = true }; + CopySettings(noKey, live); + Check.False(live.HpFailsafeRecall, "no saved value: the recall loads off"); + // A profile that saved true (the owner turned it on, or the earlier default was saved): kept. + node["HpFailsafeRecall"] = true; + var saved = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!; + var live2 = new LegacyUiSettings(); + CopySettings(saved, live2); + Check.True(live2.HpFailsafeRecall, "a saved true stays on"); + } + + // A melee character with nothing to heal with (no spell, kit or potion), resting or out-healed at + // low health, must not be jumped around and sent to the lifestone: there is nothing to retry. + private static void NoHealCapabilityNeverFires() + { + try + { + var r = new Rig(healthPct: 20, canHeal: false); + r.Run(0, 40); + Check.Eq(FakeHost.Casts.Count, 0, "nothing to cast with"); + Check.Eq(FakeHost.TapJumps, 0, "no failsafe jump"); + Check.Eq(r.B.HpFailsafeBreaks, 0, "nothing counted"); + Check.Eq(FakeHost.ChatCommands.Count, 0, "no /lifestone"); + Check.Eq(r.B.HpFailsafeRecalls, 0, "no recall"); + Check.True(r.S.IsMacroRunning, "the macro keeps running"); + + // Life Magic trained but no Heal Self known, and a potion listed with Use Potions off: still nothing. + const uint Potion = 0x80001234; + var p = new Rig(healthPct: 20, canHeal: false); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + FakeHost.Names[Potion] = "Healing Elixir"; + p.S.UsePotions = false; + p.S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Potion), Name = "Healing Elixir", Type = "HealthPotion" }); + var cache = new WorldObjectCache(p.Host); + cache.SetPlayerId(Player); + cache.OnCreateObject(Player); + _ = cache[unchecked((int)Potion)]; + cache.Tick(); + p.B.SetWorldObjectCache(cache); + p.Run(0, 40); + Check.Eq(FakeHost.TapJumps, 0, "no spell known, potions off: no jump"); + Check.Eq(FakeHost.ChatCommands.Count, 0, "and no recall"); + Check.True(p.S.IsMacroRunning, "the macro keeps running"); + } + finally { Done(); } + } + + // The gate does not switch the failsafe off for a character that can heal: stuck heals still break, then recall. + private static void CapableStuckStillRecalls() + { + try + { + var r = new Rig(healthPct: 20, canHeal: true, recall: true); + r.Run(0, 15.0); + Check.Eq(FakeHost.TapJumps, 1, "capable + stuck: the jump"); + Check.False(r.S.IsMacroRunning, "capable + stuck + recall on: the macro stops"); + r.Run(15.1, 16.0); + Check.Eq(FakeHost.ChatCommands.Count, 1, "and /lifestone goes out"); + + // The option off (the default): the jump only, the macro keeps running. + var d = new Rig(healthPct: 20, canHeal: true, recall: false); + d.Run(0, 30.0); + Check.Eq(FakeHost.TapJumps, 1, "recall off: the jump still"); + Check.True(d.S.IsMacroRunning, "recall off: no stop"); + Check.Eq(FakeHost.ChatCommands.Count, 0, "recall off: no /lifestone"); + } + finally { Done(); } + } + + // No spell, but a listed health potion with Use Potions on: the potion goes out (a heal sent), so + // the failsafe can arm when the potion does not raise health. + private static void PotionSentProvesCapability() + { + const uint Potion = 0x80001234; + try + { + var r = new Rig(healthPct: 20, canHeal: false); + FakeHost.Names[Potion] = "Healing Elixir"; + r.S.UsePotions = true; + r.S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Potion), Name = "Healing Elixir", Type = "HealthPotion" }); + var cache = new WorldObjectCache(r.Host); + cache.SetPlayerId(Player); + cache.OnCreateObject(Player); + _ = cache[unchecked((int)Potion)]; + cache.Tick(); + r.B.SetWorldObjectCache(cache); + r.Run(0, 15.0); + Check.True(FakeHost.Uses.Contains(Potion), "the potion is drunk"); + Check.Eq(FakeHost.TapJumps, 1, "it did not raise health: the failsafe jump"); + Check.False(r.S.IsMacroRunning, "and the recall stage"); + } + finally { Done(); } + } + private static void BreakThenRecall() { try diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/IdRefusalTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/IdRefusalTests.cs new file mode 100644 index 0000000..6215e94 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/IdRefusalTests.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The engine refuses RequestId around a death or a portal (it returns false). A caller that marks an item +// "already asked" before the call, or counts the refusal as an attempt, never asks again; these callers +// record the request only when the engine took it. +internal static class IdRefusalTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("id refusal: the worn-gear appraisal asks again after the engine refused, and once it is taken", EquipmentAppraisalRetried); + r.Add("id refusal: the weapon identify pump does not count a refused request", WeaponPumpRetried); + } + + private static void EquipmentAppraisalRetried() + { + const uint Player = 0x50000F01, Helm = 0x80000A01; + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // wires RequestId / HasAppraisalData + FakeHost.PlayerIdValue = Player; + FakeHost.Names[Helm] = "Helm"; + FakeHost.Containers[Helm] = Player; + FakeHost.ItemTypes[Helm] = 0x2; + var host = FakeHost.Create(playerId: Player); + var plugin = new RynthAiPlugin(); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi }); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + typeof(RynthAiPlugin).GetField("_objectCache", Any)!.SetValue(plugin, cache); + cache.OnCreateObject(Helm); + cache.Tick(); + var equip = new List<(string Name, uint Id, int Slot)> { ("Helm", Helm, 1) }; + void Pass() => typeof(RynthAiPlugin).GetMethod("AppraiseEquipment", Any)!.Invoke(plugin, new object[] { equip }); + + FakeHost.RequestIdAccepts = false; // a portal in progress + Pass(); + Check.True(FakeHost.RefusedIdRequests >= 1, "the engine refused the first request"); + Check.Eq(FakeHost.IdRequests.Count, 0, "so nothing went out"); + FakeHost.RequestIdAccepts = true; + Pass(); + Check.Eq(FakeHost.IdRequests.Count(i => i == Helm), 1, "the next pass asked again and it was taken"); + Pass(); + Check.Eq(FakeHost.IdRequests.Count(i => i == Helm), 1, "a taken request is not repeated"); + } + + private static void WeaponPumpRetried() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + var host = FakeHost.Create(); + DateTime t = new(2026, 10, 18, 12, 0, 0); + var tr = new WeaponElementTracker(host, () => t); + int[] ids = { 0x60000051 }; + + FakeHost.RequestIdAccepts = false; + Check.Eq(tr.Pump(ids), 0, "refused: nothing asked for"); + Check.Eq(tr.RequestsSent, 0, "and not counted"); + FakeHost.RequestIdAccepts = true; + t = t.AddMilliseconds(500); + Check.Eq(tr.Pump(ids), 0, "inside the gap the retry is paced"); + t = t.AddMilliseconds(2000); + Check.Eq(tr.Pump(ids), ids[0], "after the gap it is asked again"); + t = t.AddMilliseconds(5100); + Check.Eq(tr.Pump(ids), ids[0], "unanswered: the second (and last) ask still available, the refusal cost none"); + t = t.AddMilliseconds(5100); + Check.Eq(tr.Pump(ids), 0, "at most twice per weapon"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/IgnoreMonsterTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/IgnoreMonsterTests.cs index 0101f16..7b1b158 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/IgnoreMonsterTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/IgnoreMonsterTests.cs @@ -21,6 +21,7 @@ internal static class IgnoreMonsterTests public static void Register(Runner r) { + r.Add("monster ignore: a profile with a Priority 0 row logs and says in chat what Priority 0 means now, once", PriorityZeroIsAnnounced); r.Add("monster ignore: a Priority 0 monster is never targeted", NotTargeted); r.Add("monster ignore: a Priority 0 monster holds nothing up (nav, combat, close-threat gates)", HoldsNothingUp); r.Add("monster ignore: the kill-shot swap does not count a Priority 0 monster as an alternate", KillShotAlternate); @@ -28,6 +29,41 @@ internal static class IgnoreMonsterTests r.Add("monster ignore: Priority 1, no rule and the Default row behave as before", UnchangedForOtherPriorities); } + // -- 0. the owner is told what Priority 0 means now ----------------------- + + private static int Notices() => FakeHost.Logs.Count(l => l.Contains("Priority 0 now means")); + + private static void PriorityZeroIsAnnounced() + { + var c = World(GrubIgnored(), out var ids, (Grub, 3f)); + var s = (LegacyUiSettings)typeof(CombatManager).GetField("_settings", Any)!.GetValue(c)!; + s.IsMacroRunning = true; + c.OnHeartbeat(); // the macro runs: the first check + c.OnHeartbeat(); + c.NotePriorityZeroRules(); + Check.Eq(Notices(), 1, "one log line for the profile's Priority 0 row, however often it is checked"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Priority 0 now means") && l.Contains("never attacked or tracked") && l.Contains(Grub)), "it says what it means and names the row"); + Check.Eq(FakeHost.Chat.Count(l => l.Contains("Priority 0 now means")), 1, "and one chat notice"); + Check.False(Scanned(c, ids[0]), "behavior unchanged: the Priority 0 monster is still never scanned"); + + // Another profile loads with the same Priority 0 rule: nothing new to say. + s.MonsterRules = GrubIgnored(); + c.NotePriorityZeroRules(); + Check.Eq(Notices(), 1, "the same Priority 0 set again: not repeated"); + // A different Priority 0 row: said again. + s.MonsterRules = new() { new MonsterRule { Name = "Default", Priority = 1 }, new MonsterRule { Name = Soldier, Priority = 0 } }; + c.NotePriorityZeroRules(); + Check.Eq(Notices(), 2, "a different set of Priority 0 rows: said again"); + + // No Priority 0 row: silent. + var none = World(new() { new MonsterRule { Name = "Default", Priority = 1 }, new MonsterRule { Name = Grub, Priority = 2 } }, out _, (Grub, 3f)); + none.NotePriorityZeroRules(); + Check.Eq(Notices(), 0, "no Priority 0 row: no notice"); + var noRules = World(null, out _, (Grub, 3f)); + noRules.NotePriorityZeroRules(); + Check.Eq(Notices(), 0, "default rules: no notice"); + } + private static uint _next; private static void Place(uint id, string name, float north) diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs index f56e441..141e278 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs @@ -40,6 +40,7 @@ internal static class MiniRemoteMoveTests r.Add("mini remote: without RynthILT there are no ILT tabs, bits or verbs", NoRynthIlt); r.Add("mini remote: /ra hub|quests|pets stay RynthAi's; quest windows point to RynthOracle; ILT verbs say RynthILT is needed", Commands); r.Add("mini remote: the pyreal refill path never spends without RynthILT's confirmation", RefillNeedsIlt); + r.Add("vaulted dungeons: the master switch is off by default, saved with the profile, and an older engine's save leaves it alone", VaultedMasterSwitch); r.Add("profile: the old Server Features fields still round-trip (RynthILT migrates them)", LegacyProfileFields); r.Add("RynthAi.Hub: table, spell names, nothing before login", HubTable); } @@ -177,6 +178,39 @@ internal static class MiniRemoteMoveTests Check.False(fresh.Contains("InfiniteLeaftide"), "a fresh profile no longer gets an ILT server list"); } + /// + /// "Vaulted Dungeons" (Settings > Navigation) is RynthILT's keeper's master switch and lives only in + /// RynthAi's profile: off for a new or older profile, round-tripped through the settings bridge, and + /// an engine that predates the row (it sends no such field) never flips it. + /// + private static void VaultedMasterSwitch() + { + Check.False(new LegacyUiSettings().EnableVaultedDungeons, "off by default"); + var oldProfile = JsonSerializer.Deserialize("{\"BoostNavPriority\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!; + Check.False(oldProfile.EnableVaultedDungeons, "a profile saved before the switch existed has it off"); + + var on = new LegacyUiSettings { EnableVaultedDungeons = true }; + string json = JsonSerializer.Serialize(on, RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!.EnableVaultedDungeons, "saved with the profile"); + + var s = new LegacyUiSettings(); + var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + var flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance; + typeof(LegacyDashboardRenderer).GetField("_settings", flags)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", flags)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); + + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!; + Check.True(sent.EnableVaultedDungeons == false, "the Settings face is sent the switch (off)"); + dash.ApplySettingsJson("{\"EnableVaultedDungeons\":true}"); + Check.True(s.EnableVaultedDungeons, "the Settings checkbox turns it on"); + dash.ApplySettingsJson("{\"NavRingThickness\":6}"); + Check.True(s.EnableVaultedDungeons, "an older engine's save (no such field) leaves it on"); + dash.ApplySettingsJson("{\"EnableVaultedDungeons\":false}"); + Check.False(s.EnableVaultedDungeons, "the checkbox turns it off"); + dash.ApplySettingsJson("{\"NavRingThickness\":6}"); + Check.False(s.EnableVaultedDungeons, "and an older engine's save leaves it off"); + } + private static unsafe void HubTable() { Check.Eq(HubInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "not ours"); @@ -193,6 +227,8 @@ internal static class MiniRemoteMoveTests QuestStatusV1 st; Check.Eq(t->QuestStatus(&st), 0, "no quest tracker before login"); Check.Eq(t->MiniRemoteVisible(), 0, "no Mini Remote before login"); + Check.True(t->VaultedDungeonsEnabled != null, "the Vaulted Dungeons master switch is served"); + Check.Eq(t->VaultedDungeonsEnabled(), 0, "the master switch is off before login (and by default)"); SessionStatsV1 ss; Check.Eq(t->SessionStats(&ss), 0, "no session before login"); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MissileCraftingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MissileCraftingTests.cs new file mode 100644 index 0000000..5ef3b3b --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MissileCraftingTests.cs @@ -0,0 +1,182 @@ +using System; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Silentkelpie, 2026-10-15: with Missile Crafting on, combat swapped Electric Bow + arrows for +// Fire Crossbow + quarrels, and crafting kept wielding 'Infinite Deadly Prismatic Arrow' every +// 5 s (784 tries in one session). The stowed bow still read wielded (the client keeps a stowed +// item's old wielder and slot), the crossbow in hand read slot 0, the server ignored each arrow +// wield, and every try stopped the nav route while it waited. +internal static class MissileCraftingTests +{ + private const uint Player = 0x50000C01; + private const uint Crossbow = 0x80000601, Bow = 0x80000602, Quarrels = 0x80000603, Arrows = 0x80000604; + private const int MissileSlot = 0x00400000, AmmoSlot = 0x00800000; + + public static void Register(Runner r) + { + r.Add("missile crafting: a stowed bow that still reads wielded is not the launcher (no arrows at a crossbow)", StowedBowNotLauncher); + r.Add("missile crafting: wielded quarrels are not taken for a bow launcher", AmmoNotLauncher); + r.Add("missile crafting: an ammo wield the server ignores backs off after 2 tries", IgnoredWieldBacksOff); + r.Add("missile crafting: a bow in hand with its arrows in the pack still gets them wielded", BowInHandArrowsInPack); + } + + /// Kelpie's state at 13:36: crossbow and quarrels in hand (slot 0), bow and arrows in the main pack. + private static void StowedBowNotLauncher() + { + var cm = Rig(crossbowInHand: true); + Idle(cm); + Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "crossbow with quarrels on: nothing to do"); + Check.Eq(FakeHost.Uses.Count, 0, "no arrow wield"); + Check.False(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no")), "no evaluation logged"); + } + + /// The quarrels wielded at login (slot set, typed MissileWeapon) and no launcher readable. + private static void AmmoNotLauncher() + { + var cm = Rig(crossbowInHand: false, arrange: () => + { + FakeHost.Containers.Remove(Bow); // no bow anywhere + FakeHost.Wielded.Remove(Bow); + FakeHost.Containers.Remove(Quarrels); // the quarrels on, the crossbow in the pack + FakeHost.Wielded[Quarrels] = AmmoSlot; + }); + Idle(cm); + Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "no launcher: crafting idles"); + Check.Eq(FakeHost.Uses.Count, 0, "the quarrels never pass for a bow"); + } + + /// Bow in hand, arrows in the pack, and the server never puts them on. + private static void IgnoredWieldBacksOff() + { + var cm = BowRig(); + for (int i = 0; i < 4; i++) Cycle(cm); + Check.Eq(FakeHost.Uses.Count(u => u == Arrows), 2, "two arrow wields, then no more"); + Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "crafting let go"); + Check.True(FakeHost.Logs.Any(l => l.Contains("didn't wield") && l.Contains("2 tries")), "the back-off is logged"); + + Cycle(cm); + Check.Eq(FakeHost.Uses.Count(u => u == Arrows), 2, "inside the back-off: still two"); + } + + /// The fix must not stop crafting doing its job: no ammo on, the pack's arrows go on. + private static void BowInHandArrowsInPack() + { + var cm = BowRig(); + Cycle(cm); + Check.Eq(FakeHost.Uses.LastOrDefault(), Arrows, "UseObject(arrows)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no Arrow") && l.Contains("'Longbow'")), "the launcher it saw is logged"); + } + + // ── The rig ───────────────────────────────────────────────────────────── + + private static WorldObjectCache? _cache; + + /// Changes to the fake world, made before the host and cache read it. + private static MissileCraftingManager Rig(bool crossbowInHand, Action? arrange = null) + { + PaceOff(); + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // UseObject, GetCurrentCombatMode + FakeHost.SalvageCalls = true; // GetObjectWielderInfo (answers from Wielded) + FakeHost.Names[Player] = "Silentkelpie"; + Item(Crossbow, "Fire Crossbow", MissileSlot); + Item(Bow, "Electric Bow", MissileSlot); + Item(Quarrels, "Infinite Deadly Prismatic Quarrel", AmmoSlot); + Item(Arrows, "Infinite Deadly Prismatic Arrow", AmmoSlot); + + // The pack listing holds only what is in the pack; the stowed bow's description still + // names the player and the missile slot. + FakeHost.Containers[Bow] = Player; + FakeHost.Containers[Arrows] = Player; + FakeHost.Wielded[Bow] = MissileSlot; + if (crossbowInHand) + { + FakeHost.Wielded[Crossbow] = 0; // wielded after login: slot reads 0 + FakeHost.Wielded[Quarrels] = 0; + } + else + { + FakeHost.Containers[Crossbow] = Player; + FakeHost.Containers[Quarrels] = Player; + } + arrange?.Invoke(); + + var host = FakeHost.Create(Player); + _cache = FakeHost.MakeCache(host, Player, new[] { Crossbow, Bow, Quarrels, Arrows }); + var cm = new MissileCraftingManager(host, new LegacyUiSettings { EnableMissileCrafting = true }); + cm.SetObjectCache(_cache); + return cm; + } + + /// A real bow in hand (slot set) with nothing in the ammo slot and arrows in the pack. + private static MissileCraftingManager BowRig() => Rig(crossbowInHand: false, arrange: () => + { + FakeHost.Containers.Remove(Bow); + FakeHost.Names[Bow] = "Longbow"; + }); + + private static void Item(uint id, string name, int validSlots) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = 0x100; // MissileWeapon, as the server types ammo too + FakeHost.Ints[(id, 9)] = validSlots; + } + + private static readonly FieldInfo LastAmmoCheck = + typeof(MissileCraftingManager).GetField("_lastAmmoCheck", BindingFlags.Instance | BindingFlags.NonPublic)!; + private static readonly FieldInfo PhaseStart = + typeof(MissileCraftingManager).GetField("_phaseStart", BindingFlags.Instance | BindingFlags.NonPublic)!; + + /// One idle tick with the 5 s ammo-check interval already passed. + private static void Idle(MissileCraftingManager cm) + { + LastAmmoCheck.SetValue(cm, DateTime.MinValue); + ForceRescan(); + cm.ProcessCrafting(); + } + + /// One ammo check through to its wield (or its back-off), the clocks moved past each wait. + private static void Cycle(MissileCraftingManager cm) + { + for (int i = 0; i < 4 && (i == 0 || cm.State != MissileCraftingManager.CraftState.Idle); i++) + { + if (cm.State == MissileCraftingManager.CraftState.Idle) + { + // The back-off moves _lastAmmoCheck into the future; only an expired check is reset. + if ((DateTime)LastAmmoCheck.GetValue(cm)! <= DateTime.Now) + LastAmmoCheck.SetValue(cm, DateTime.MinValue); + } + else + { + PhaseStart.SetValue(cm, DateTime.Now.AddSeconds(-1)); // past EQUIP_DELAY_MS + } + ForceRescan(); + cm.ProcessCrafting(); + } + } + + /// GetDirectInventory re-serves a scan under 1 s old; the test can't wait on the wall clock. + private static void ForceRescan() => + typeof(WorldObjectCache).GetField("_lastDirectInventoryScan", BindingFlags.Instance | BindingFlags.NonPublic)! + .SetValue(_cache, DateTime.MinValue); + + 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; + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs index b87f5fb..0fe6df4 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs @@ -45,6 +45,7 @@ internal static class MonsterEditorTests GravityWell = true, Imperil = true, Yield = true, Vuln = true, UseArc = true, UseRing = true, UseStreak = true, UseBolt = false, UseBlast = true, UseWall = true, ExVuln = "Fire", OffhandId = 2, PetDamage = "Cold", CustomDebuffs = "Corrosion Vulnerability Other, Fire Vulnerability Other VII", + Kite = "PullAway", }, new PluginRule { Name = "", Category = "Expression only", MatchExpression = "wobjectfindnearestbytemplatetype[1]" }, }; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs index af6384f..4d5f09e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using System.Text.RegularExpressions; using RynthCore.Plugin.RynthAi; using RynthCore.Plugin.RynthAi.LegacyUi; @@ -71,6 +72,7 @@ internal static class NavEngineTests r.Add("nav engine: a Linear index past the end carries on from that end", LinearIndexOffEnd); // was a known failure; fixed by 91178c1 r.Add("nav engine: a chat point that loads another route hands over to it", ChatLoadsRoute); // was a known failure; fixed by a8e5de0 r.Add("nav engine: a recall that never fires, next waypoint far: stops instead of walking off", RecallTimeoutFar); // was a known failure; fixed by 5cfbcea + r.Add("nav engine: a portal/NPC use the engine did not send is not logged as sent and is asked again", PortalNpcUseNotSent); } // ── Rig ─────────────────────────────────────────────────────────────────── @@ -342,6 +344,34 @@ internal static class NavEngineTests Check.True(nav.S.EnableNavigation, "nav still on"); } + private static void PortalNpcUseNotSent() + { + FakeHost.Reset(); At(0, 0); + FakeHost.WeaponCalls = true; // UseObject + const uint Npc = 0x7A000001, Me = 0x50000F01; + var pose = FakeHost.PlayerPose; + FakeHost.Names[Me] = "Tester"; + FakeHost.Positions[Me] = pose; + FakeHost.Names[Npc] = "Gateway"; + FakeHost.Positions[Npc] = (pose.Cell, pose.X + 1f, pose.Y, pose.Z); + var host = FakeHost.Create(Me); + var cache = FakeHost.MakeCache(host, Me, new[] { Npc }); + var nav = new Nav(Route(RT.Once, Pt(10, 0), Pt(20, 0))); + nav.E.SetWorldObjectCache(cache); + nav.E.SetPlayerId(Me); + var fire = typeof(NavigationEngine).GetMethod("FirePortalNpcUse", BindingFlags.Instance | BindingFlags.NonPublic)!; + var point = new NavPoint { Type = T.PortalNPC, TargetName = "Gateway" }; + + FakeHost.UseObjectAccepts = false; + Check.False((bool)fire.Invoke(nav.E, new object[] { point })!, "the engine did not send the use: not fired, the caller asks again"); + Check.Eq(LogCount("UseObject portal 'Gateway' (dist="), 0, "and no 'used' line is logged"); + Check.Eq(LogCount("was not sent - will retry"), 1, "the refusal is logged"); + + FakeHost.UseObjectAccepts = true; + Check.True((bool)fire.Invoke(nav.E, new object[] { point })!, "once the engine sends it the portal counts as fired"); + Check.Eq(LogCount("UseObject portal 'Gateway' (dist="), 1, "and the 'used' line is logged"); + } + private static void RecallTimeoutNear() { var nav = RecallRoute(30); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs index bf707c5..8bf62a5 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs @@ -31,6 +31,35 @@ internal static class NavOverlayTests 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); + r.Add("nav overlay: Settings > Navigation shows the Nav panel's Breadcrumbs and Route overlay switches", SettingsLinksNavPanelSwitches); + } + + /// + /// Settings > Navigation carries the Nav panel's two switches (NavOverlay.TrackBreadcrumbs and + /// ShowRouteMarkers), so either place changes the same setting. An engine that predates them + /// sends neither, and its save must leave them alone. + /// + private static void SettingsLinksNavPanelSwitches() + { + var s = new LegacyUiSettings(); + s.NavOverlay.TrackBreadcrumbs = false; + s.NavOverlay.ShowRouteMarkers = true; + var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + var flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance; + typeof(LegacyDashboardRenderer).GetField("_settings", flags)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", flags)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); + + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!; + Check.True(sent.TrackBreadcrumbs == false, "Breadcrumbs sent to the Settings face (off)"); + Check.True(sent.ShowRouteOverlay == true, "Route overlay sent to the Settings face (on)"); + + dash.ApplySettingsJson("{\"TrackBreadcrumbs\":true,\"ShowRouteOverlay\":false}"); + Check.True(s.NavOverlay.TrackBreadcrumbs, "Settings turns Breadcrumbs on (the Nav panel's switch)"); + Check.False(s.NavOverlay.ShowRouteMarkers, "Settings turns Route overlay off (the Nav panel's switch)"); + + dash.ApplySettingsJson("{\"NavRingThickness\":6}"); + Check.True(s.NavOverlay.TrackBreadcrumbs, "an older engine's save leaves Breadcrumbs alone"); + Check.False(s.NavOverlay.ShowRouteMarkers, "an older engine's save leaves Route overlay alone"); } // ── Rig ───────────────────────────────────────────────────────────── diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs index 5e76e37..d0e3650 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs @@ -23,6 +23,7 @@ internal static class PetRefillTests private const uint Mob = 0x80300010; private const uint Essence = 0x80300001; private const uint Spirit = 0x80300002; + private const uint Essence2 = 0x80300003; // a second essence, only for the assume-window test private const uint StructureKey = 92; // AcIntProperty.Structure private const uint Lb = 0xA9B40000; @@ -38,6 +39,8 @@ internal static class PetRefillTests 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); + r.Add("pets: a landed summon whose pet is not in the cache yet holds a second essence back for the 10 s window", LandedSummonHoldsWindow); + r.Add("pets: failed summon (no charge drop) does not assume a pet; waits the 45 s essence cooldown", FailedSummonRespectsCooldown); } // ── Rig ─────────────────────────────────────────────────────────────── @@ -48,7 +51,7 @@ internal static class PetRefillTests public readonly LegacyUiSettings S = new() { SummonPets = true, MonsterRange = 20, CustomPetRange = 5, PetAutoRefill = true }; public readonly PetManager Pets; - public Rig(int charges) + public Rig(int charges, bool secondEssence = false) { FakeHost.Reset(); FakeHost.WeaponCalls = true; // UseObject (summon), RequestId (re-identify) @@ -61,11 +64,19 @@ internal static class PetRefillTests FakeHost.Names[Spirit] = "Encapsulated Spirit"; FakeHost.Containers[Spirit] = Player; SetCharges(charges); + if (secondEssence) + { + FakeHost.Names[Essence2] = "Frost Moar Essence (50)"; + FakeHost.Containers[Essence2] = Player; + FakeHost.Ints[(Essence2, StructureKey)] = 50; + } var host = FakeHost.Create(Player); - var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Essence, Spirit }); + var cache = FakeHost.MakeCache(host, Player, secondEssence ? new[] { Mob, Essence, Spirit, Essence2 } : new[] { Mob, Essence, Spirit }); S.IsMacroRunning = true; S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence), Name = "Fire Moar Essence (50)", Type = "Pet" }); + if (secondEssence) + S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence2), Name = "Frost Moar Essence (50)", Type = "Pet" }); var combat = new CombatManager(host, S, cache); combat.SetPlayerId(Player); combat.ScanNearbyTargets(); @@ -101,6 +112,7 @@ internal static class PetRefillTests public int Refills => FakeHost.UsesOn.Count(u => u.Source == Spirit && u.Target == Essence); public int Summons => FakeHost.Uses.Count(u => u == Essence); + public int AllSummons => FakeHost.Uses.Count(u => u == Essence || u == Essence2); public void Dispose() => PetManager.Clock = static () => Environment.TickCount64; } @@ -191,8 +203,49 @@ internal static class PetRefillTests 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. + // parks the essence for the 45 s PetDevice cooldown. After 30 minutes the trust is gone. rig.Run(31 * 60_000); Check.True(rig.Refills > refills, "after 30 minutes the empty read is believed again"); } + + /// + /// Kelpie 2026-10-16: Use refused (cooldown / environment) leaves Structure unchanged. + /// Must not assume a pet is out, and must wait the full ~45 s essence cooldown before retry. + /// + private static void FailedSummonRespectsCooldown() + { + using var rig = new Rig(charges: 50); + rig.Run(1500); + Check.Eq(rig.Summons, 1, "first Use fired"); + // Structure never drops and no pet appears → timeout treats it as a failed Use. + Rig.SetCharges(50); + rig.Run(9_000); + Check.Eq(rig.Summons, 1, "still one Use during the 45 s cooldown (no false re-issue)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("failed Use", StringComparison.OrdinalIgnoreCase) + || l.Contains("no charge drop", StringComparison.OrdinalIgnoreCase)), + "failed Use is logged"); + // Park is from IssueSummon (~t=100 ms), not from the 8 s timeout. At ~44 s from start + // still cooling; a few seconds more clears the 45 s essence cooldown. + rig.Run(34_000); + Check.Eq(rig.Summons, 1, "still cooling at ~44 s from first Use"); + rig.Run(4_000); + Check.Eq(rig.Summons, 2, "second Use after the 45 s essence cooldown"); + } + + /// + /// The charge dropped (the Use landed) but the pet is not in the landscape cache yet: the assume + /// window must keep a second essence from being summoned beside it, and lapse after 10 s. + /// + private static void LandedSummonHoldsWindow() + { + using var rig = new Rig(charges: 50, secondEssence: true); + rig.Run(1500); + Check.Eq(rig.AllSummons, 1, "first Use fired"); + Rig.SetCharges(49); + FakeHost.Ints[(Essence2, StructureKey)] = 49; // whichever essence it was, its charge dropped + rig.Run(8_000); + Check.Eq(rig.AllSummons, 1, "inside the 10 s window the other essence is not used"); + rig.Run(5_000); + Check.Eq(rig.AllSummons, 2, "window over and still no pet: the other essence is used"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ProfileLoadTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ProfileLoadTests.cs index cb94cdf..9fbd779 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ProfileLoadTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ProfileLoadTests.cs @@ -28,6 +28,10 @@ internal static class ProfileLoadTests r.Add("profile: every saved setting survives loading (CopySettings lists each serialized field)", EverySavedFieldIsCopied); r.Add("profile: Describe Items and the Item Info options survive a save and a reload", ItemInfoSurvivesReload); r.Add("profile: a profile with null item info / nav overlay loads defaults, not null", NullNestedOptionsLoadDefaults); + r.Add("profile: a save is atomic (temp file swapped in, no temp left) and keeps the previous profile as .bak", SaveKeepsBackup); + r.Add("profile: a profile that doesn't read loads the .bak, sets the broken file aside and puts the backup back", UnreadableLoadsBackup); + r.Add("profile: a profile that doesn't read and has no backup is kept, not overwritten by defaults until a setting changes", UnreadableKeptNotOverwritten); + r.Add("profile: switching to a profile that doesn't read keeps it (backup used when there is one)", SwitchUnreadableKept); } /// LegacyDashboardRenderer.CopySettings(src, dst): what LoadSettings / SwitchProfile run. @@ -169,4 +173,161 @@ internal static class ProfileLoadTests CopySettings(edited, live2); Check.Eq(live2.ItemInfoSettings.Prefix.Length, 32, "prefix trimmed to 32"); } + + // ── Settings no longer reset after a bad read (2026-10-17, Silentkelpie's design) ────────────── + // Saving used File.WriteAllText, which empties the profile first: a client killed mid-save left an + // empty / cut-off file, the load swallowed the failed read, kept defaults and the autosave wrote + // them over the profile. Saves now swap a temp file in and keep the previous one as .json.bak; + // a profile that doesn't read loads the .bak, else is set aside as .unreadable-