diff --git a/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs b/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs index ba3938e..ce40e1a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs @@ -77,12 +77,20 @@ internal readonly struct ArbiterInputs /// looting Boost Nav Priority still lets through (it is the player's own ask). /// public readonly bool ForcedLoot; + /// + /// The death wait (2026-11-08, RynthAiPlugin.DeathWait.cs): our kill's corpse is on its way (the + /// death animation) or being looted. Looting outranks combat as with Boost Loot Priority, except + /// while engaged (a monster on you is fought), so nothing walks off before the corpse is looted. + /// + public readonly bool DeathWait; public ArbiterInputs(bool macroRunning, bool wantBuffing, bool wantCombat, bool wantLooting, bool wantSalvaging, bool wantNav, bool combatEngaged = false, bool boostNav = false, bool boostLoot = false, - bool followActive = false, bool lootStarved = false, bool forcedLoot = false) + bool followActive = false, bool lootStarved = false, bool forcedLoot = false, + bool deathWait = false) { + DeathWait = deathWait; ForcedLoot = forcedLoot; MacroRunning = macroRunning; WantBuffing = wantBuffing; @@ -146,6 +154,9 @@ internal sealed class ActivityArbiter // clause instead. if (s.BoostLoot && s.WantLooting && !s.CombatEngaged) return BotActivity.Looting; + // The death wait: the kill's corpse first, on the same terms (2026-11-08). + if (s.DeathWait && s.WantLooting && !s.CombatEngaged) return BotActivity.Looting; + // Loot starvation: a corpse waited too long behind combat and nothing is close. if (s.LootStarved && s.WantLooting) return BotActivity.Looting; diff --git a/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs b/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs index 11d7476..8104495 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs @@ -202,7 +202,7 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings var pts = DungeonPathfinder.BuildPathPoints(cells, blk.Graph, blk.Geo, null, DungeonGeometry.WorldToNav(from.Y), DungeonGeometry.WorldToNav(from.X), from.Z, - DungeonGeometry.WorldToNav(to.Y), DungeonGeometry.WorldToNav(to.X), to.Z, out _); + DungeonGeometry.WorldToNav(to.Y), DungeonGeometry.WorldToNav(to.X), to.Z, out _, mergeSamePieces: false); var way = new List(pts.Count + 2) { from }; foreach (var p in pts) way.Add(new Vec(DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS), p.Z * 240.0, p.Doorway)); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealHold.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealHold.cs new file mode 100644 index 0000000..31d3cfc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealHold.cs @@ -0,0 +1,133 @@ +// ============================================================================ +// RynthSuite - Combat/BuffManager.HealHold.cs +// The Buffing hold for a heal, capped when no heal is landing. +// +// Health under a heal line wins the arbiter by itself (WantsVitalRecharge, ahead of combat and +// nav). That is right while heals land, and wrong when none does: a melee character with a shield +// went to Buffing at 48% health, stopped attacking the boss, and stood there 17 s re-sending a +// healing kit the server no longer had until it died. Nothing healed, and nothing fought either. +// +// VirindiTank's give-up for one kit: re-sent until the heal motion starts, given up after 3 s, +// then up to 3 s for its result. So: HealHoldGiveUpMs (6 s) under a heal line with no heal landing +// (health up FailsafeRiseMinPct, the HP failsafe's own test) hands combat the tick for +// HealHoldReleaseMs (5 s, HealUnavailableMs, the backoff after "nothing could heal"), then the +// vitals hold it again. A heal landing, or health back over the line, ends the episode. Only in a +// fight (InCombatNow): with no monster in range there is nothing for combat to do with the tick. +// +// The vitals step still runs every tick meanwhile (OnHeartbeat runs whatever the arbiter decides): +// kits and potions keep going. What it does not do while combat has the tick is change stance or +// wield for a heal (a wand swap for Heal Self, peace mode for a kit, in any stance): combat would +// take the weapon back on its next tick and the two would trade the hands for nothing. A caster +// already in Magic stance casts as before. The cast in flight (PendingSpellId) still holds the +// arbiter by itself. +// +// The safety floor is untouched: the kit despite Kit Min Success (AttemptHealChain's last resort) +// still goes, in the stance the character is in, and the HP failsafe's recall casts with the macro +// off, where this hold is reset and never applies. +// +// Every start and end of a release, and the first stance change it refuses in each release, is +// logged with "heal hold" in the line. +// ============================================================================ + +using System; + +namespace RynthCore.Plugin.RynthAi; + +public partial class BuffManager +{ + internal const double HealHoldGiveUpMs = 6000; + internal const double HealHoldReleaseMs = 5000; + + private DateTime _hhSince = DateTime.MinValue; + private int _hhLow; + private DateTime _hhReleasedUntil = DateTime.MinValue; + // Set for one CheckVitals while combat has the tick and the character is out of Magic stance. + private bool _vitalsNoStanceChange; + // Set for one CheckVitals while combat has the tick, in any stance: a kit sends no peace switch. + private bool _vitalsNoPeaceSwitch; + // What the current release already logged refusing (one line per kind per release). + private bool _hhSwapRefusedLogged, _hhPeaceRefusedLogged; + + /// Times the hold was handed to combat (tests, status). + internal int HealHoldReleases { get; private set; } + + /// True while combat has the tick because no heal has been landing (see the header). + internal bool HealHoldReleased => _hhReleasedUntil != DateTime.MinValue && Now < _hhReleasedUntil; + + /// + /// A heal already under way that a release would starve: a kit in flight whose heal motion has + /// played (NoteKitProgress), or the wand swap for a heal spell in flight (TickWandSwap's state, or + /// the wand's wield sent and not answered). + /// + private bool HealUnderWay() => + (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue && _kitSawAnimating) + || _wandSwap.Active || _pendingWieldId != 0; + + /// Ends a hold episode: the next heal line starts a fresh HealHoldGiveUpMs count. + private void ResetHealHold(string why) + { + if (_hhReleasedUntil != DateTime.MinValue && Now < _hhReleasedUntil) + _host.Log($"[RynthAi] Vitals: heal hold ended ({why}): the vitals hold the tick again."); + _hhSince = DateTime.MinValue; + _hhReleasedUntil = DateTime.MinValue; + } + + /// The vitals step refused a stance change because combat has the tick (logged once per release). + private void NoteHealHoldRefusal(bool peace, string what) + { + if (peace ? _hhPeaceRefusedLogged : _hhSwapRefusedLogged) return; + if (peace) _hhPeaceRefusedLogged = true; else _hhSwapRefusedLogged = true; + _host.Log($"[RynthAi] Vitals: heal hold: no {(peace ? "peace switch" : "wand swap")} for {what} while combat has the tick " + + $"({(_hhReleasedUntil - Now).TotalSeconds:0.#} s left)."); + } + + /// Once per heartbeat while the macro runs, before the vitals step. + private void TickHealHold() + { + DateTime now = Now; + int hp = _vitals.HealthPct; + // Only in a fight (a monster within Monster Range): with nothing to fight, handing the tick on + // would give it to nav or looting at low health, walking on into the next pull. + // The macro being off is handled by the caller: HeartbeatCore returns before this tick then, and + // calls ResetHealHold instead, so a restart in a fight starts a fresh count. + if (_vitals.MaxHealth == 0 || Portaling()) { ResetHealHold("portal space or no vitals"); return; } + if (!HealthUnderAnyLine(hp, _vitals.StaminaPct)) { ResetHealHold($"health {hp}% is over the heal lines"); return; } + if (!InCombatNow()) { ResetHealHold("no monster within Monster Range"); return; } + if (_hhSince == DateTime.MinValue) + { + _hhSince = now; + _hhLow = hp; + return; + } + if (hp >= _hhLow + FailsafeRiseMinPct) + { + // A heal landed: the heals work, the vitals hold the tick again and the count starts over. + if (HealHoldReleased) + _host.Log($"[RynthAi] Vitals: heal hold ended (a heal landed, {_hhLow}% -> {hp}%): the vitals hold the tick again."); + _hhSince = now; + _hhLow = hp; + _hhReleasedUntil = DateTime.MinValue; + return; + } + if (hp < _hhLow) _hhLow = hp; + if (_hhReleasedUntil != DateTime.MinValue) + { + if (now < _hhReleasedUntil) return; + // The window is over: hold again, and count the next HealHoldGiveUpMs from here. + _host.Log($"[RynthAi] Vitals: heal hold ended (its {HealHoldReleaseMs / 1000:0} s are over, health {hp}%): the vitals hold the tick again."); + _hhReleasedUntil = DateTime.MinValue; + _hhSince = now; + return; + } + double heldMs = (now - _hhSince).TotalMilliseconds; + if (heldMs < HealHoldGiveUpMs) return; + // A heal the server is playing is not cut off: combat would re-stance or re-wield over it. The + // release waits for it (a removed kit never animates, so that case still releases). + if (HealUnderWay()) return; + _hhReleasedUntil = now.AddMilliseconds(HealHoldReleaseMs); + _hhSwapRefusedLogged = _hhPeaceRefusedLogged = false; + HealHoldReleases++; + _host.Log($"[RynthAi] Vitals: heal hold started: health {hp}% under a heal line and no heal landed in {heldMs / 1000:0.#} s: " + + $"combat gets the tick for {HealHoldReleaseMs / 1000:0} s (kits and potions keep going; no stance change for a heal)."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs index 84168f0..2c15821 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs @@ -238,7 +238,7 @@ public partial class BuffManager foreach (var r in _settings.ConsumableRules) if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase) && !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase) - && ConsumableLookup.Resolve(_worldObjectCache, r) is WorldObject wo && IsUseOnSelfKit(wo)) { capable = true; break; } + && ConsumableLookup.Resolve(_worldObjectCache, r, KitUsedUp) is WorldObject wo && IsUseOnSelfKit(wo)) { capable = true; break; } } if (!capable && _settings.UsePotions && HasListedPotion("HealthPotion")) capable = true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.KitUsedUp.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.KitUsedUp.cs new file mode 100644 index 0000000..c707ea9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.KitUsedUp.cs @@ -0,0 +1,75 @@ +// ============================================================================ +// RynthSuite - Combat/BuffManager.KitUsedUp.cs +// A kit its own result line says is used up is not picked again. +// +// A kit's last use ends "... Your Treated Healing Kit is used up." (ACE Healer.DoHealing), and the +// server removes the kit. A use of an item the player no longer has is answered with a bare UseDone +// and no chat, so no heal lands: a used-up kit picked again is a heal lost. +// +// Kit picks read the client's live pack walk (ConsumableLookup.Resolve, BestPackHealingKit, +// BestPackStaminaKit: WorldObjectCache.GetDirectInventory), which drops a removed kit, but a walk is +// reused for up to a second (DirectInventoryCooldownMs) and the next kit goes out KitLandGraceMs +// (700 ms) after the line, inside that reuse. An engine without GetContainerContents has no walk at +// all: its inventory view is the object cache, which can keep a removed kit for good. +// +// So: the line names the kit in flight -> every kit pick skips that kit. With the live walk the skip +// lasts UsedUpKitSkipMs, long enough for a fresh walk to have dropped it; without the walk it lasts +// for the session (the server deleted the object, and its id never comes back). Only a line naming +// the kit in flight counts: a late line from a kit whose wait ended can land while the next kit is +// out, and must not mark that one. Kit use itself is unchanged. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +public partial class BuffManager +{ + /// How long a kit its result line called used up is skipped while the live pack walk runs + /// (the walk's 1 s reuse, with margin). Without the walk the skip does not end. + internal const double UsedUpKitSkipMs = 3000; + + // The kit in flight (its id and name), from the use until the next one. + private int _kitInFlightId; + private string _kitInFlightName = ""; + // Kits called used up by their result line, and until when kit picks skip each. + private readonly Dictionary _usedUpKitUntil = new(); + + /// Kits skipped because their result line said they are used up (tests, status). + internal int KitsUsedUp { get; private set; } + + /// Records which kit went out (AttemptHealthKitUse, AttemptStaminaKitUse). + private void NoteKitInFlight(WorldObject kit) + { + _kitInFlightId = kit.Id; + _kitInFlightName = kit.Name ?? ""; + } + + /// True while is a kit its result line called used up (see the header). + internal bool KitUsedUp(int id) + { + if (id == 0 || !_usedUpKitUntil.TryGetValue(id, out DateTime until)) return false; + if (until > Now) return true; + _usedUpKitUntil.Remove(id); + return false; + } + + /// A kit result line arrived (OnChatWindowText): an "is used up" line naming the kit in flight marks it. + private void NoteKitResultLine(string text, string lower) + { + if (!lower.Contains(" is used up", StringComparison.Ordinal) || _kitInFlightId == 0) return; + if (_kitInFlightName.Length > 0 && lower.Contains(_kitInFlightName.ToLowerInvariant(), StringComparison.Ordinal)) + { + bool walk = _host.HasGetContainerContents; + _usedUpKitUntil[_kitInFlightId] = walk ? Now.AddMilliseconds(UsedUpKitSkipMs) : DateTime.MaxValue; + KitsUsedUp++; + _host.Log($"[RynthAi] Vitals: kit 0x{(uint)_kitInFlightId:X8} '{_kitInFlightName}' is used up (its result line): " + + (walk ? $"kit picks skip it for {UsedUpKitSkipMs / 1000:0} s, until the pack walk has dropped it." + : "kit picks skip it from now on (no pack walk on this engine).")); + } + else + _host.Log($"[RynthAi] Vitals: an 'is used up' line that doesn't name the kit in flight " + + $"(0x{(uint)_kitInFlightId:X8} '{_kitInFlightName}') ignored: \"{text}\""); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs index 4e896a5..d0338c9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs @@ -23,6 +23,8 @@ namespace RynthCore.Plugin.RynthAi; /// default) turns it off. /// * When: on the armor's rules (Rebuff With, Also Refresh Under in a batch, Force Rebuff), on the /// shield's own timers, recorded from the "You cast X on <shield>" line. +/// * A shield marked "No buff" in the Items list (ItemRule.KeepBuffed off) is treated as an +/// unlisted one: nothing is aimed at it, and it never makes buffing due. /// * Never at a shield being moved (its pack move or wield not settled, a swap under way). /// * A cast at the shield that gets no answer twice in a row, or that the server says can't be /// cast on it, stops shield buffing for ShieldParkTime; the armor is never held up by it. @@ -49,6 +51,13 @@ public partial class BuffManager internal const int ShieldNoShowsToPark = 2; internal static readonly TimeSpan ShieldParkTime = TimeSpan.FromMinutes(30); + // Shields the server said take no spells ("Brogard's Defiance cannot be cast on Covenant Shield.", + // ACE IsInvalidTarget): never buffed again, kept in bufftimers.txt (2026-11-08, Tom: "if an item + // is deemed unbuffable it should just skip it altogether"; it was only parked for 30 min, so a + // Covenant Shield was tried again every half hour). /ra buffs unbuffable [clear] lists or forgets them. + private readonly Dictionary _unbuffableShields = new(); + internal IReadOnlyDictionary UnbuffableShields => _unbuffableShields; + // The off-hand item buffing's wand swap put into a pack (combat puts it back on), and when. // Seen in the off hand again after StowedSightingGraceMs, it is forgotten: the next time it is // in a pack, something else put it there. @@ -57,13 +66,15 @@ public partial class BuffManager private const double StowedSightingGraceMs = 10000; // ShieldToBuff walks the inventory: its answer is kept ShieldReadMs (the arbiter asks every tick), - // and worked out again at once when the Items list or the cache changes. Tests set ShieldReadMs 0. + // and worked out again at once when the Items list or the cache changes, or an entry's "No buff" + // is flipped in place (ExcludedSignature). Tests set ShieldReadMs 0. internal long ShieldReadMs = 1000; private int _shieldChoice; private string _shieldChoiceWhy = ""; private long _shieldChoiceAt = long.MinValue / 2; private List? _shieldChoiceRules; private int _shieldChoiceRuleCount; + private long _shieldChoiceExcluded; private WorldObjectCache? _shieldChoiceCache; private string _shieldChoiceLogged = ""; @@ -89,26 +100,40 @@ public partial class BuffManager OffhandStowed?.Invoke(id); } - /// The Items list's shields the cache knows, in list order. - private List ListedShields() + /// + /// The Items list's shields the cache knows, in list order. A shield marked "No buff" + /// (ItemRule.KeepBuffed off) is left out, so it is treated as an unlisted shield is: never a + /// target. An id with any of its rules marked is left out, whatever the rules' order. + /// are the listed shields left out for that. + /// + private List ListedShields(out List excludedIds) { + excludedIds = new List(); var found = new List(); var cache = _worldObjectCache; if (cache == null) return found; List rules; try { rules = new List(_settings.ItemRules); } catch { return found; } // the list edited mid-copy: next read + var excludedRule = new HashSet(); + foreach (var r in rules) + if (r.Id != 0 && r.ExcludedFromBuffing()) excludedRule.Add(r.Id); foreach (var r in rules) { - if (r.Id == 0 || found.Contains(r.Id)) continue; + if (r.Id == 0 || found.Contains(r.Id) || excludedIds.Contains(r.Id)) continue; var wo = cache[r.Id]; if (wo == null) continue; if (CombatManager.IsShieldItem(wo) || (WeaponList.IsShieldRule(r) && wo.ObjectClass == AcObjectClass.Armor)) + { + if (excludedRule.Contains(r.Id)) { excludedIds.Add(r.Id); continue; } found.Add(r.Id); + } } return found; } + private List ListedShields() => ListedShields(out _); + private bool InInventory(int id) { if (_worldObjectCache == null || id == 0) return false; @@ -125,7 +150,8 @@ public partial class BuffManager { long now = KitClockMs(); var rules = _settings.ItemRules; - if (!fresh && ReferenceEquals(rules, _shieldChoiceRules) && rules.Count == _shieldChoiceRuleCount + long excludedSig = ExcludedSignature(rules); + if (!fresh && ReferenceEquals(rules, _shieldChoiceRules) && rules.Count == _shieldChoiceRuleCount && excludedSig == _shieldChoiceExcluded && ReferenceEquals(_worldObjectCache, _shieldChoiceCache) && now >= _shieldChoiceAt && now - _shieldChoiceAt < ShieldReadMs) { where = _shieldChoiceWhy; @@ -137,6 +163,7 @@ public partial class BuffManager _shieldChoiceAt = now; _shieldChoiceRules = rules; _shieldChoiceRuleCount = rules.Count; + _shieldChoiceExcluded = excludedSig; _shieldChoiceCache = _worldObjectCache; // One log line when the answer changes, only for a character with a shield listed. string line = anyListed ? $"{id:X8}|{where}" : ""; @@ -151,13 +178,42 @@ public partial class BuffManager return id; } + /// + /// Which entries are marked "No buff", as one number (count and ids): ShieldToBuff's kept answer + /// is read again when it changes, so a flag flipped on an entry in place takes effect on the next + /// tick, not after ShieldReadMs. A list walk only (no inventory); -1 if it is edited mid-walk. + /// The Items face and a profile load replace the list, which the reference check already + /// catches; this covers an edit in place (the VTank importer removes then adds, so the count + /// can stay the same). + /// + private static long ExcludedSignature(List rules) + { + try + { + long count = 0, ids = 0; + foreach (var r in rules) + if (r.ExcludedFromBuffing()) { count++; ids = unchecked(ids * 31 + (uint)r.Id); } + return unchecked((count << 48) ^ ids); + } + catch { return -1; } + } + private int FindShieldToBuff(out string where, out bool anyListed) { anyListed = false; if (!_settings.BuffShield) { where = "Buff the shield is off"; return 0; } - var listed = ListedShields(); - anyListed = listed.Count > 0; - if (!anyListed) { where = "no shield listed"; return 0; } + var listed = ListedShields(out List excludedIds); + anyListed = listed.Count > 0 || excludedIds.Count > 0; + // A shield that takes no spells counts as one marked No buff: in the off hand it is the one in + // use and nothing is buffed. + bool unbuffable = false; + foreach (int id in listed.FindAll(_unbuffableShields.ContainsKey)) { listed.Remove(id); excludedIds.Add(id); unbuffable = true; } + if (listed.Count == 0) + { + where = unbuffable ? "the listed shield takes no spells (the server said so)" + : excludedIds.Count > 0 ? "the listed shield is marked No buff" : "no shield listed"; + return 0; + } foreach (int id in listed) { if (!IsWieldedLive(id)) continue; @@ -167,6 +223,16 @@ public partial class BuffManager where = "in the off hand"; return id; } + // A marked shield in the off hand is the one in use: no shield is buffed, not one put away + // for the wand some time before (a stale stow). + foreach (int id in excludedIds) + { + if (!IsWieldedLive(id)) continue; + _stowedShieldId = 0; + where = _unbuffableShields.ContainsKey(id) ? "the shield in the off hand takes no spells (the server said so)" + : "the shield in the off hand is marked No buff"; + return 0; + } if (_stowedShieldId != 0 && listed.Contains(_stowedShieldId) && InInventory(_stowedShieldId)) { where = "put into a pack for the wand"; @@ -487,7 +553,45 @@ public partial class BuffManager _host.WriteToChat($"[RynthAi] Not buffing the shield '{ItemName(shield)}' for {ShieldParkTime.TotalMinutes:0} min ({why}).", 2); } - /// Force Rebuff: the shield starts over too. + /// The server said takes no spells: never buffed again (saved). + private void MarkShieldUnbuffable(int shield, string serverLine) + { + if (shield == 0) return; + string name = ItemName(shield); + _unbuffableShields[shield] = name; + _shieldChoiceAt = long.MinValue / 2; // chosen again at once + foreach (long key in new List(_shieldSpellTimers.Keys)) + if (unchecked((int)(uint)(key >> 32)) == shield) _shieldSpellTimers.Remove(key); + SaveBuffTimers(); + _host.Log($"[Buff] shield 0x{(uint)shield:X8} '{name}': '{serverLine}' - it takes no spells: never buffed again (/ra buffs unbuffable clear to try again)."); + _host.WriteToChat($"[RynthAi] '{name}' takes no spells (the server said so): it is never buffed again. /ra buffs unbuffable clear to try it again.", 2); + } + + /// /ra buffs unbuffable [clear]: the shields that take no spells, or forget them. Chat lines to show. + internal List UnbuffableCommand(bool clear) + { + var lines = new List(); + if (clear) + { + int n = _unbuffableShields.Count; + _unbuffableShields.Clear(); + _shieldChoiceAt = long.MinValue / 2; + SaveBuffTimers(); + lines.Add(n == 0 ? "[RynthAi] No item was marked as taking no spells." : $"[RynthAi] Forgot {n} item(s) marked as taking no spells: they are buffed (and tried) again."); + return lines; + } + if (_unbuffableShields.Count == 0) + { + lines.Add("[RynthAi] No item is marked as taking no spells. Usage: /ra buffs unbuffable [clear]"); + return lines; + } + lines.Add($"[RynthAi] Never buffed, the server said they take no spells ({_unbuffableShields.Count}):"); + foreach (var kv in _unbuffableShields) lines.Add($"[RynthAi] 0x{(uint)kv.Key:X8} '{kv.Value}'"); + lines.Add("[RynthAi] /ra buffs unbuffable clear tries them again."); + return lines; + } + + /// Force Rebuff: the shield starts over too (the shields that take no spells stay skipped). private void ResetShieldBuffs() { _shieldSpellTimers.Clear(); @@ -509,11 +613,20 @@ public partial class BuffManager int family = unchecked((int)(kvp.Key & 0xFFFFFFFF)); lines.Add($"shield|{id}|{family}|{info.CastAt.Ticks}|{info.ExpiresAt.Ticks}|{info.SpellLevel}|{info.SpellName}"); } + // "unbuffable|id|name": a shield that takes no spells (kept until /ra buffs unbuffable clear). + foreach (var kv in _unbuffableShields) + lines.Add($"unbuffable|{unchecked((uint)kv.Key)}|{kv.Value}"); } /// One "shield|..." line of bufftimers.txt; false when the line is something else. private bool LoadShieldTimer(string[] p) { + if (p[0] == "unbuffable") + { + if (p.Length >= 2 && uint.TryParse(p[1], out uint ub) && ub != 0) + _unbuffableShields[unchecked((int)ub)] = p.Length >= 3 ? string.Join("|", p, 2, p.Length - 2) : ""; + return true; + } if (p[0] != "shield") return false; if (p.Length < 7) return true; if (!uint.TryParse(p[1], out uint id) || !int.TryParse(p[2], out int family) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs new file mode 100644 index 0000000..1598f8f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs @@ -0,0 +1,266 @@ +// ============================================================================ +// RynthSuite - Combat/BuffManager.VitalWandGate.cs +// No wand swap for a vital spell while a kit or potion can do the job. +// +// Kits are the standard heal, and the shield stays on: putting the shield away for a wand costs more +// damage than a small heal spell buys back. A melee character under Heal At used to put its shield away +// and pull a wand for Heal Self with kits in the pack (the wand was skipped only at Emergency Heal At). +// +// Out of Magic mode with no caster in hand, a vital spell (Heal Self, Stamina to Health, Revitalize, +// Stamina to Mana, the script hook's heal) would start a weapon swap to the wand. VitalSpellWouldSwap +// refuses it (CastVital: not handled), so the chain falls through to the potion, the kit, and the kit +// despite Kit Min Success. The exceptions: +// - nothing else can restore that vital (no usable kit, no potion Use Potions may drink): the swap is +// the only heal there is, so it goes; +// - a caster already wielded needs only the stance change (no weapon moves): allowed; +// - no wand found (FindWandInItems 0): the Magic stance goes bare-handed and no weapon moves: allowed; +// - a swap already under way finishes (refusing it mid-way left the shield in the pack); +// - health at or under Emergency Heal At (2026-11-07): a kit at low health and vitae can be a 5-8% +// chance, and refusing the spell there killed Drakkon; the surest heal goes; +// - Stamina to Mana never swaps in a fight (InCombatNow), potion or not; out of a fight it may, even +// with a mana potion carried (buffing is about to swap to the wand anyway). +// Buffing (EnsureMagicMode forBuff) is not gated and still swaps, and so does the HP failsafe's +// Lifestone Recall (it calls EnsureMagicMode itself, with the macro off). +// +// A kit the gate counts is one the kit picks would use: the live pack walk (ConsumableLookup, +// GetDirectInventory), minus a kit its line called used up (BuffManager.KitUsedUp.cs), minus a kit the +// server refused KitRefusedStreakMax times within KitRefusedStreakMs (a UseDone error or "You're too +// busy!" is no answer the kit wait drops, so such a kit would block every spell heal forever). A streak +// with no refusal for KitRefusedStreakMs ages out; a kit landing, or the macro stopping, ends them all. +// +// The stamina sources share one order with a last resort (AttemptStaminaRestore): with Revitalize +// refused here (or not cast at all for the between-fights top-off), a stamina kit skipped for Stamina +// Kit Min Success % would leave nothing. +// +// Logging: one "wand gate" line when the gate starts refusing a vital's spell, one when that ends (the +// swap is allowed again, the spell isn't asked for WandGateQuietMs, or the macro stops), and one when a +// refused kit stops counting. +// ============================================================================ + +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +public partial class BuffManager +{ + internal const int KitRefusedStreakMax = 3; + internal const double KitRefusedStreakMs = 10_000; + /// A refusal episode with no refusal this long is over (logged). + internal const double WandGateQuietMs = 5000; + private readonly Dictionary _kitRefusedStreak = new(); + // The vitals whose spell the gate is refusing now (by label): the spell's name and the last refusal. + private readonly Dictionary _wandGateRefusing = new(); + + /// Times the gate refused a vital spell's wand swap (tests, status). + internal int WandGateRefusals { get; private set; } + + /// True when the vital spell for must not start a wand swap now (see the header). + private bool VitalSpellWouldSwap(string label, string what, out string why) + { + why = ""; + string allowed; + if (_wandSwap.Active) allowed = "a wand swap is already under way"; + else if (CurrentCombatMode == CombatMode.Magic) allowed = "in Magic stance"; + else + { + int wandId = FindWandInItems(); + if (wandId == 0) allowed = "no wand found (bare-handed Magic)"; + else if (IsBuffWandWielded(wandId)) allowed = "a caster is in hand (the stance change only)"; + else if (label == LabelMana) + { + if (!InCombatNow()) allowed = "out of a fight"; + else + { + why = "no wand swap for Stamina to Mana in a fight (the shield stays on)"; + return NoteWandGateRefusal(label, what, "Stamina to Mana never swaps in a fight"); + } + } + else if (label != LabelStamina && _vitals.HealthPct <= _settings.EmergencyHealAt) + { + // At Emergency Heal At the surest heal goes: a kit's success chance falls with health and vitae + // (Drakkon's was 5-8% at low health), and at 9% the gate sent that kit instead of Stamina to + // Health and he died (2026-11-07). + allowed = $"health {_vitals.HealthPct}% at or under Emergency Heal At {_settings.EmergencyHealAt}%"; + } + else + { + bool stamina = label == LabelStamina; + bool kit =stamina ? HasUsableStaminaKit() : HasUsableHealthKit(); // Healing and the script heal + bool potion = !kit && (stamina ? HasAnyPotion("StaminaPotion", "Stamina") : HasAnyPotion("HealthPotion")); + if (!kit && !potion) allowed = $"no {(stamina ? "stamina" : "healing")} kit or potion is carried"; + else + { + why = "no wand swap for a vital spell (kits are the standard heal; the shield stays on)"; + return NoteWandGateRefusal(label, what, kit ? "a kit is carried" : "a potion is carried"); + } + } + } + if (_wandGateRefusing.Remove(label, out var ep)) + _host.Log($"[RynthAi] Vitals: wand gate ended for {ep.What}: {allowed}; its wand swap may go."); + return false; + } + + /// A refusal: logged when an episode for that vital starts. Always true (the caller returns it). + private bool NoteWandGateRefusal(string label, string what, string because) + { + WandGateRefusals++; + if (!_wandGateRefusing.ContainsKey(label)) + _host.Log($"[RynthAi] Vitals: wand gate: no wand swap for {what} - {because} " + + $"(health {_vitals.HealthPct}%, stamina {_vitals.StaminaPct}%, mana {_vitals.ManaPct}%); the kit or potion goes instead."); + _wandGateRefusing[label] = (what, Now); + return true; + } + + /// Every heartbeat (macro running): an episode with no refusal for WandGateQuietMs is over. + private void TickWandGateLog() + { + if (_wandGateRefusing.Count == 0) return; + List? done = null; + foreach (var kv in _wandGateRefusing) + if ((Now - kv.Value.Last).TotalMilliseconds >= WandGateQuietMs) (done ??= new()).Add(kv.Key); + if (done == null) return; + foreach (string label in done) + { + _host.Log($"[RynthAi] Vitals: wand gate ended for {_wandGateRefusing[label].What}: not asked for in {WandGateQuietMs / 1000:0} s."); + _wandGateRefusing.Remove(label); + } + } + + /// Ends every refusal episode (the macro stopped), logged. + private void EndWandGateEpisodes(string why) + { + if (_wandGateRefusing.Count == 0) return; + foreach (var kv in _wandGateRefusing) + _host.Log($"[RynthAi] Vitals: wand gate ended for {kv.Value.What}: {why}."); + _wandGateRefusing.Clear(); + } + + private void NoteKitRefusedStreak(int kitId) + { + if (kitId == 0) return; + DateTime now = Now; + PruneKitRefusedStreaks(now); + var next = _kitRefusedStreak.TryGetValue(kitId, out var s) && (now - s.First).TotalMilliseconds <= KitRefusedStreakMs + ? (s.Count + 1, s.First, now) + : (1, now, now); + _kitRefusedStreak[kitId] = next; + if (next.Item1 == KitRefusedStreakMax) + _host.Log($"[RynthAi] Vitals: wand gate: kit 0x{(uint)kitId:X8} '{_kitInFlightName}' refused {KitRefusedStreakMax} times in " + + $"{KitRefusedStreakMs / 1000:0} s: it no longer counts as a heal, a vital spell may swap to the wand."); + } + + /// Drops streaks with no refusal for KitRefusedStreakMs: the kit counts for the gate again. + private void PruneKitRefusedStreaks(DateTime now) + { + if (_kitRefusedStreak.Count == 0) return; + List? stale = null; + foreach (var kv in _kitRefusedStreak) + if ((now - kv.Value.Last).TotalMilliseconds > KitRefusedStreakMs) (stale ??= new()).Add(kv.Key); + if (stale != null) foreach (int id in stale) _kitRefusedStreak.Remove(id); + } + + /// Ends every refusal streak (a kit landed, or the macro stopped). + private void ClearKitRefusedStreaks() => _kitRefusedStreak.Clear(); + + /// A kit the gate does not count: called used up, or refused KitRefusedStreakMax times with the last + /// refusal under KitRefusedStreakMs ago. + private bool KitOutForGate(int id) + { + if (KitUsedUp(id)) return true; + PruneKitRefusedStreaks(Now); + return _kitRefusedStreak.TryGetValue(id, out var s) && s.Count >= KitRefusedStreakMax; + } + + /// A healing kit AttemptHealthKitUse could pick (a listed one, else the pack's). + private bool HasUsableHealthKit() + { + if (_worldObjectCache == null) return false; + foreach (var r in _settings.ConsumableRules) + if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase) + && !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase) + && ConsumableLookup.Resolve(_worldObjectCache, r, KitOutForGate) is WorldObject wo + && IsUseOnSelfKit(wo)) + return true; + return HasPackKit("Healing Kit"); + } + + /// A stamina kit AttemptStaminaKitUse could pick. + private bool HasUsableStaminaKit() => _host.HasUseObjectOn && HasPackKit("Stamina Kit"); + + /// A kit named "... " in the pack the gate still counts (BestPack*Kit's match). + private bool HasPackKit(string suffix) + { + if (_worldObjectCache == null) return false; + foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false)) + if ((wo.Name ?? "").EndsWith(suffix, StringComparison.OrdinalIgnoreCase) && !KitOutForGate(wo.Id)) + return true; + return false; + } + + /// A potion of AttemptPotion could drink (listed or in the pack), with Use Potions on. + private bool HasAnyPotion(params string[] types) + { + if (!_settings.UsePotions || _worldObjectCache == null) return false; + if (HasListedPotion(types)) return true; + foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false)) + { + string? kind = LegacyWeaponsUi.PotionType(wo); + if (kind == null || Array.FindIndex(types, t => t.Equals(kind, StringComparison.OrdinalIgnoreCase)) < 0) continue; + if (IsKitName(wo.Name)) continue; + return true; + } + return false; + } + + /// + /// The stamina sources in order, shared by the stamina step, the mana step's refill (AttemptManaRefill) + /// and the buffing mana floor: a kit, a listed potion first when , + /// Revitalize (unless is false: the between-fights top-off out of Magic), + /// any potion, then the kit Stamina Kit Min Success % skipped as the last resort. + /// + private bool AttemptStaminaRestore(bool listedPotionFirst = false, bool allowCast = true) + { + if (AttemptStaminaKit(false, out bool underMinSuccess) + || (listedPotionFirst && AttemptPotion(true, "StaminaPotion", "Stamina")) + || (allowCast && AttemptVitalCast("Revitalize Self")) + || AttemptPotion("StaminaPotion", "Stamina")) + return true; + // Last resort, as the heal chain's: the stamina kit Stamina Kit Min Success % skipped. With + // Revitalize refused by the wand gate (or not cast) and no potion, nothing else restores stamina. + if (underMinSuccess && AttemptStaminaKit(true, out _)) + { + _host.Log("[RynthAi] Vitals: no spell or potion could restore stamina; using the stamina kit despite Stamina Kit Min Success %."); + return true; + } + return false; + } + + /// + /// True when (FindWandInItems' pick) is in the player's hand: EnsureMagicMode + /// then needs no weapon move, only the stance change. Shared by EnsureMagicMode and VitalSpellWouldSwap. + /// + private bool IsBuffWandWielded(int wandId) + { + if (wandId == 0) return false; + // Primary check: CurrentWieldedLocation (stype=10) - works even before the + // phys-obj offset probe fires, mirrors CombatManager.EquipWeaponAndSetStance. + bool alreadyWielded = false; + var wandObj = _worldObjectCache?[wandId]; + if (wandObj != null) + alreadyWielded = wandObj.Values(LongValueKey.CurrentWieldedLocation, 0) > 0; + + // Secondary check via API if primary didn't confirm + if (EquippedState.IsWielded(_host, wandId) is bool trackedWand) alreadyWielded = trackedWand; // the server's word + else if (!alreadyWielded && _host.HasGetObjectWielderInfo) + { + uint playerId = _host.GetPlayerId(); + if (playerId != 0 && + _host.TryGetObjectWielderInfo((uint)wandId, out uint wielder, out _) && + wielder == playerId && _worldObjectCache?.InPackWalk(wandId) != true) // a stale record (the wand in a pack) + alreadyWielded = true; + } + return alreadyWielded; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 385140f..22d2faa 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -349,8 +349,51 @@ public partial class BuffManager : IDisposable /// Tests: whether a monster is within Monster Range (else CombatManager decides). internal Func? InCombatOverride { get; set; } - private bool InCombatNow() => InCombatOverride?.Invoke() - ?? _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true; + private bool InCombatNow() + { + bool beingHit = HealthFellRecently(); // first: it keeps its record on every pass + return InCombatOverride?.Invoke() + ?? (_combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true || beingHit); + } + + // Health falling means a fight, whatever the scan says. A mob behind a wall isn't in the scan, + // so a character it was hitting read as idle: every hit put him under Top Off HP, the heal took + // the tick, and nothing else ran until it stopped (2026-11-06: 45 s of kits with the mob hitting + // him once a second). With the fight lines he heals at Heal At and otherwise gets on with it. + private const double HealthFellCountsMs = 5000; + private int _healthFellLastPct = -1; + private DateTime _healthFellAt = DateTime.MinValue; + + private bool HealthFellRecently() + { + int pct = _vitals.HealthPct; + DateTime now = RynthClock.Now; + if (_healthFellLastPct >= 0 && pct < _healthFellLastPct) _healthFellAt = now; + _healthFellLastPct = pct; + return _healthFellAt != DateTime.MinValue && (now - _healthFellAt).TotalMilliseconds < HealthFellCountsMs; + } + + // ── Buffs wait while hurt in a fight (2026-11-07) ── + // Drakkon cast four weapon auras (2.4 s each) one after another with a golem's Force Bolts hitting him + // and his health under Heal At; the emergency heal then waited for the last aura's cast and he died. + // Under Heal At in a fight no new buff cast starts (one already sent finishes) and the arbiter doesn't + // give Buffing the tick for buffs: the heals (vital recharge keeps its slot) and combat go first. The + // buffs carry on once health is back over Heal At or the fight is over. + private bool _buffHurtWaitOn; + + /// True while health is under Heal At in a fight: no new buff cast. Logs the start and end of each wait. + public bool BuffsWaitForHealth() + { + bool wait = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt && InCombatNow(); + if (wait != _buffHurtWaitOn) + { + _host.Log(wait + ? $"[Buff] buffs wait: health {_vitals.HealthPct}% is under Heal At {_settings.HealAt}% in a fight; heals and combat go first." + : $"[Buff] buffs go on: health {_vitals.HealthPct}%, {(InCombatNow() ? "back over Heal At" : "the fight is over")}."); + _buffHurtWaitOn = wait; + } + return wait; + } // ── Rebuff When Idle (RebuffWhenIdle + RebuffIdleMarginMinutes; VTank's "idlebufftopoff") ── // The checkbox was saved and shown since the first version but nothing read it (a player asked, @@ -839,11 +882,14 @@ public partial class BuffManager : IDisposable get => _busyCount; set { + if (value > 0 && _busyCount <= 0) _busyRoseAt = Now; // the heal grace counts from the rise (BusyHoldsHeal) _busyCount = value; _busyGate.NoteCount(value, UseDoneSeqNow()); } } private int _busyCount; + // When the busy count last rose from 0 (the heal grace in BusyHoldsHeal). + private DateTime _busyRoseAt = DateTime.MinValue; // A heal and a leftover busy count (2026-10-05, a mage's heals "sometimes several seconds // late"): a war or void cast raises the plugin's busy count, and AC lowers its own count @@ -863,15 +909,28 @@ public partial class BuffManager : IDisposable /// True while the busy count should hold a heal: it is positive and not a leftover. A leftover /// (a UseDone arrived after the count last rose and no cast gesture is animating: the server /// finished every action behind it) is cleared here, as combat does, and lets the heal go. + /// So is a count up ActionPacer.HealGraceMs since it rose (the heal grace, below). /// internal bool BusyHoldsHeal() { if (BusyCount <= 0) return false; bool gesture = _host.HasGetCastBusyState && !_host.CanCastNow; - if (!_busyGate.IsStale(BusyCount, _host.HasUseDoneSeq, UseDoneSeqNow(), gesture)) return true; + string why; + if (_busyGate.IsStale(BusyCount, _host.HasUseDoneSeq, UseDoneSeqNow(), gesture)) + why = "the server finished the action (UseDone)"; + else + { + // The heal grace: the count can't say what it waits for (a lost UseDone leaves it up until + // the 5 s force-clear), so it holds a heal ActionPacer.HealGraceMs at most, timed from its + // rise so it does not add to the pacer's own hold. The pacer and the cast gate still hold + // a heal for an action the server hasn't answered and for a gesture that is animating. + double upMs = (Now - _busyRoseAt).TotalMilliseconds; + if (upMs < ActionPacer.HealGraceMs) return true; + why = $"the count has been up {upMs:0} ms (heal grace)"; + } int was = BusyCount; StaleBusyClears++; - _onStaleBusy?.Invoke($"vitals: health is under a heal line and the server finished the action (UseDone) — was {was}"); + _onStaleBusy?.Invoke($"vitals: health is under a heal line and {why} - was {was}"); if (BusyCount > 0) BusyCount = 0; // no callback, or the shared mirror was already 0 _busyGate.Reset(); return false; @@ -1151,7 +1210,8 @@ public partial class BuffManager : IDisposable /// and they need the same mid-cast protection a buff gets. Side-effect free: /// CheckVitals repopulates these flags every cycle it reaches. /// - public bool WantsVitalRecharge => _isHealingSelf || _isRechargingMana || _isRechargingStamina || WantsHealNow() || WantsManaNow(); + public bool WantsVitalRecharge => (!HealHoldReleased && (_isHealingSelf || WantsHealNow())) // the heal hold (BuffManager.HealHold.cs) + || _isRechargingMana || _isRechargingStamina || WantsManaNow(); // Health below a heal line wins the arbiter's tick by itself. The flags above are only set on // a tick where CheckVitals actually ran and acted, and it doesn't run while the client is busy @@ -1336,6 +1396,7 @@ public partial class BuffManager : IDisposable public void OnHeartbeat() { bool track = _settings.IsMacroRunning && _vitals.MaxHealth > 0; + NoteKitProgress(); // every heartbeat: the vitals step is not reached while the kit's heal motion plays _healHold = ""; _healHoldDetail = ""; _healWaitKind = ""; @@ -1383,7 +1444,15 @@ public partial class BuffManager : IDisposable TickRechargeRequest(); // /ra recharge: one vitals pass, macro on or off (BuffManager.Recharge.cs) TickOneTouchRequest(); // /ra heal, /ra stam, /ra mana: one-touch recharge, macro on or off (BuffManager.OneTouch.cs) - if (!_settings.IsMacroRunning) { DropWandSwap("the macro stopped"); return; } + if (!_settings.IsMacroRunning) + { + DropWandSwap("the macro stopped"); + ResetHealHold("the macro stopped"); + ClearKitRefusedStreaks(); // the vital wand gate's refusal streaks end + EndWandGateEpisodes("the macro stopped"); + return; + } + TickWandGateLog(); // the vital wand gate: says when a refusal episode is over (BuffManager.VitalWandGate.cs) // A wand swap's next step goes as soon as the server has answered the last (before the cast gates). NoteModeChange(); @@ -1396,7 +1465,9 @@ public partial class BuffManager : IDisposable // Heals failing at Emergency Heal At: break the cast, then recall (BuffManager.HpFailsafe.cs). TickHpFailsafe(); - if (!_settings.IsMacroRunning) return; + if (!_settings.IsMacroRunning) { ResetHealHold("the HP failsafe stopped the macro for a recall"); return; } + // No heal landing under a heal line: combat gets the tick for a while (BuffManager.HealHold.cs). + TickHealHold(); // A Magic stance we asked for: watch the client's mode every tick (see ObserveStance). ObserveStance(); @@ -1825,8 +1896,7 @@ public partial class BuffManager : IDisposable if (_vitals.StaminaPct <= 15) { _vitalWhy = ""; - if (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") - || AttemptPotion("StaminaPotion", "Stamina")) + if (AttemptStaminaRestore()) { _isRechargingStamina = true; return; @@ -1914,6 +1984,8 @@ public partial class BuffManager : IDisposable if (_settings.EnableBuffing) { + if (BuffsWaitForHealth()) + return; // hurt in a fight: no new buff cast (a run in progress resumes after) if (CheckAndCastSelfBuffs()) return; @@ -2029,6 +2101,15 @@ public partial class BuffManager : IDisposable } internal bool CheckVitals() // internal for the host tests (VitalsTests) + { + // Combat has the tick (BuffManager.HealHold.cs): no stance change or wield for a vital this pass. + _vitalsNoStanceChange = HealHoldReleased && CurrentCombatMode != CombatMode.Magic; + _vitalsNoPeaceSwitch = HealHoldReleased; // no peace switch for a kit either, Magic stance included + try { return CheckVitalsCore(); } + finally { _vitalsNoStanceChange = false; _vitalsNoPeaceSwitch = false; } + } + + private bool CheckVitalsCore() { int curHealthPct = _vitals.HealthPct; int curManaPct = _vitals.ManaPct; @@ -2156,8 +2237,15 @@ public partial class BuffManager : IDisposable // for the wand and back (slow, and the 10-06 stalls began at those switches), so a stamina // potion listed in Consumables goes before it. A potion drunk under 2.5 s ago: no Revitalize // on top of it. In Magic stance (a caster) Revitalize stays first. + // No wand swap for the between-fights top-off (the owner, 2026-11-07): with melee or missile + // weapons in hand, Revitalize means weapons -> peace -> wand -> Magic -> cast -> back, about + // 5.5 s, and a melee character (Top Off Stam 60, no kit or potion) did it every 2 minutes, often between + // two corpses or with the next monster walking up. Kits and potions still top off; stamina + // regenerates otherwise. Under Re-stam At, or in a Re-stam To run, the cast goes as before. + bool castNeedsSwap = !inCombat && !_restamRun && curStamPct >= _settings.RestamAt + && CurrentCombatMode != CombatMode.Magic && !FightsWithMagic(); int sentBefore = _vitalActionsSent; - if (curStamPct < stamThreshold && AttemptStaminaChain()) + if (curStamPct < stamThreshold && AttemptStaminaChain(allowCast: !castNeedsSwap)) { _isRechargingStamina = true; // Only a cast, kit or potion actually sent counts toward the run's cap. The chain also @@ -2167,10 +2255,18 @@ public partial class BuffManager : IDisposable if (_restamRun && _vitalActionsSent != sentBefore) _restamRunCasts++; return true; } + if (curStamPct < stamThreshold && castNeedsSwap && (RynthClock.Now - _staminaNoSwapLoggedAt).TotalSeconds >= 60) + { + _staminaNoSwapLoggedAt = RynthClock.Now; + _host.Log($"[RynthAi] Vitals: stamina {curStamPct}% < Top Off Stamina {stamThreshold}%, no stamina kit or potion: " + + $"no wand swap for it out of a fight (it regenerates); under Re-stam At {_settings.RestamAt}% Revitalize is cast."); + } return false; } + private DateTime _staminaNoSwapLoggedAt = DateTime.MinValue; + /// /// The heal chain of the vitals step (CheckVitals, and the one-touch heal): a kit, Heal Self and a /// potion, or with the kit and potion before the spell (no wand swap @@ -2220,7 +2316,7 @@ public partial class BuffManager : IDisposable // Stamina too low for Stamina to Mana (StaminaToManaFloorPct: Re-stam At, at least 15): a // stamina kit, Revitalize or a potion first. if (curStamPct <= StaminaToManaFloorPct() && TopStaminaToManaId() != 0 - && (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") || AttemptPotion("StaminaPotion", "Stamina"))) + && AttemptStaminaRestore()) { refilledStamina = true; return true; @@ -2230,19 +2326,16 @@ public partial class BuffManager : IDisposable /// /// The stamina step: a kit, a listed potion first out of Magic stance, Revitalize, then any potion - /// (the reasons are in the comment above CheckVitals' stamina line). + /// (the reasons are in the comment above CheckVitals' stamina line). + /// false: kits and potions only (no wand swap for the idle top-off). /// - private bool AttemptStaminaChain() + private bool AttemptStaminaChain(bool allowCast = true) { bool potionFirst = CurrentCombatMode != CombatMode.Magic; bool potionJustDrunk = potionFirst && _settings.UsePotions && (RynthClock.Now - _lastPotionAt).TotalMilliseconds < 2500 && HasListedPotion("StaminaPotion", "Stamina"); - return !potionJustDrunk - && (AttemptStaminaKitUse() - || (potionFirst && AttemptPotion(true, "StaminaPotion", "Stamina")) - || AttemptVitalCast("Revitalize Self") - || AttemptPotion("StaminaPotion", "Stamina")); + return !potionJustDrunk && AttemptStaminaRestore(listedPotionFirst: potionFirst, allowCast: allowCast); } // Re-stam To (2026-10-06): a recharge started under Re-stam At carries on until stamina @@ -2438,8 +2531,16 @@ public partial class BuffManager : IDisposable // A recovery vital retried after a mana refusal: its retry gap and the per-second ceiling. if (IsRecoveryVital(what) && RecoveryRetryHolds(family) is { Length: > 0 } recoveryWhy) return VitalNo(recoveryWhy); + // No wand swap for a vital spell while a kit or potion heals (BuffManager.VitalWandGate.cs). + if (VitalSpellWouldSwap(label, what, out string swapWhy)) + return VitalNo(swapWhy); if (CurrentCombatMode != CombatMode.Magic && RynthClock.Now < _vitalSwapBlockedUntil) return VitalNo("wand swap blocked, retrying shortly"); + if (_vitalsNoStanceChange) + { + NoteHealHoldRefusal(peace: false, what); + return VitalNo("combat has the tick (no heal landed): no wand swap for a spell"); + } bool urgentHeal = label == LabelHealing && (_oneTouchHealthScope || HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct)); if (!EnsureMagicMode(urgentHeal: urgentHeal)) { @@ -2684,15 +2785,18 @@ public partial class BuffManager : IDisposable foreach (var r in _settings.ConsumableRules) if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase) && !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase) // a stamina kit heals no health - && ConsumableLookup.Resolve(_worldObjectCache, r) is WorldObject wo + && ConsumableLookup.Resolve(_worldObjectCache, r, KitUsedUp) is WorldObject wo && IsUseOnSelfKit(wo)) { kit = wo; break; } // no kit: the potion step drinks it if (kit == null) { kit = BestPackHealingKit(); fromPack = true; } if (kit == null) return VitalNo("no healing kit"); if (KitRetryWait(out string kitWait)) return VitalNo(kitWait); // Too likely to fail on what's missing (KitMinSuccessPct): let the spell have it. uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0; - if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits, _settings.KitMinSuccessPct)) return VitalNo($"{kit.Name} under Kit Min Success %"); - if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) + // Combat has the tick (BuffManager.HealHold.cs): no peace switch goes out, so the chance is the stance it is in. + if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch, _settings.KitMinSuccessPct)) return VitalNo($"{kit.Name} under Kit Min Success %"); + if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && _vitalsNoPeaceSwitch) + NoteHealHoldRefusal(peace: true, "the healing kit"); + if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && !_vitalsNoPeaceSwitch) { // Only a request that went out starts the wait: a refusal (the engine turns stance changes away // around a teleport) leaves no pacing state, so the next tick asks again. @@ -2711,6 +2815,7 @@ public partial class BuffManager : IDisposable _host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself"); _lastCastAttempt = RynthClock.Now; MarkKitUsed(); + NoteKitInFlight(kit); NoteHealSent(kit.Name ?? "healing kit"); return true; } @@ -2719,8 +2824,13 @@ public partial class BuffManager : IDisposable /// Uses the best stamina kit in the pack on the player, with the same rules as healing /// kits: not in Magic mode unless UseKitsInMagicMode, peace mode first if PeaceModeForKits. /// - private bool AttemptStaminaKitUse() + private bool AttemptStaminaKitUse() => AttemptStaminaKit(false, out _); + + /// : a kit was there and skipped only for Stamina Kit Min Success %; + /// uses it anyway (AttemptStaminaRestore's last resort). + private bool AttemptStaminaKit(bool ignoreMinSuccess, out bool underMinSuccess) { + underMinSuccess = false; if (_worldObjectCache == null || !_host.HasUseObjectOn) return false; int mode = CurrentCombatMode; if (mode == CombatMode.Magic && !_settings.UseKitsInMagicMode) return false; @@ -2729,8 +2839,15 @@ public partial class BuffManager : IDisposable if (KitRetryWait(out _)) return false; uint missing = _vitals.MaxStamina > _vitals.CurrentStamina ? _vitals.MaxStamina - _vitals.CurrentStamina : 0; // Its own line (Stamina Kit Min Success %): below it Revitalize Self or a potion goes. - if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits, _settings.StaminaKitMinSuccessPct)) return false; - if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) + // Combat has the tick (BuffManager.HealHold.cs): no peace switch goes out, so the chance is the stance it is in. + if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch, _settings.StaminaKitMinSuccessPct)) + { + underMinSuccess = true; + return false; + } + if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && _vitalsNoPeaceSwitch) + NoteHealHoldRefusal(peace: true, "the stamina kit"); + if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && !_vitalsNoPeaceSwitch) { if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit")) _lastCastAttempt = RynthClock.Now; @@ -2744,6 +2861,7 @@ public partial class BuffManager : IDisposable _vitalActionsSent++; _lastCastAttempt = RynthClock.Now; MarkKitUsed(stamina: true); + NoteKitInFlight(kit); return true; } @@ -2753,10 +2871,43 @@ public partial class BuffManager : IDisposable // and used a second kit, every time (2026-10-03). After a kit, vitals wait for the // kit's own result line (heal, fail, movement disrupted, already at full), plus // KitLandGraceMs for the vitals to catch up, or KitResultTimeoutMs with no line at all. + // + // The heal grace (2026-11-07): a kit with no result line held every vital for 8 s, the old + // KitResultTimeoutMs, with the label reading Healing and nothing healing. ACE answers a kit it + // won't play (an item the player no longer has, a target it can't heal) with a bare UseDone and + // no chat, and sends a kit's result line before its UseDone. So (KitWaitVerdict): + // - a UseDone(0) for the kit with no line ends the wait KitLandGraceMs later (none is coming), + // unless the heal motion is still playing (that UseDone was another action's); + // - a kit the server shows no sign of having taken (no heal motion since the send, no UseDone, + // no line) is let go after ActionPacer.HealGraceMs, and the next tick may send it again; + // - a started kit is waited for KitResultTimeoutMs at most (a healthy kit answers in 2.5 s). private DateTime _kitUsedAt = DateTime.MinValue; private DateTime _kitLandedAt = DateTime.MinValue; - private const double KitResultTimeoutMs = 8000; + private DateTime _kitAnsweredAt = DateTime.MinValue; // the kit's own UseDone(0), no line yet + private bool _kitSawAnimating; // the motion queue read busy since the send + // 3.5 s: the longest healthy kit answer is 2.5 s (ActionPacer's time limits). Stamina kits share it. + internal const double KitResultTimeoutMs = 3500; private const double KitLandGraceMs = 700; + /// Kits let go with no result line (heal grace or the time limit) (tests, status). + internal int KitRetries { get; private set; } + + internal enum KitWaitEnd { Waiting, Landed, Answered, NotTaken, TimedOut } + + /// + /// The kit wait, from what has been seen since the send (pure; a ms value below 0 = not seen): the + /// result line plus KitLandGraceMs; the kit's UseDone(0) with no line plus KitLandGraceMs, with no + /// motion playing; nothing at all from the server ( false) and no + /// motion playing after ActionPacer.HealGraceMs; or KitResultTimeoutMs whatever happened. + /// + internal static KitWaitEnd KitWaitVerdict(double msSinceUse, double msSinceLanded, double msSinceAnswered, + bool serverTookIt, bool animatingNow) + { + if (msSinceLanded >= 0) return msSinceLanded >= KitLandGraceMs ? KitWaitEnd.Landed : KitWaitEnd.Waiting; + if (msSinceAnswered >= KitLandGraceMs && !animatingNow) return KitWaitEnd.Answered; + if (!serverTookIt && !animatingNow && msSinceUse >= ActionPacer.HealGraceMs) return KitWaitEnd.NotTaken; + if (msSinceUse >= KitResultTimeoutMs) return KitWaitEnd.TimedOut; + return KitWaitEnd.Waiting; + } // A refused kit (2026-10-05): ACE answers a kit used while the character is busy (a swing, a // cast still resolving), in the air, or on something it can't heal with a UseDone error and @@ -2777,10 +2928,36 @@ public partial class BuffManager : IDisposable { _kitUsedAt = RynthClock.Now; _kitLandedAt = DateTime.MinValue; + _kitAnsweredAt = DateTime.MinValue; + _kitSawAnimating = false; _kitIsStamina = stamina; _kitSeqAtUse = UseDoneSeqNow(); } + private bool MotionQueueBusy => _host.HasGetCastBusyState && !_host.CanCastNow; + + /// + /// The server has shown it took the kit in flight (its heal motion, or its UseDone(0)). An engine + /// with neither GetCastBusyState nor the UseDone sequence can show neither, so there the kit counts + /// as taken and only KitResultTimeoutMs ends the wait (no resend at the heal grace). + /// + private bool KitServerTookIt() => + (!_host.HasGetCastBusyState && !_host.HasUseDoneSeq) || _kitSawAnimating || _kitAnsweredAt != DateTime.MinValue; + + /// + /// Records what the server has done with the kit in flight: the heal motion playing (the client's + /// motion queue busy) or the kit's UseDone(0), the first UseDone after the send (as the pacer pairs + /// a cast). Every heartbeat, and from KitPending. + /// + private void NoteKitProgress() + { + if (_kitUsedAt == DateTime.MinValue || _kitLandedAt != DateTime.MinValue) return; + if (!_kitSawAnimating && MotionQueueBusy) _kitSawAnimating = true; + if (_kitAnsweredAt == DateTime.MinValue && _host.HasUseDoneSeq && _host.TryGetLastUseDone(out int seq, out uint err) + && seq == _kitSeqAtUse + 1 && err == 0) + _kitAnsweredAt = RynthClock.Now; + } + internal bool KitPending() { if (_kitUsedAt == DateTime.MinValue) return false; @@ -2791,12 +2968,30 @@ public partial class BuffManager : IDisposable KitRefused($"UseDone error 0x{err:X}"); return false; } + NoteKitProgress(); DateTime now = RynthClock.Now; - bool done = _kitLandedAt != DateTime.MinValue - ? (now - _kitLandedAt).TotalMilliseconds >= KitLandGraceMs - : (now - _kitUsedAt).TotalMilliseconds >= KitResultTimeoutMs; - if (done) { _kitUsedAt = DateTime.MinValue; _kitLandedAt = DateTime.MinValue; } - return !done; + double sinceUse = (now - _kitUsedAt).TotalMilliseconds; + var end = KitWaitVerdict(sinceUse, + _kitLandedAt != DateTime.MinValue ? (now - _kitLandedAt).TotalMilliseconds : -1, + _kitAnsweredAt != DateTime.MinValue ? (now - _kitAnsweredAt).TotalMilliseconds : -1, + KitServerTookIt(), MotionQueueBusy); + if (end == KitWaitEnd.Waiting) return true; + if (end != KitWaitEnd.Landed) + { + KitRetries++; + string what = end switch + { + KitWaitEnd.Answered => "was answered (UseDone) with no result line", + KitWaitEnd.NotTaken => "shows no sign the server took it (no motion, no UseDone, no result line)", + _ => "has no result line yet", + }; + _host.Log($"[RynthAi] Vitals: the {(_kitIsStamina ? "stamina" : "healing")} kit {what} {sinceUse:0} ms after use: " + + "vitals carry on (heal grace), the next tick may send it again."); + } + _kitUsedAt = DateTime.MinValue; + _kitLandedAt = DateTime.MinValue; + _kitAnsweredAt = DateTime.MinValue; + return false; } /// The kit in flight was refused: no result line will come, so stop waiting for one. @@ -2807,6 +3002,7 @@ public partial class BuffManager : IDisposable _kitUsedAt = DateTime.MinValue; _kitRefusedAt = RynthClock.Now; KitRefusals++; + NoteKitRefusedStreak(_kitInFlightId); // the vital wand gate stops counting a kit refused again and again _host.Log($"[RynthAi] Vitals: the {(_kitIsStamina ? "stamina" : "healing")} kit was refused {ms:0} ms after use ({why}): " + $"no result will come, vitals carry on (next kit in {KitRetryAfterRefusalMs:0} ms)."); } @@ -2898,6 +3094,7 @@ public partial class BuffManager : IDisposable { string name = wo.Name ?? ""; if (!name.EndsWith("Stamina Kit", StringComparison.OrdinalIgnoreCase)) continue; + if (KitUsedUp(wo.Id)) continue; // its line said used up; the walk may not show it yet int rank = name.Contains("Greater", StringComparison.OrdinalIgnoreCase) ? 0 : name.Contains("Lesser", StringComparison.OrdinalIgnoreCase) ? 2 : 1; if (rank < bestRank) { best = wo; bestRank = rank; } @@ -2917,6 +3114,7 @@ public partial class BuffManager : IDisposable { string name = wo.Name ?? ""; if (!name.EndsWith("Healing Kit", StringComparison.OrdinalIgnoreCase)) continue; + if (KitUsedUp(wo.Id)) continue; // its line said used up; the walk may not show it yet int rank = Array.FindIndex(KitRanks, k => name.Contains(k, StringComparison.OrdinalIgnoreCase)); if (rank < 0) rank = name.Contains("Crude", StringComparison.OrdinalIgnoreCase) ? KitRanks.Length + 1 : KitRanks.Length; if (rank < bestRank) { best = wo; bestRank = rank; } @@ -4522,7 +4720,11 @@ public partial class BuffManager : IDisposable // A kit on yourself finished (see KitPending). After the speech filter: "heal yourself" in a tell is not one. if (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue && IsKitResultLine(lower)) + { _kitLandedAt = RynthClock.Now; + NoteKitResultLine(text, lower); // "... is used up." naming it: kit picks skip it (BuffManager.KitUsedUp.cs) + ClearKitRefusedStreaks(); // a kit landed: the refusal streaks end (BuffManager.VitalWandGate.cs) + } // Real failure phrases. Note: bare "component" was removed — it false-matches // the "consumed the following components" line, which fires for both success @@ -4740,7 +4942,7 @@ public partial class BuffManager : IDisposable { _cast.Result(null, "refused by the server", atStart: true); _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} on the shield 0x{(uint)_pendingShieldId:X8} - '{text}'"); - ParkShield(_pendingShieldId, "the server says these spells can't be cast on it"); + MarkShieldUnbuffable(_pendingShieldId, text); // never again, not just 30 min (BuffManager.Shield.cs) _pendingSpellId = 0; _pendingShieldId = 0; _onCastResolved?.Invoke("can't be cast on the shield"); @@ -5390,23 +5592,7 @@ public partial class BuffManager : IDisposable return false; } - // Primary check: CurrentWieldedLocation (stype=10) — works even before the - // phys-obj offset probe fires, mirrors CombatManager.EquipWeaponAndSetStance. - bool alreadyWielded = false; - var wandObj = _worldObjectCache?[wandId]; - if (wandObj != null) - alreadyWielded = wandObj.Values(LongValueKey.CurrentWieldedLocation, 0) > 0; - - // Secondary check via API if primary didn't confirm - if (EquippedState.IsWielded(_host, wandId) is bool trackedWand) alreadyWielded = trackedWand; // the server's word - else if (!alreadyWielded && _host.HasGetObjectWielderInfo) - { - uint playerId = _host.GetPlayerId(); - if (playerId != 0 && - _host.TryGetObjectWielderInfo((uint)wandId, out uint wielder, out _) && - wielder == playerId && _worldObjectCache?.InPackWalk(wandId) != true) // a stale record (the wand in a pack) - alreadyWielded = true; - } + bool alreadyWielded = IsBuffWandWielded(wandId); // shared with the vital wand gate (BuffManager.VitalWandGate.cs) if (!_settings.FastWeaponSwap) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs index eabf0e9..865981a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs @@ -4,12 +4,13 @@ using System.Linq; using RynthCore.Plugin.RynthAi.CreatureData; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthAi; /// /// Missile swaps between launchers that shoot different ammo (bow / crossbow / atlatl), rules in -/// . Melee, magic and thrown weapons never come here. +/// . Melee and magic weapons never come here. /// /// 1. The plan: a launcher with no fitting ammo in the pack is not a candidate (logged once), /// unless it is the one in hand (running out is ammo crafting's job, as before) or no @@ -18,29 +19,43 @@ namespace RynthCore.Plugin.RynthAi; /// picks. /// 2. Before wielding a launcher, ammo of another type in the ammunition slot goes into the /// pack (the server refuses the launcher otherwise). One move in flight, 3 tries, then a rest. -/// 3. Once the launcher is in hand, the chosen stack is wielded: one in flight, confirmed in -/// the ammunition slot, retry cap and no flip-flop (, the same -/// tracker as weapons). Ammo crafting holds off while this runs (). +/// Before a thrown weapon, any ammo goes into the pack too (it is its own ammo). +/// 3. Whenever a launcher of a known type is in hand in a fight and the ammo slot holds nothing it +/// can shoot, the chosen stack is wielded: one in flight, confirmed in the ammunition slot, +/// retry cap (, the same tracker as weapons). Ammo of the wrong type +/// goes into the pack first. No fitting ammo at all: said in chat once, and no shot goes out. +/// Ammo crafting holds off while this runs (). +/// +/// Step 3 ran only after combat's own launcher swap, for 30 s, and only when a fitting stack was in +/// the pack when the swap began; any other empty quiver was left to ammo crafting, which knows ammo +/// and launchers by name only (2026-11-07, the owner: a bow to crossbow swap put the bow and its +/// infinite arrows away and wielded the crossbow, but not the infinite quarrels, so it dry fired). /// public partial class CombatManager { - /// Combat's ammo wields after a launcher swap: one in flight, confirmed, capped. + /// Combat's ammo wields: one in flight, confirmed, capped. internal WeaponSwapTracker AmmoTracker { get; } = new(); /// Tests: the pack an ammo stack is put into (default: an open pack with room). internal Func? OpenPackOverride { get; set; } + /// When something else (ammo crafting) last wielded ammo; set by the plugin. Combat's + /// ammo step leaves the slot alone for after it. + public Func? AmmoWieldedElsewhereAt { get; set; } + private const double AmmoElsewhereGraceMs = 3000; // The launcher whose ammo combat wields once it lands, and until when that holds crafting off. private int _ammoFollowUpFor; private DateTime _ammoFollowUpUntil = DateTime.MinValue; private const double AmmoFollowUpMs = 30_000; - // Putting ammo of the wrong type away before the launcher wield. - private int _ammoDequipPendingId, _ammoDequipTries; + // Putting ammo of the wrong type away before the launcher wield (or for the launcher in hand). + private int _ammoDequipPendingId, _ammoDequipTries, _ammoDequipFor; private DateTime _ammoDequipAt = DateTime.MinValue, _ammoDequipRestUntil = DateTime.MinValue; private const double AmmoDequipResolveMs = 2500; private const int AmmoDequipMaxTries = 3; // When the old ammo first read out of the ammunition slot (MinValue = not seen yet). private DateTime _ammoOffSeenAt = DateTime.MinValue; + // Ammo of no AmmoType taken off for a swap to _ammoTakenOffFor (it belongs to the old launcher). + private int _ammoTakenOffId, _ammoTakenOffFor; /// /// How long the launcher waits once the old ammo reads off (2026-10-12). Before, the dequip @@ -51,23 +66,36 @@ public partial class CombatManager internal double AmmoOffSettleMs { get; set; } = 400; private readonly HashSet _noAmmoNoted = new(); + // Launchers whose "no ammo to shoot" was said in chat (until ammo is on it again). + private readonly HashSet _noAmmoSaid = new(); /// /// A launcher swap's ammo step is under way (the old stack going into the pack, or the new /// one being wielded). Ammo crafting waits: it would otherwise equip ammo for the launcher /// being swapped away from, or start a craft in the middle of the swap. /// - public bool AmmoSwapInProgress => _ammoFollowUpFor != 0 && RynthClock.Now < _ammoFollowUpUntil; + public bool AmmoSwapInProgress + { + get + { + DateTime now = RynthClock.Now; + return (_ammoFollowUpFor != 0 && now < _ammoFollowUpUntil) + || AmmoTracker.InFlight(now) // bounded: no target any more must not hold crafting off for good + || (_ammoDequipPendingId != 0 && (now - _ammoDequipAt).TotalMilliseconds < AmmoDequipResolveMs + AmmoOffSettleMs); + } + } private void ResetAmmoState() { AmmoTracker.Reset(); _ammoFollowUpFor = 0; _ammoFollowUpUntil = DateTime.MinValue; - _ammoDequipPendingId = _ammoDequipTries = 0; + _ammoDequipPendingId = _ammoDequipTries = _ammoDequipFor = 0; _ammoDequipRestUntil = DateTime.MinValue; _ammoOffSeenAt = DateTime.MinValue; + _ammoTakenOffId = _ammoTakenOffFor = 0; _noAmmoNoted.Clear(); + _noAmmoSaid.Clear(); } /// Arrows, quarrels, darts: ValidLocations has the ammunition slot; by name when that isn't known. @@ -78,15 +106,30 @@ public partial class CombatManager return WorldObjectCache.IsAmmo(wo); } + /// A thrown weapon (a missile weapon that stacks and isn't ammo): its own ammo. + private static bool IsThrownWeapon(WorldObject? wo) => + wo != null && wo.ObjectClass == AcObjectClass.MissileWeapon && !IsAmmoItem(wo) + && wo.Values(LongValueKey.MaxStackSize, 0) > 1; + /// The ammo type a weapon needs; 0 for anything but a launcher whose type is known (thrown, melee, wand). - private static int LauncherTypeOf(WorldObject? wo) + internal static int LauncherTypeOf(WorldObject? wo) { if (wo == null || wo.ObjectClass != AcObjectClass.MissileWeapon || IsAmmoItem(wo)) return 0; bool stackable = wo.Values(LongValueKey.MaxStackSize, 0) > 1; return MissileAmmo.LauncherAmmoType(wo.Values((int)MissileAmmo.PropAmmoType, 0), wo.Name, stackable); } - private static int AmmoTypeOfItem(WorldObject wo) => MissileAmmo.AmmoTypeOf(wo.Values((int)MissileAmmo.PropAmmoType, 0), wo.Name); + /// An ammo item's type: AmmoType, else its name; 0 = none (an ammunition-slot item with neither). + internal static int AmmoTypeOfItem(WorldObject wo) => MissileAmmo.AmmoTypeOf(wo.Values((int)MissileAmmo.PropAmmoType, 0), wo.Name); + + /// Ammo that never runs out (): UnlimitedUse, or a single unstackable item. + internal static bool IsInfiniteAmmo(RynthCoreHost host, WorldObject wo) + { + bool unlimited = false; + try { unlimited = host.HasGetObjectBoolProperty && host.TryGetObjectBoolProperty(unchecked((uint)wo.Id), MissileAmmo.PropUnlimitedUse, out bool u) && u; } + catch { unlimited = false; } + return MissileAmmo.LooksInfinite(unlimited, wo.Values(LongValueKey.StackCount, 0), wo.Values(LongValueKey.MaxStackSize, 0), wo.Name); + } /// Every ammo stack the character carries (wielded one included), in pack order. internal List PackAmmo() @@ -96,8 +139,9 @@ public partial class CombatManager foreach (var wo in _worldFilter.GetDirectInventory(forceRefresh: true)) { if (!IsAmmoItem(wo)) continue; + // Named ammo always has a type (its name); 0 is an ammunition-slot item with no AmmoType + // and a name of its own (a server's infinite ammo): it is kept, as ammo of no type. int type = AmmoTypeOfItem(wo); - if (type == 0) continue; uint uid = unchecked((uint)wo.Id); int? dt = _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, WeaponElements.PropDamageType, out int d) ? d : null; int? fx = _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, WeaponElements.PropUiEffects, out int f) ? f : null; @@ -106,7 +150,7 @@ public partial class CombatManager int listIdx = rules.FindIndex(r => r.Id == wo.Id); int quality = AmmoRecipes.OutputRank(wo.Name, MissileAmmo.CategoryOf(type)); bool wielded = WorldObjectCache.IsWieldedByPlayer(_host, wo); - list.Add(new AmmoCandidate(wo.Id, wo.Name, type, elem, prismatic, quality, listIdx, wielded)); + list.Add(new AmmoCandidate(wo.Id, wo.Name, type, elem, prismatic, quality, listIdx, wielded, IsInfiniteAmmo(_host, wo))); } return list; } @@ -146,7 +190,7 @@ public partial class CombatManager pack ??= PackAmmo(); var wielded = pack.FirstOrDefault(a => a.Wielded); - var use = wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType) + var use = wielded != null && MissileAmmo.CanShoot(lt, wielded.AmmoType) ? wielded : MissileAmmo.Choose(lt, c.Element, pack, rank); if (use == null) @@ -182,41 +226,67 @@ public partial class CombatManager private enum AmmoPrep { Ready, Busy, Blocked } /// - /// Step 2: called right before a launcher wield is sent. Ready: send it. Busy: ammo of the - /// wrong type is on its way into the pack (wait). Blocked: it can't be put away now (no pack - /// room, or resting after failed tries); don't send the launcher, the server would refuse it. - /// Also arms step 3 when a fitting stack is in the pack. + /// Step 2: called right before a launcher (or thrown weapon) wield is sent. Ready: send it. + /// Busy: ammo that must come off is on its way into the pack (wait). Blocked: it can't be put + /// away now (no pack room, or resting after failed tries); don't send the wield, the server + /// would refuse it. Also arms step 3's swap window when a stack it can shoot is in the pack. /// private AmmoPrep PrepareAmmoFor(int launcherId) { - int lt = LauncherTypeOf(_worldFilter[launcherId]); - if (lt == 0) return AmmoPrep.Ready; + var lwo = _worldFilter[launcherId]; + int lt = LauncherTypeOf(lwo); + bool thrown = lt == 0 && IsThrownWeapon(lwo); + if (lt == 0 && !thrown) return AmmoPrep.Ready; // a launcher of no known type: ammo left alone, as before DateTime now = RynthClock.Now; var pack = PackAmmo(); var wielded = pack.FirstOrDefault(a => a.Wielded); - if (wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType)) + if (!thrown && wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType)) { - _ammoDequipPendingId = 0; _ammoDequipTries = 0; _ammoOffSeenAt = DateTime.MinValue; + ClearAmmoDequip(); return AmmoPrep.Ready; // same ammo type: it stays } - if (pack.Any(a => !a.Wielded && MissileAmmo.Fits(lt, a.AmmoType))) + if (!thrown && pack.Any(a => !a.Wielded && MissileAmmo.CanShoot(lt, a.AmmoType))) ArmAmmoFollowUp(launcherId, now); - if (wielded == null) - { - // Our own dequip just landed: a short settle, then the swap gate is told the move is - // done so the launcher goes on the server's answers rather than its full 3 s. - if (_ammoDequipPendingId != 0) - { - if (_ammoOffSeenAt == DateTime.MinValue) _ammoOffSeenAt = now; - if ((now - _ammoOffSeenAt).TotalMilliseconds < AmmoOffSettleMs) return AmmoPrep.Busy; - _weaponSwapGate?.MoveDone(_ammoDequipPendingId); - } - _ammoDequipPendingId = 0; _ammoDequipTries = 0; _ammoOffSeenAt = DateTime.MinValue; - return AmmoPrep.Ready; - } + if (wielded == null) return AmmoOffSettled(now) ? AmmoPrep.Ready : AmmoPrep.Busy; - // Ammo of another type is wielded: into the pack first. + // Ammo of another type (or of none) is wielded, or any ammo before a thrown weapon: into the pack first. + // Ammo of no type taken off a launcher is that launcher's: the new one picks it last. + if (!thrown && wielded.Untyped) { _ammoTakenOffId = wielded.Id; _ammoTakenOffFor = launcherId; } + return PutAmmoAway(wielded, launcherId, + thrown ? $"before wielding the thrown weapon 0x{(uint)launcherId:X8} '{WeaponName(launcherId)}'" + : $"before wielding 0x{(uint)launcherId:X8} '{WeaponName(launcherId)}'", now); + } + + /// + /// The ammunition slot reads empty. After our own dequip: a short settle, then the swap gate is + /// told the move is done so the next wield goes on the server's answers rather than its full 3 s. + /// True once settled (or nothing of ours was in flight). + /// + private bool AmmoOffSettled(DateTime now) + { + if (_ammoDequipPendingId != 0) + { + if (_ammoOffSeenAt == DateTime.MinValue) _ammoOffSeenAt = now; + if ((now - _ammoOffSeenAt).TotalMilliseconds < AmmoOffSettleMs) return false; + _weaponSwapGate?.MoveDone(_ammoDequipPendingId); + } + ClearAmmoDequip(); + return true; + } + + private void ClearAmmoDequip() + { + _ammoDequipPendingId = 0; _ammoDequipTries = 0; _ammoDequipFor = 0; _ammoOffSeenAt = DateTime.MinValue; + } + + /// + /// Puts the wielded into a pack: one move in flight (Busy until it + /// reads off or passes), tries, + /// then Blocked for 2 min. Blocked too with no pack room. + /// + private AmmoPrep PutAmmoAway(AmmoCandidate wielded, int forId, string why, DateTime now) + { if (_ammoDequipPendingId == wielded.Id && (now - _ammoDequipAt).TotalMilliseconds < AmmoDequipResolveMs) return AmmoPrep.Busy; if (now < _ammoDequipRestUntil) return AmmoPrep.Blocked; @@ -224,14 +294,15 @@ public partial class CombatManager { _ammoDequipTries = 0; _ammoDequipPendingId = 0; + _ammoDequipFor = 0; _ammoDequipRestUntil = now.AddMinutes(2); - _host.Log($"[EquipDiag] {MissileAmmo.Label(wielded.AmmoType)} 0x{(uint)wielded.Id:X8} '{wielded.Name}' didn't come off after {AmmoDequipMaxTries} tries — not swapping to 0x{(uint)launcherId:X8} '{WeaponName(launcherId)}' for 2 min"); + _host.Log($"[EquipDiag] {LabelOf(wielded)} 0x{(uint)wielded.Id:X8} '{wielded.Name}' didn't come off after {AmmoDequipMaxTries} tries — not swapping to 0x{(uint)forId:X8} '{WeaponName(forId)}' for 2 min"); return AmmoPrep.Blocked; } int packId = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1); if (packId == 0 || !_host.HasMoveItemInternal) { - if (packId == 0) WorldObjectCache.WarnPackFull(_host, $"can't put the {MissileAmmo.Label(wielded.AmmoType)} away to switch launchers"); + if (packId == 0) WorldObjectCache.WarnPackFull(_host, $"can't put the {LabelOf(wielded)} away to switch launchers"); return AmmoPrep.Blocked; } if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-ammo-dequip")) return AmmoPrep.Busy; @@ -241,15 +312,18 @@ public partial class CombatManager _host.MoveItemInternal(unchecked((uint)wielded.Id), unchecked((uint)packId), 0, amount); _weaponSwapGate?.NoteMove(wielded.Id, wieldedNow: true); _ammoDequipPendingId = wielded.Id; + _ammoDequipFor = forId; _ammoDequipAt = now; _ammoDequipTries++; _ammoOffSeenAt = DateTime.MinValue; // No _lastEquipTime stamp: its 2 s equip pacing would hold the launcher after the ammo is // already off. Busy above (until it reads off and settles) does the waiting instead. - _host.Log($"[EquipDiag] {MissileAmmo.Label(wielded.AmmoType)} 0x{(uint)wielded.Id:X8} '{wielded.Name}' x{amount} -> pack 0x{(uint)packId:X8} before wielding 0x{(uint)launcherId:X8} '{WeaponName(launcherId)}' (try {_ammoDequipTries}/{AmmoDequipMaxTries})"); + _host.Log($"[EquipDiag] {LabelOf(wielded)} 0x{(uint)wielded.Id:X8} '{wielded.Name}' x{amount} -> pack 0x{(uint)packId:X8} {why} (try {_ammoDequipTries}/{AmmoDequipMaxTries})"); return AmmoPrep.Busy; } + private static string LabelOf(AmmoCandidate a) => a.Untyped ? "ammo" : MissileAmmo.Label(a.AmmoType); + private void ArmAmmoFollowUp(int launcherId, DateTime now) { if (_ammoFollowUpFor == launcherId && now < _ammoFollowUpUntil) return; @@ -266,12 +340,14 @@ public partial class CombatManager /// Missile/peace/Melee for the whole swap; it also stayed the outstanding server action for /// 2 s, which held the swap gate at its full 3 s per step (2026-10-11 14:45:11-17). Once the /// launcher reads in hand, the wielded branch sends the stance after the ammo is on. - /// Thrown weapons and launchers of an unknown type: false (as before). + /// A thrown weapon: only while ammo is on its way into the pack for it. A launcher of an + /// unknown type: false (as before). /// private bool LauncherSwapHoldsStance(int launcherId) { - int lt = LauncherTypeOf(_worldFilter[launcherId]); - if (lt == 0) return false; + var lwo = _worldFilter[launcherId]; + int lt = LauncherTypeOf(lwo); + if (lt == 0) return _ammoDequipPendingId != 0 && IsThrownWeapon(lwo); if (_ammoDequipPendingId != 0) return true; // old ammo going into the pack if (_ammoFollowUpFor == launcherId && AmmoSwapInProgress) return true; // its ammo goes on once it lands if (SwapTracker.PendingId == launcherId) return true; // its wield is in flight @@ -281,40 +357,82 @@ public partial class CombatManager /// /// Step 3, with confirmed in hand. True while the attack should - /// wait for the ammo wield. Only after combat's own launcher swap: an empty quiver otherwise is - /// left to ammo crafting (which may craft better ammo first), as before. + /// wait for an ammo step (the wrong ammo going into the pack, the new stack's wield in flight). + /// : ammo the launcher can shoot is on (or, for a thrown weapon or a + /// launcher of unknown type, any ammo reads wielded, as before). With neither, no attack and no + /// Missile stance go out (the caller holds the tick). /// - private bool AmmoFollowUp(int launcherId, WorldObject target, MonsterRule? rule) + private bool AmmoFollowUp(int launcherId, WorldObject target, MonsterRule? rule, out bool canShoot) { - if (_ammoFollowUpFor == 0) return false; + canShoot = false; DateTime now = RynthClock.Now; - if (_ammoFollowUpFor != launcherId || now >= _ammoFollowUpUntil) { EndAmmoFollowUp(); return false; } var wo = _worldFilter[launcherId]; int lt = LauncherTypeOf(wo); - if (wo == null || lt == 0) { EndAmmoFollowUp(); return false; } - - SwapTracker.Confirmed(launcherId, now); // the launcher landed + // Combat's own swap to this launcher (PrepareAmmoFor armed it): the launcher landed. + bool swapped = _ammoFollowUpFor == launcherId && now < _ammoFollowUpUntil; + if (_ammoFollowUpFor != 0 && !swapped) EndAmmoFollowUp(); + if (wo == null || lt == 0) + { + canShoot = HasWieldedAmmo(); // thrown (its own ammo), or a type not known: as before + return false; + } + if (swapped) SwapTracker.Confirmed(launcherId, now); FoldServerAnswer(AmmoTracker, now); var pack = PackAmmo(); - var wielded = pack.FirstOrDefault(a => a.Wielded); - if (wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType)) + // A stack it can shoot first: a stowed one whose stale record still reads wielded must not hide it. + var wielded = pack.FirstOrDefault(a => a.Wielded && MissileAmmo.CanShoot(lt, a.AmmoType)) ?? pack.FirstOrDefault(a => a.Wielded); + if (wielded != null && MissileAmmo.CanShoot(lt, wielded.AmmoType)) { + bool ours = swapped || AmmoTracker.PendingId != 0; AmmoTracker.Confirmed(wielded.Id, now); - _host.Log($"[EquipDiag] ammo in: 0x{(uint)wielded.Id:X8} '{wielded.Name}' for 0x{(uint)launcherId:X8} '{wo.Name}'"); + if (ours) _host.Log($"[EquipDiag] ammo in: 0x{(uint)wielded.Id:X8} '{wielded.Name}' for 0x{(uint)launcherId:X8} '{wo.Name}'"); EndAmmoFollowUp(); + ClearAmmoDequip(); + _noAmmoSaid.Remove(launcherId); + canShoot = true; return false; } - var pick = MissileAmmo.Choose(lt, LauncherElement(launcherId, wo), pack, AmmoRank(RuleElementOf(rule), WeaknessFor(target))); + // Our own dequip for another launcher's swap is still on its way: that swap goes on. + if (_ammoDequipPendingId != 0 && _ammoDequipFor != launcherId + && (now - _ammoDequipAt).TotalMilliseconds < AmmoDequipResolveMs + AmmoOffSettleMs) + return true; + + if (wielded != null) + { + // The wrong ammo is on (another launcher's, after a swap by hand or a meta): it goes into the + // pack first, the server refuses ammo of another type with this launcher in hand. + var prep = PutAmmoAway(wielded, launcherId, $"for 0x{(uint)launcherId:X8} '{wo.Name}' in hand", now); + if (prep == AmmoPrep.Blocked) + { + SayNoAmmo(launcherId, wo.Name, lt, $"the {LabelOf(wielded)} on ('{wielded.Name}') won't come off"); + return false; + } + return true; + } + if (!AmmoOffSettled(now)) return true; + + // An item reads in the ammunition slot that the pack walk can't place (no slot or type read): + // leave it alone, as before. + if (AmmoTracker.PendingId == 0 && HasWieldedAmmo()) { canShoot = true; return false; } + + var usable = pack.Where(a => !AmmoTracker.Resting(a.Id, now)).ToList(); + var pick = MissileAmmo.Choose(lt, LauncherElement(launcherId, wo), usable, AmmoRank(RuleElementOf(rule), WeaknessFor(target)), + demoteId: _ammoTakenOffFor == launcherId ? _ammoTakenOffId : 0); if (pick == null) { - _host.Log($"[EquipDiag] no {MissileAmmo.Label(lt)} left for 0x{(uint)launcherId:X8} '{wo.Name}' — leaving it to ammo crafting"); EndAmmoFollowUp(); + SayNoAmmo(launcherId, wo.Name, lt, usable.Count < pack.Count ? "the ammo there didn't wield" : ""); return false; } - var step = AmmoTracker.Next(pick.Id, wielded?.Id ?? 0, now, WeaponName); + // Ammo crafting wielded some a moment ago: give the server time to answer it. + if (!swapped && AmmoTracker.PendingId == 0 && AmmoWieldedElsewhereAt is { } elsewhere + && (now - elsewhere()).TotalMilliseconds < AmmoElsewhereGraceMs) + return true; + + var step = AmmoTracker.Next(pick.Id, 0, now, WeaponName); if (AmmoTracker.Notice != null) { _host.Log($"[EquipDiag] {AmmoTracker.Notice}"); @@ -329,12 +447,13 @@ public partial class CombatManager _host.UseFor(unchecked((uint)pick.Id), "Combat", "ammo for the missile weapon"); if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq; if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq; - AmmoTracker.Sent(pick.Id, wielded?.Id ?? 0, now); + AmmoTracker.Sent(pick.Id, 0, now); _lastEquipTime = now; - _host.Log($"[EquipDiag] ammo: wielding 0x{(uint)pick.Id:X8} '{pick.Name}' for 0x{(uint)launcherId:X8} '{wo.Name}' (try {AmmoTracker.TriesFor(pick.Id)}/{AmmoTracker.MaxTries})"); + _host.Log($"[EquipDiag] ammo: wielding 0x{(uint)pick.Id:X8} '{pick.Name}'{(pick.Infinite ? " (infinite)" : "")} for 0x{(uint)launcherId:X8} '{wo.Name}' " + + $"(try {AmmoTracker.TriesFor(pick.Id)}/{AmmoTracker.MaxTries}{(swapped ? "" : ", none it can shoot was on")})"); return true; case WeaponSwapTracker.Step.Hold: - _host.Log($"[EquipDiag] ammo: not wielding 0x{(uint)pick.Id:X8} '{pick.Name}' ({AmmoTracker.HoldReason}) — leaving it to ammo crafting"); + _host.Log($"[EquipDiag] ammo: not wielding 0x{(uint)pick.Id:X8} '{pick.Name}' ({AmmoTracker.HoldReason})"); EndAmmoFollowUp(); return false; default: @@ -342,4 +461,15 @@ public partial class CombatManager return false; } } + + /// No ammo this launcher can shoot: logged and said in chat once (until ammo is on it again). + private void SayNoAmmo(int launcherId, string launcherName, int lt, string why) + { + if (!_noAmmoSaid.Add(launcherId)) return; + string label = MissileAmmo.Label(lt); + string extra = why.Length > 0 ? $" ({why})" : ""; + _host.Log($"[EquipDiag] no {label} it can shoot for 0x{(uint)launcherId:X8} '{launcherName}'{extra} — holding its attacks"); + string crafting = _settings.EnableMissileCrafting ? " Missile crafting will try to make some." : ""; + _host.WriteToChat($"[RynthAi] No {label} for {launcherName}{extra}: not shooting with it.{crafting}", 2); + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ShieldFacing.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ShieldFacing.cs new file mode 100644 index 0000000..fbc63dc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ShieldFacing.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using RynthCore.Plugin.RynthAi.CreatureData; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Damage taken by shield and facing (2026-11-08: does a shield actually cut a boss's hits?). +/// Each monster hit line ("X slashes your leg for N points of slashing damage!") is learned in +/// monster_damage.txt as before (T rows) and, split, as TS rows: was a shield in the off hand in a +/// combat stance, and was the attacker in front of us or behind (ACE counts a shield only within +/// 90 degrees of the facing, Creature_Combat.GetShieldMod). +/// +/// * Shield: the item in the Shield slot (, the engine's +/// EquipmentTracker when it has one) is a shield (), and the stance +/// isn't peace. An off-hand item the cache doesn't know: the hit isn't split (no guess). +/// * Facing: the heading from the pose quaternion (compass, ) and the +/// attacker's position when its line arrives. The line names it, not its object: every live +/// monster of that name within 80 m is measured, and they must all agree, else unknown. +/// * Log: one [Taken] line per monster every 30 s while hits come (never one per hit). +/// +public partial class CombatManager +{ + private static readonly TimeSpan TakenSummaryEvery = TimeSpan.FromSeconds(30); + + /// Hits since the last [Taken] summary, for one monster. + private sealed class TakenTally + { + public string Name = ""; + public int Hits; + public double Damage; + public int ShieldUnread; + // index = (shield ? 0 : 3) + front 0 / behind 1 / unknown 2 + public readonly int[] N = new int[6]; + public readonly double[] Sum = new double[6]; + public readonly double[] Max = new double[6]; + } + + private readonly Dictionary _takenTally = new(); + private DateTime _takenTallySince = DateTime.MinValue; + + private static int TallyIndex(bool shield, HitFacing f) + => (shield ? 0 : 3) + (f == HitFacing.Front ? 0 : f == HitFacing.Behind ? 1 : 2); + + /// + /// A shield counts now: one in the off hand, in a combat stance. False with none (or a + /// dual-wield weapon there, or peace); null when the off-hand item isn't known to the cache. + /// + internal bool? ShieldCountsNow() + { + int off = OffhandInSlot(); + if (off == 0) return false; + var wo = _worldFilter[off]; + if (wo == null) return null; + if (!IsShieldItem(wo)) return false; + if (_host.HasGetCurrentCombatMode && _host.GetCurrentCombatMode() == CombatMode.NonCombat) return false; + return true; + } + + /// Where the monster named stands against our facing now (see the class comment). + internal HitFacing AttackerFacing(string name) + { + if (string.IsNullOrEmpty(name) || !_host.HasGetPlayerPose) return HitFacing.Unknown; + if (!_host.TryGetPlayerPose(out uint pc, out float px, out float py, out _, out float qw, out _, out _, out float qz)) + return HitFacing.Unknown; + double heading = ShieldFacing.CompassFromQuaternion(qw, qz); + var each = new List(2); + foreach (var wo in _worldFilter.GetLandscape()) + { + if (wo.ObjectClass != AcObjectClass.Monster) continue; + if (!string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase)) continue; + if (wo.Id == unchecked((int)_playerId)) continue; + if (_worldFilter.GetHealthRatio(wo.Id) == 0f) continue; // the server said dead + if (!_host.TryGetObjectPosition(unchecked((uint)wo.Id), out uint ac, out float ax, out float ay, out _)) + { + each.Add(HitFacing.Unknown); + continue; + } + double d = ShieldFacing.Distance2D(pc, px, py, ac, ax, ay); + if (!double.IsNaN(d) && d > ShieldFacing.MaxAttackerRange) continue; // too far to be the one + each.Add(ShieldFacing.Classify(heading, pc, px, py, ac, ax, ay)); + } + return ShieldFacing.Agree(each); + } + + /// A monster's hit on us (LearnFromCombatChat): the split row, and the [Taken] summary's tally. + private void LearnTakenSplit(uint wcid, string name, int amount) + { + if (_damageStore == null || amount <= 0) return; + bool? shield = ShieldCountsNow(); + HitFacing facing = AttackerFacing(name); + if (shield.HasValue) _damageStore.RecordTakenSplit(wcid, name, shield.Value, facing, amount); + + DateTime now = RynthClock.Now; + if (_takenTally.Count == 0) _takenTallySince = now; + if (!_takenTally.TryGetValue(wcid, out var t)) _takenTally[wcid] = t = new TakenTally(); + t.Name = name; + t.Hits++; + t.Damage += amount; + if (!shield.HasValue) { t.ShieldUnread++; return; } + int i = TallyIndex(shield.Value, facing); + t.N[i]++; + t.Sum[i] += amount; + if (amount > t.Max[i]) t.Max[i] = amount; + } + + /// Every 30 s (OnHeartbeat): one [Taken] line per monster that hit us since the last one. + private void FlushTakenSummary() + { + if (_takenTally.Count == 0) return; + DateTime now = RynthClock.Now; + if (now - _takenTallySince < TakenSummaryEvery) return; + foreach (string line in TakenSummaryLines(now)) _host.Log(line); + } + + /// The [Taken] lines and a fresh tally (tests call it directly). + internal List TakenSummaryLines(DateTime now) + { + var lines = new List(_takenTally.Count); + double secs = Math.Max(0, (now - _takenTallySince).TotalSeconds); + foreach (var kv in _takenTally) lines.Add(TakenSummaryLine(kv.Value, secs)); + _takenTally.Clear(); + _takenTallySince = now; + return lines; + } + + private static string TakenSummaryLine(TakenTally t, double secs) + { + var ic = CultureInfo.InvariantCulture; + var sb = new StringBuilder(160); + sb.Append("[Taken] ").Append(t.Name).Append(": ").Append(t.Hits.ToString(ic)) + .Append(t.Hits == 1 ? " hit" : " hits").Append(" in ").Append(secs.ToString("0", ic)).Append(" s, ") + .Append(t.Damage.ToString("0", ic)).Append(" damage"); + string[] cell = { "shield front", "shield behind", "shield facing unknown", "no shield front", "no shield behind", "no shield facing unknown" }; + string sep = " - "; + for (int i = 0; i < 6; i++) + { + if (t.N[i] == 0) continue; + sb.Append(sep).Append(cell[i]).Append(' ').Append(t.N[i].ToString(ic)) + .Append(" avg ").Append((t.Sum[i] / t.N[i]).ToString("0", ic)) + .Append(" max ").Append(t.Max[i].ToString("0", ic)); + sep = ", "; + } + if (t.ShieldUnread > 0) + sb.Append(sep).Append(t.ShieldUnread.ToString(ic)).Append(" with the off hand unreadable (not split)"); + return sb.ToString(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.TargetLock.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.TargetLock.cs index 9fc56d4..ade7581 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.TargetLock.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.TargetLock.cs @@ -121,6 +121,7 @@ public partial class CombatManager _lockedPriority = priority; _lockedLastSeen = c; _lockedLastSeenInScan = now; + _lockByPlayer = true; return true; } if (bySelection) @@ -129,6 +130,7 @@ public partial class CombatManager else LockTarget(c, priority, $"target lock: picked by the player, {DescribeTargetPos(fid)}", _lockedTargetId != 0 ? "target lock" : null); + _lockByPlayer = true; // once the player's pick ends, normal priority takes over again return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index f49480e..6b958c2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -161,6 +161,18 @@ public partial class CombatManager : IDisposable // ── Native attack state ────────────────────────────────────── // StartAttackRequest auto-repeats — only call once per target. private uint _nativeAttackTargetId; + // Native attack wedge (2026-11-06, see NativeForThisAttack): the client's own attack state can + // be left stuck by a stance change mid-fight, and then every native attack sends nothing. + private bool _nativeResetPending; // the next swing goes out as the regular attack + private DateTime _lastNativeAttackAt = DateTime.MinValue; + private DateTime _nativeQuietSince = DateTime.MinValue; // first native attack since the last hit, miss or kill + private int _nativeQuietAttacks; + private int _nativeFallbackTargetId; // regular attacks until the target changes + private bool _nativeStanceSeen = true; // last tick was in Melee/Missile (WatchNativeStance) + internal const double NativeResetWindowMs = 5000; // a native attack this recent when the stance left = mid-fight + internal const double NativeFallbackMs = 10_000; // native attacks with no hit, miss or kill this long = fall back + internal const int NativeFallbackAttacks = 4; // ... and at least this many of them + internal const double NativeQuietGapMs = 5000; // no native attack this long: the quiet clock starts over private bool _facingTarget; // True only on attack cycles where an OFFENSIVE damage spell was actually @@ -297,6 +309,8 @@ public partial class CombatManager : IDisposable /// loot. A monster within CloseAttackYards is still fought at once. Null = never hold. /// public Func? HoldNewTarget { get; set; } + /// Why HoldNewTarget holds, for its one log line (null: Boost Loot Priority's words). + public Func? HoldNewTargetWhy { get; set; } private bool _newTargetHeldLogged; /// @@ -689,6 +703,8 @@ public partial class CombatManager : IDisposable private List? _priorityCacheRules; private const double PriorityCacheMs = 1000; private int _lockedPriority; + private (int Locked, int Other) _lockHeldOverLogged; // the last "Target Lock keeps" line (HandleCombatTrigger) + private bool _lockByPlayer; // the lock came from the player's pick (TryLockForcedTarget), not the bot's /// With Target Lock off, an attack at the locked target this recent, with no /// damage landed since, is still on its way: no switch until it lands or this passes. @@ -891,7 +907,9 @@ public partial class CombatManager : IDisposable if (!_newTargetHeldLogged) { _newTargetHeldLogged = true; - _host.Log("[CombatTarget] next target waits: Boost Loot Priority loots the kill first"); + string why = "Boost Loot Priority loots the kill first"; + try { if (HoldNewTargetWhy?.Invoke() is { Length: > 0 } w) why = w; } catch { } + _host.Log("[CombatTarget] next target waits: " + why); } return true; } @@ -1232,6 +1250,12 @@ public partial class CombatManager : IDisposable if (losDebug) LogLosDebug(wo, losBlocked, losDetail); } + // Melee reaches through walls, on both sides: a monster this close is a target when + // melee is, or is about to be, the attack (the owner, 2026-11-06). It was left out while + // hitting the character, who then read as having nothing to fight. + if (losBlocked && dist <= MeleeIgnoresLosWithin && MeleeIsTheAttackOn(wo, attackType)) + losBlocked = false; + // Don't blacklist from scan — just exclude from this result. // Blacklisting only happens when an active target fails LOS during attack. if (losBlocked) @@ -1624,7 +1648,10 @@ public partial class CombatManager : IDisposable uint src = WcidForName(name); if (src == 0) return; if (int.TryParse(m.Groups["n"].Value, out int amount)) + { _damageStore!.RecordTaken(src, name, ElementFromWord(m.Groups["type"].Value), amount); + LearnTakenSplit(src, name, amount); // by shield and facing (CombatManager.ShieldFacing.cs) + } } /// A chat line for the damage meter, the stall watchdog and the environment throttle. @@ -2292,6 +2319,8 @@ public partial class CombatManager : IDisposable _lastSwingEvidenceAt = now; _lastSwingEvidenceKind = kind; _attacksSinceEvidence = 0; + _nativeQuietSince = DateTime.MinValue; // the native attack's quiet clock (NativeForThisAttack) + _nativeQuietAttacks = 0; switch (kind) { case "hit": _lastHitAt = now; break; @@ -2467,6 +2496,16 @@ public partial class CombatManager : IDisposable if (hit) { _consecutiveCastMisses = 0; _magicMissesSinceHit = 0; return; } + // A swing or shot ACE refused in the air (WeenieError 0x4EB since it went out, Player_Melee / + // Player_Missile: IsJumping) never happened: not a no-damage attack. A cast's 0x4EB comes as + // its UseDone and is dropped before it gets here (JudgePendingOffensiveCast). + if (CurrentCombatMode != CombatMode.Magic && InTheAirErrorSince(_pendingJudgeErrSeq)) + { + RefusedCastsNotJudged++; + _host.Log($"[Blacklist] attack at 0x{(uint)tid:X8} refused in the air (0x4EB): not counted as a no-damage attack"); + return; + } + if (CurrentCombatMode == CombatMode.Magic) NoteMagicMissForResync(tid); _consecutiveCastMisses++; if (_consecutiveCastMisses >= _settings.BlacklistAttempts) @@ -2513,11 +2552,13 @@ public partial class CombatManager : IDisposable // A refusal is not a cast (in a client log, three healthy targets were blacklisted 'after 3 // no-damage casts' whose casts had all come back UseDone 0x1D): // the answer 0x1D, or no answer yet while the server is taken as busy, is not judged. - bool refused = _pendingOffensiveErr == ActionPacer.TooBusyErr || (_pendingOffensiveErr < 0 && ActionPacer.ServerBusy); + // So is 0x4EB, "You can't do that while in the air" (a cast sent in a jump). + bool inAir = _pendingOffensiveErr == InTheAirErr; + bool refused = _pendingOffensiveErr == ActionPacer.TooBusyErr || inAir || (_pendingOffensiveErr < 0 && ActionPacer.ServerBusy); if (refused) { RefusedCastsNotJudged++; - _host.Log($"[Blacklist] cast at 0x{(uint)_pendingOffensiveTargetId:X8} {(_pendingOffensiveErr >= 0 ? "refused 'too busy' (UseDone 0x1D)" : "unanswered while the server is busy")}: not counted as a no-damage cast"); + _host.Log($"[Blacklist] cast at 0x{(uint)_pendingOffensiveTargetId:X8} {(inAir ? "refused in the air (UseDone 0x4EB)" : _pendingOffensiveErr >= 0 ? "refused 'too busy' (UseDone 0x1D)" : "unanswered while the server is busy")}: not counted as a no-damage cast"); _pendingOffensiveSpellId = 0; _pendingOffensiveTargetId = 0; _pendingOffensiveCastAt = DateTime.MinValue; @@ -2572,6 +2613,30 @@ public partial class CombatManager : IDisposable _pendingJudgeCastAt = RynthClock.Now; _pendingJudgeTargetId = targetId; _damageSincePendingCast = false; + _pendingJudgeErrSeq = WeenieErrorSeqNow(); + } + + /// WeenieError 0x4EB, "You can't do that while in the air" (ACE WeenieError.YouCantDoThatWhileInTheAir). + internal const uint InTheAirErr = 0x4EB; + + private int _pendingJudgeErrSeq; // the engine's refusal counter when the judged attack was armed + + private int WeenieErrorSeqNow() + { + try { return _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0; } + catch { return 0; } + } + + /// The last refusal the engine saw is 0x4EB and came after . + private bool InTheAirErrorSince(int seqAtArm) + { + try + { + return _host.HasGetLastWeenieError + && _host.TryGetLastWeenieError(out int seq, out uint err, out _, out _) + && seq != seqAtArm && err == InTheAirErr; + } + catch { return false; } } /// @@ -3821,6 +3886,17 @@ public partial class CombatManager : IDisposable _busyGate.Reset(); } + // In the air after a jump-loot pickup's jump: ACE refuses a cast, swing or shot in the + // air (YouCantDoThatWhileInTheAir), so the attack waits for the landing (capped at + // ActionPacer.JumpLandMaxMs). Only the attack: target, approach and stance above go on; + // nothing is stamped, counted or judged for the held tick. + if (ActionPacer.LootJumpAirborne(_host, out _)) + { + LastCombatSkipReason = "loot-jump-air"; // D4 record-only + _tickWait = CombatLatencyTracker.Wait.Busy; + return true; + } + // Magic cadence guard: while a previous combat cast is still // resolving on the ACE server, do NOT turn or issue another cast. // A turn/stop MoveToState (or the next cast's free-hands stop-thunk) @@ -4209,7 +4285,12 @@ public partial class CombatManager : IDisposable ReleaseServerAttack("stall watchdog", log: false); lastAttackCmd = AttackAfterCancel(now); // the attack goes out again once the cancel has landed _ghostCheck.Arm(activeTargetId, now, TargetSpot(activeTargetId)); + _reachWatch.NoteReissue(activeTargetId, currentDist); + // With native attack: as the regular attack, which a stuck client pipeline can't hold (NativeForThisAttack). + bool nativeReset = _settings.UseNativeAttack && _host.HasNativeAttack; + if (nativeReset) _nativeResetPending = true; _host.Log($"{head} re-issue: CancelAttack, attack 0x{activeTargetId:X8} again next cycle" + + (nativeReset ? " as the regular attack" : "") + (_stallWatch.LastFireWasEarly ? $" (early: {stalledMs / 1000:0.0}s with no swing playing and the character standing still)" : "")); return true; } @@ -4218,6 +4299,18 @@ public partial class CombatManager : IDisposable { ReleaseServerAttack("stall watchdog", log: false); int old = activeTargetId; + // The walk to it isn't getting anywhere (a wall between us): leave it, and spare the + // next target the rest of the ladder. See MeleeReachWatch. + if (mode == CombatMode.Melee && _reachWatch.CantReach(old, currentDist, _lastSwingEvidenceAt)) + { + int skipSec = _reachWatch.NoteFailure(old, now); + _blacklistManager.BlacklistFor(old, skipSec); + _stallWatch.EndEpisode(); + _host.Log($"[StallWatch] can't reach 0x{old:X8} '{targetObj.Name}': still {currentDist:0.0} m away after the re-issue (a wall between us?); leaving it {skipSec}s."); + DropTarget($"can't reach it for {skipSec}s"); + lastAttackCmd = now; + return true; + } bool alt = HasAlternateTarget(old); if (alt) _recentlyKilled[old] = now.AddMilliseconds(StallReselectSuppressMs); _host.Log($"{head} re-select: dropping 0x{old:X8} '{targetObj.Name}'" + @@ -4258,6 +4351,7 @@ public partial class CombatManager : IDisposable } private CombatStallWatchdog.StallAction _lastStallStep = CombatStallWatchdog.StallAction.None; + private readonly MeleeReachWatch _reachWatch = new(); /// How long the server has said nothing about : the engine's /// record (plugin API v83) when it has one, else the plugin's own OnUpdateObject/OnCreateObject @@ -4522,7 +4616,8 @@ public partial class CombatManager : IDisposable : _serverAttackTargetId == tid ? "same" : $"0x{_serverAttackTargetId:X8} '{_worldFilter[_serverAttackTargetId]?.Name}' dead={IsKnownDead(_serverAttackTargetId)} {DescribeTargetPos(_serverAttackTargetId)}"; _host.Log($"[StallWatch] attack: lastCmd={Ago(lastAttackCmd)} interval=1000ms lastSkip='{LastCombatSkipReason}' serverTarget={serverTarget} " + - $"rebinds={_attackRebinds} native={(_settings.UseNativeAttack && _host.HasNativeAttack)} " + + $"rebinds={_attackRebinds} native={(_settings.UseNativeAttack && _host.HasNativeAttack)}" + + (_nativeFallbackTargetId != 0 ? " (regular attack this fight)" : "") + " " + $"evidence: hit={Ago(_lastHitAt)} miss={Ago(_lastMissAt)} kill={Ago(_lastKillAt)} (last={_lastSwingEvidenceKind})"); string castGate = _host.HasGetCastBusyState ? (_host.CanCastNow ? "open" : "closed") : "n/a"; @@ -4545,7 +4640,9 @@ public partial class CombatManager : IDisposable public void OnHeartbeat() { + FlushTakenSummary(); // the [Taken] line every 30 s while monsters hit us, macro running or not NoteSwapPortal(); + NoteSwapWieldsSeen(); // The hands swap's steps (weapons back, or the fight's weapons) go before the gates; the macro stopping ends it (freeing the gate). TickRearmSwap(); @@ -4567,6 +4664,7 @@ public partial class CombatManager : IDisposable NotePriorityZeroRules(); LogCombatStateIfChanged(); + WatchNativeStance(); // a stance change mid-fight: the first swing back is the regular attack // Environment-impact throttle: follow our spell projectiles, judge finished casts, and // let go of an approach Think stopped driving. @@ -4715,9 +4813,9 @@ public partial class CombatManager : IDisposable /// Target selection, every tick. Candidates are the top monster-rule Priority among monsters /// inside MonsterRange (or among all scanned ones when none is inside it), ranked by the /// Targeting setting (). Target Lock on: a valid incumbent is kept, - /// full stop. Off: it is kept unless another candidate beats it by the scheme's margin, and - /// never while an attack at it is still in flight. A higher-priority monster in range always - /// takes over at once (the tier filter: the incumbent is no longer a candidate). + /// full stop, a higher priority in range or not (2026-11-07). Off: a higher-priority monster in + /// range takes over at once, and otherwise the incumbent is kept unless another candidate beats + /// it by the scheme's margin, and never while an attack at it is still in flight. /// public void HandleCombatTrigger() { @@ -4791,8 +4889,14 @@ public partial class CombatManager : IDisposable gone = _lockedLastSeenInScan == DateTime.MinValue || inc.Id != _lockedTargetId || (now - _lockedLastSeenInScan).TotalMilliseconds > TARGET_SCAN_GRACE_MS; } + // Target Lock on: a higher priority doesn't take the target either. The lock holds until + // the target dies or leaves Monster Range (the owner, 2026-11-07); with the lock off a + // higher priority in range takes over at once, as before. A lock left over from the + // player's own pick (fight selected, /ra targetlock) isn't the bot's: once that pick ends, + // priority decides again. + bool priorityTakesOver = (!_settings.TargetLock || _lockByPlayer) && _lockedPriority < topPriority; invalidWhy = gone ? "gone" - : _lockedPriority < topPriority ? $"priority {_lockedPriority} < {topPriority}" + : priorityTakesOver ? $"priority {_lockedPriority} < {topPriority}" : inc.Distance > acquireRange ? $"out of Monster Range, {inc.Distance:0.0} m" : _blacklistManager.IsBlacklisted(_lockedTargetId) ? "blacklisted" : _recentlyKilled.ContainsKey(_lockedTargetId) ? "suppressed" @@ -4802,8 +4906,20 @@ public partial class CombatManager : IDisposable string? switchWhy = null; if (_lockedTargetId != 0 && invalidWhy == null) { - // Target Lock on: keep it until it is no longer valid. Nothing to log. - if (_settings.TargetLock || best.Id == _lockedTargetId) return; + // Target Lock on: keep it until it is no longer valid. A higher priority it holds off is + // logged once per pair, so a report shows the lock, not a priority ignored. + if (_settings.TargetLock) + { + if (_lockedPriority < topPriority && best.Id != _lockedTargetId + && _lockHeldOverLogged != (_lockedTargetId, best.Id)) + { + _lockHeldOverLogged = (_lockedTargetId, best.Id); + _host.Log($"[CombatTarget] Target Lock keeps 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' priority {_lockedPriority} " + + $"over 0x{best.Id:X8} '{_worldFilter[best.Id]?.Name}' priority {PriorityOf(best.Id)} (it holds until the target dies or leaves Monster Range)"); + } + return; + } + if (best.Id == _lockedTargetId) return; // Target Lock off: switch only to a clearly better one, and never with an attack // at the incumbent still on its way. @@ -4835,6 +4951,7 @@ public partial class CombatManager : IDisposable private void LockTarget(ScannedTarget best, int bestPriority, string picked, string? switchWhy) { int bestId = best.Id; + _lockByPlayer = false; // TryLockForcedTarget sets it after its own LockTarget _lockWasSwitch = _lockedTargetId != 0 && _lockedTargetId != bestId; // A higher-priority monster that wasn't a candidate (out of sight, past Monster Range, // blacklisted...): named with why, so a report shows whether the priority was ignored. @@ -4886,7 +5003,8 @@ public partial class CombatManager : IDisposable /// reading that as 0 ("at death's door") made every untouched mob look nearly dead, and a /// target's rank collapsed the moment we hit it and its real health arrived: pick, turn, /// hit once, re-pick, turn again (the spin). An un-engaged mob is almost certainly at full - /// health. + /// health. Since 2026-11-07 the engine's monster plates fill the gaps where they can (API v93, + /// ): they probe the other monsters' health from the server. /// internal double SchemeKey(TargetScheme scheme, in ScannedTarget c) => scheme switch { @@ -4898,10 +5016,51 @@ public partial class CombatManager : IDisposable private double HealthOrFull(int id) { - float r = _worldFilter.GetHealthRatio(id); + float r = RankingHealth(id, out _); return r < 0f ? 1.0 : Math.Clamp(r, 0f, 1f); } + /// The engine plates' readings older than this (ms) are not used to rank. + internal const uint PlateHealthMaxAgeMs = 10_000; + /// A plate reading takes over from RynthAi's own server value only when it is this much + /// fresher (ms): the two are the same 0x01C0 for the streamed target, a few ms apart. + internal const double PlateHealthFresherByMs = 500; + + /// + /// The health Lowest health ranks by, -1 = unknown (counted as full). RynthAi's + /// own value (GetHealthRatio: the server's stream for the target it queried, or an estimate from its + /// own splash hits) unless the engine's monster plates (API v93 TryGetMonsterHealth: the server's + /// reading from the plates' round-robin probes, 2026-11-07) know better: + /// * own unknown: the plate reading; + /// * own an estimate: the lower of the two (each misses the damage the other saw); + /// * own a server value: the plate reading when it is clearly fresher. + /// Plate readings older than , or 0 (dead to the plates, not yet to + /// RynthAi), are ignored, and RynthAi's own 0 (the server said dead) always stands. RANKING ONLY: + /// nothing here goes into the cache, fight tracking, kill prediction, damage rows or the dashboard. + /// : the plates' reading decided it (for the log line). + /// + internal float RankingHealth(int id, out bool fromPlates) + { + fromPlates = false; + float own = _worldFilter.GetHealthRatio(id); + if (own == 0f || !_host.HasMonsterHealth) return own; + if (!_host.TryGetMonsterHealth(unchecked((uint)id), out float plate, out uint ageMs)) return own; + if (ageMs > PlateHealthMaxAgeMs || !(plate > 0f)) return own; + + float pick; + if (own < 0f) + pick = plate; + else if (_worldFilter.IsHealthEstimated(id)) + pick = Math.Min(own, plate); + else if (!_worldFilter.TryGetServerHealthTime(id, out DateTime ownAt) + || ageMs + PlateHealthFresherByMs < (TargetClock() - ownAt).TotalMilliseconds) + pick = plate; + else + pick = own; + fromPlates = pick != own; + return pick; + } + /// Ranks ahead of the best so far: a lower key, ties to the /// closer one, then the lower id (so the pick is stable tick to tick). private static bool BetterCandidate(double key, in ScannedTarget c, double bestKey, in ScannedTarget best) @@ -4933,8 +5092,9 @@ public partial class CombatManager : IDisposable switch (scheme) { case TargetScheme.LowestHealth: - float r = _worldFilter.GetHealthRatio(c.Id); - return r < 0f ? "health unknown (as full)" : $"health {Math.Clamp(r, 0f, 1f) * 100:0}%"; + float r = RankingHealth(c.Id, out bool fromPlates); + return r < 0f ? "health unknown (as full)" + : $"health {Math.Clamp(r, 0f, 1f) * 100:0}%" + (fromPlates ? " (the plates' reading)" : ""); case TargetScheme.LeastTurning: return $"turn {c.Angle:0} deg"; default: @@ -5877,7 +6037,9 @@ public partial class CombatManager : IDisposable // The server's own list (v87) says it never reached the hand: the wield can't work // (the client refused it unasked). Out of the choice like a "skill too low" answer, // not retried every 2 minutes with the off hand taken off each time (the Tetsubo, 2026-10-18). - if (SwapTracker.GaveUpId is int gaveUp && EquippedState.TryGet(_host, out _)) + // Only when the list shows it missing now AND it was never seen in a main-hand slot while + // its wields were under way (NeverReachedHand). + if (SwapTracker.GaveUpId is int gaveUp && NeverReachedHand(gaveUp)) NoteSkillTooLow(gaveUp, "it never reached your hand (the client refused the wield)"); } SwapTracker.GaveUpId = null; @@ -5891,6 +6053,41 @@ public partial class CombatManager : IDisposable private DateTime _lastSwapHoldLogAt = DateTime.MinValue; + /// + /// True only when the engine's equipment list can be read, does not hold + /// now, and the swap tracker never saw it in a main-hand slot while its + /// wields were under way (). A readable list alone used to be + /// enough, so a weapon that did reach the hand, and that buffing then swapped out for the wand + /// before combat looked, was left out of the weapon choice for 30 min. A weapon that truly never + /// shows in the list (refused by the client or the server) is still left out. + /// + private bool NeverReachedHand(int id) + { + if (SwapTracker.WasSeenWielded(id)) return false; + EquippedState.Invalidate(); + return EquippedState.TryGet(_host, out var map) && !map.ContainsKey(id); + } + + /// + /// While a combat wield is in flight or has recent tries counted, read the engine's equipment + /// list (API v87, the server's own wield messages) and tell the swap tracker about every item + /// in a main-hand slot (the slots reads; a weapon in the shield + /// slot is not the wield combat asked for). Called every tick by the plugin ahead of its + /// buffing hold, which skips , and from OnHeartbeat itself. Reads + /// only, no game command, and never throws. + /// + internal void NoteSwapWieldsSeen() + { + try + { + if (!SwapTracker.HasAttemptsAt(RynthClock.Now)) return; + if (!EquippedState.TryGet(_host, out var map)) return; + foreach (var kv in map) + if ((kv.Value & MainHandSlots) != 0) SwapTracker.SeenWielded(kv.Key); + } + catch { /* a failed read must never stop the tick */ } + } + /// /// Why a swap the tracker allows should not start now (null = start it). Settling: the /// target was switched to (it replaced another live target) under WeaponSwapSettleMs ago; @@ -5940,7 +6137,7 @@ public partial class CombatManager : IDisposable int lt = LauncherTypeOf(_worldFilter[inHand]); if (lt == 0) return true; var wielded = PackAmmo().FirstOrDefault(a => a.Wielded); - return wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType); + return wielded != null && MissileAmmo.CanShoot(lt, wielded.AmmoType); } // Last swap deferral logged: (chosen, in hand, reason kind) and when. @@ -6324,16 +6521,11 @@ public partial class CombatManager : IDisposable if (alreadyWielded) { - // Just swapped to this launcher: wield its ammo (one in flight, confirmed, capped). - if (desiredMode == CombatMode.Missile && AmmoFollowUp(targetWeaponId, target, rule)) - { - _lastMissileNoAmmoAt = RynthClock.Now; // waiting on ammo is not a stall - LastCombatSkipReason = "no-ammo"; - return false; - } - - // Don't enter missile mode without ammo — AC rejects it and cycles stance - if (desiredMode == CombatMode.Missile && !HasWieldedAmmo()) + // A launcher in hand: ammo it can shoot goes on (after a swap, or whenever the slot holds none + // it can shoot), one in flight, confirmed, capped. Don't enter missile mode without it: AC + // rejects it and cycles stance, and a shot would be a dry fire. + if (desiredMode == CombatMode.Missile + && (AmmoFollowUp(targetWeaponId, target, rule, out bool canShoot) || !canShoot)) { // Waiting on ammo is not a stall. The attack block's stamp is never reached // from here (Think returns on false), so the stall watchdog's no-ammo @@ -6435,9 +6627,19 @@ public partial class CombatManager : IDisposable // a wand in hand in Magic mode was kept whatever the list said (2026-09-30). if (SwapToChosenSameKind(targetWeaponId, desiredMode)) return false; - // The chosen weapon read in hand (the wield-location read was only late): the off hand. - if (InHandWeaponId() == targetWeaponId && OffhandFollowUp(target, rule, targetWeaponId)) - return false; + // The chosen weapon read in hand (the wield-location read was only late): a launcher's ammo, + // then the off hand. + if (InHandWeaponId() == targetWeaponId) + { + if (desiredMode == CombatMode.Missile + && (AmmoFollowUp(targetWeaponId, target, rule, out bool shootable) || !shootable)) + { + _lastMissileNoAmmoAt = RynthClock.Now; + LastCombatSkipReason = "no-ammo"; + return false; + } + if (OffhandFollowUp(target, rule, targetWeaponId)) return false; + } return true; } @@ -6783,6 +6985,22 @@ public partial class CombatManager : IDisposable /// Melee (or peace with a melee weapon) is one chest-to-chest ray. Magic stays a straight /// line with the dungeon silhouette rays, as before. /// + /// The line-of-sight check is skipped for melee within this (same units as Monster Range). + internal const double MeleeIgnoresLosWithin = 4.0; + + /// + /// This monster gets melee: the attack type says so (Melee, or peace with a melee weapon in hand), + /// or the fight's plan picks a melee weapon (a wand still in hand from buffing, about to swap). + /// + private bool MeleeIsTheAttackOn(WorldObject target, TargetingFSM.AttackType attackType) + { + int mode = CurrentCombatMode; + if (mode == CombatMode.Melee || attackType == TargetingFSM.AttackType.Melee) return true; + if (mode == CombatMode.Missile) return false; + int planned = PlanFor(target, GetRuleForTarget(target)).WeaponId; + return planned != 0 && _worldFilter[planned]?.ObjectClass == AcObjectClass.MeleeWeapon; + } + private TargetingFSM.AttackType DetermineAttackTypeForLOS() { if (_raycastSystem?.TargetingFSM == null) return TargetingFSM.AttackType.Linear; @@ -7089,10 +7307,26 @@ public partial class CombatManager : IDisposable // arrows that arrived via OnCreateObject keep WieldedLocation=0 and // never match. The forced refresh adds ~one InqInt call per pack item // but is cheap and fixes detection definitively. + // A launcher of a known ammo type in hand: only ammo it can shoot counts (2026-11-07). Arrows + // left on with a crossbow in hand counted, and a shot went out with nothing it could fire. + int lt = LauncherTypeOf(_worldFilter[InHandWeaponId()]); + bool any = false; foreach (var item in _worldFilter.GetDirectInventory(forceRefresh: true)) - if (LooksLikeWieldedAmmo(item, playerId)) return true; - - return false; + { + if (!LooksLikeWieldedAmmo(item, playerId)) continue; + if (lt == 0) return true; + if (!IsAmmoItem(item)) + { + // In the ammunition slot but nothing else says ammo: its type can't be told, so it counts + // as before. A name match in another slot (a shield named for arrows) doesn't. + if ((WieldedSlotOf(item) & AmmunitionSlot) != 0) any = true; + continue; + } + // Not returned false at once: a stowed stack whose stale record still names the ammunition + // slot must not hide the stack really on. + if (MissileAmmo.CanShoot(lt, AmmoTypeOfItem(item))) return true; + } + return any; } // EquipMask bit for the ammunition slot. Items wielded in this slot are ammo @@ -7143,7 +7377,9 @@ public partial class CombatManager : IDisposable return true; // Name-based fallback for items in non-ammo slots that still match - // ammo names (rare server-custom configurations). + // ammo names (rare server-custom configurations). Never a launcher in hand: one named + // for bolts or arrows is not its own ammo. + if ((loc & MainHandSlots) != 0 && LauncherTypeOf(item) != 0) return false; string n = item.Name; if (string.IsNullOrEmpty(n)) return false; if (n.Contains("Bundle") || n.Contains("Wrapped")) return false; @@ -7204,11 +7440,14 @@ public partial class CombatManager : IDisposable // Native attack: select target, Start fills power bar, End fires the attack. // Called each attack cycle — the client handles turn-to-face naturally. - if (_settings.UseNativeAttack && _host.HasNativeAttack) + // NativeForThisAttack can send one as the regular attack (the setting stays on). + if (_settings.UseNativeAttack && _host.HasNativeAttack && NativeForThisAttack(RynthClock.Now)) { // Marked as RynthAi's own pick: "Fight the monster I select" follows the player's only. ItemInfo.SelfSelect.SelectAsBot(_host, targetId); _host.NativeAttack(acHeight, power); + _lastNativeAttackAt = RynthClock.Now; + _nativeQuietAttacks++; } // Direct attack: raw game action (bypasses client facing) else if (isMissile) @@ -7226,6 +7465,89 @@ public partial class CombatManager : IDisposable catch { return false; } } + // ── Native attack: reset after a stance change, fall back when it stalls ────────── + // 2026-11-06, DreamWeave (a melee character dual-wielding two Hand Wraps): a buff-wand swap + // came 0.5 s after a native attack (BuffPre CancelAttack+StopCompletely, Staff, Magic, casts, + // Hand Wraps back, Melee), and from then on the character never swung again: 45 StallWatch + // episodes in 37 minutes, native=True, "no hit/miss/kill", facing errors up to 180 degrees, + // and the client's attacking flag (the heartbeat's atk=1) never set once. Turning Use Native + // Attack off fought at once. The native attack is the client's own pipeline + // (ClientCombatSystem): its attack-in-progress flag is cleared only by the server's + // AttackDone, and while it is set the client queues every attack instead of sending it. The + // client sets it even when it "attacks" in Peace or Magic, where it sends nothing (a power bar + // or a queued attack finishing after the stance changed), so no AttackDone ever came: every + // native attack after the swap was queued forever. Nothing reached the server, so it never + // swung and never turned the character to the mob (in melee the server does the turning, for + // both paths). The regular attack is the raw game action: the server swings and its AttackDone + // clears the client's flag, which is what turning the setting off did. The engine now clears a + // stuck flag itself (ClientCombatHooks, NativeAttackRearm); this side covers an engine without + // that and anything else that leaves the client's pipeline stuck: + // * a stance change that came mid-fight (a native attack under NativeResetWindowMs before the + // stance left Melee/Missile): the first swing back goes out as the regular attack. Its + // AttackDone resets the client's attack state, and native carries on from the next swing; + // * the stall watchdog's step 1 re-issue goes out as the regular attack the same way; + // * native attacks with no hit, miss or kill for NativeFallbackMs (NativeFallbackAttacks or + // more, across targets): the regular attack for the rest of this fight (this target), + // native again from the next target. Logged once each way. Use Native Attack itself is + // never changed (only the player changes settings). + + /// True: this attack goes out native. False: as the regular attack (see above). + private bool NativeForThisAttack(DateTime now) + { + if (_nativeFallbackTargetId != 0) + { + if (activeTargetId == _nativeFallbackTargetId) return false; + _nativeFallbackTargetId = 0; + _nativeQuietSince = DateTime.MinValue; + _nativeQuietAttacks = 0; + _host.Log($"[Combat] native attack again: a new fight (0x{activeTargetId:X8} '{_worldFilter[activeTargetId]?.Name}')"); + } + + if (_nativeResetPending) + { + _nativeResetPending = false; + _host.Log($"[Combat] native attack: this swing at 0x{activeTargetId:X8} goes out as the regular attack " + + "(after a stance change mid-fight or a stall re-issue; the server's answer resets the client's attack state)"); + return false; + } + + if (_nativeQuietSince == DateTime.MinValue || (now - _lastNativeAttackAt).TotalMilliseconds > NativeQuietGapMs) + { + _nativeQuietSince = now; + _nativeQuietAttacks = 0; + } + double quietMs = (now - _nativeQuietSince).TotalMilliseconds; + if (_nativeQuietAttacks >= NativeFallbackAttacks && quietMs >= NativeFallbackMs) + { + _nativeFallbackTargetId = activeTargetId; + _host.Log($"[Combat] native attack isn't landing (no hit, miss or kill in {quietMs / 1000:0} s over {_nativeQuietAttacks} attacks); " + + "using the regular attack until the next fight"); + return false; + } + return true; + } + + /// + /// Every combat tick (OnHeartbeat): a stance change out of Melee/Missile that came mid-fight + /// (a native attack under before it) makes the first swing + /// back the regular attack (see NativeForThisAttack). + /// + private void WatchNativeStance() + { + int mode = CurrentCombatMode; + bool attackStance = mode == CombatMode.Melee || mode == CombatMode.Missile; + if (attackStance == _nativeStanceSeen) return; + _nativeStanceSeen = attackStance; + if (attackStance || !_settings.UseNativeAttack || _lastNativeAttackAt == DateTime.MinValue) return; + if ((RynthClock.Now - _lastNativeAttackAt).TotalMilliseconds < NativeResetWindowMs) + _nativeResetPending = true; + } + + /// Host tests: the native attack has fallen back to the regular one for this fight. + internal bool NativeFallbackActive => _nativeFallbackTargetId != 0; + /// Host tests: the next swing goes out as the regular attack. + internal bool NativeResetPending => _nativeResetPending; + // ══════════════════════════════════════════════════════════════════════════ // MAGIC COMBAT SYSTEM // ══════════════════════════════════════════════════════════════════════════ @@ -8195,8 +8517,14 @@ public partial class CombatManager : IDisposable // Ring override: when UseRing is enabled, check if enough monsters are within // ring range. If so, upgrade to ring; otherwise keep the base shape (arc/streak/blast/bolt). - bool ringDue = rule != null && rule.UseRing && _settings.RingRange > 0 - && (RingCountOverride?.Invoke() ?? CountMonstersInRange(_settings.RingRange)) >= Math.Max(1, _settings.MinRingTargets); + bool ringOn = rule != null && rule.UseRing; + int ringNear = -1; + bool ringDue = false; + if (ringOn && _settings.RingRange > 0) + { + ringNear = RingCountOverride?.Invoke() ?? CountMonstersInRange(_settings.RingRange); + ringDue = ringNear >= Math.Max(1, _settings.MinRingTargets); + } // Like a wall, a ring is due only when one is known: a caster with Use Ring on and no ring // learned used to cast nothing once a pack came into ring range and stood in the fight // ("No spell found: elem=Nether", #rynth-issues 2026-10-23, DreamWeave). Without one, the @@ -8208,10 +8536,16 @@ public partial class CombatManager : IDisposable if (ringId == 0) { ringDue = false; - if (_noRingLogged.Add(element + (useVoid ? "/void" : ""))) - _host.Log($"[CombatCast] no {element} ring spell known{(useVoid ? " (Void: Clouded Soul, Clouded Soul II, Ring of Skulls II)" : "")}: casting the rule's other shape when a ring is due"); + // Said for the cast itself only: the element probes (Auto's weakness pick, the + // wand-in-hand check) ask every element, and used to report rings of elements + // that were never going to be cast. + if (arcTargetId != 0) ReportNoRingKnown(element, skill, useVoid); } } + // A rule with Ring on that casts no ring says why in the log (2026-11-06: "it doesn't like + // to use rings even when set" - nothing said that too few monsters were near). + if (ringOn && arcTargetId != 0 && ringId == 0) + NoteRingNotCast(rule!, ringNear, ringDue); // Wall override (Wall Range on): a wall when enough monsters are in its path toward the // target and the character knows a wall of this element (none for Nether). Asked only for a @@ -8288,11 +8622,80 @@ public partial class CombatManager : IDisposable private int FindRingSpell(string element, AcSkillType skill, bool useVoid) { if (!TryGetShapeBase(element, ShapeRing, useVoid, out string ringBase, out string? ringT7, out bool forcedWar)) return 0; - if (forcedWar) skill = AcSkillType.WarMagic; + // War has no row for this element (Nether for a caster without Void Magic): its bolts are + // Fire's (TryGetShapeBase), and so are its rings. The ring used to be looked up under the + // element itself, which has no War ring, so such a caster never rang (2026-11-06). + if (forcedWar) { skill = AcSkillType.WarMagic; element = "Fire"; } int id = FindBestRingSpell(element, skill); return id != 0 ? id : FindBestOffensiveSpellId(ringBase, skill, ringT7); } + /// + /// A ring was due but none of is known: the file log says so once + /// per element, with the reason (the tier, the spellbook not read yet, or the rings tried); + /// the chat at most every per element. For the cast + /// itself only, never an element probe. + /// + private void ReportNoRingKnown(string element, AcSkillType skill, bool useVoid) + { + string why = RingMissingReason(element, skill, useVoid); + if (_noRingLogged.Add(element + (useVoid ? "/void" : ""))) + _host.Log($"[CombatCast] no {element} ring spell known ({why}): casting the rule's other shape when a ring is due"); + DateTime nowRing = RynthClock.Now; + if (!_ringMissingChatAt.TryGetValue(element, out DateTime lastRing) + || (nowRing - lastRing).TotalMilliseconds >= NoSpellChatIntervalMs) + { + _ringMissingChatAt[element] = nowRing; + _host.WriteToChat($"[RynthAi] Ring spell not found for {element} ({why})", 2); + } + } + + /// Why no ring of was found: "War Magic tier 4: rings are + /// level 5 and 7", "the spellbook isn't read yet", or "tried: Halo of Frost II, Halo of Frost". + internal string RingMissingReason(string element, AcSkillType skill, bool useVoid) + { + if (!useVoid && !SpellShapes.ContainsKey(element)) { skill = AcSkillType.WarMagic; element = "Fire"; } + string school = skill == AcSkillType.VoidMagic ? "Void Magic" : "War Magic"; + int tier = EffectiveMaxTier(skill); + if (tier < 5) return $"{school} tier {tier}: rings are level 5 and 7"; + if (_spellManager != null && !_spellManager.IsKnownSnapshotWarm) return "the spellbook isn't read yet"; + if (skill == AcSkillType.VoidMagic) + return $"tried: {string.Join(", ", VoidRingsLevel7)}, {VoidRingLevel5}"; + if (!RingLoreNames.TryGetValue(element, out string[]? lore) || lore.Length < 2) return "War has no ring of this element"; + string plain = PlainRings.TryGetValue(element, out string? p) ? ", " + p : ""; + return tier >= 7 ? $"tried: {lore[1]}, {lore[0]}{plain}" : $"tried: {lore[0]}{plain}; {lore[1]} is level 7"; + } + + // Why a rule with Ring on cast no ring (2026-11-06): the log says it when the reason changes and + // then at most every RingNotCastLogMs per rule and reason, never every attack. + internal const double RingNotCastLogMs = 30_000; + private readonly Dictionary _ringNotCastLoggedAt = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _ringOffLogged = new(StringComparer.OrdinalIgnoreCase); + + /// + /// A real cast under a rule with Ring on, and no ring this time: Ring Range 0 (rings off, said + /// once per rule), or fewer than Min Ring Targets monsters within Ring Range (the count is + /// said). A ring that was due but isn't known is 's. + /// + private void NoteRingNotCast(MonsterRule rule, int near, bool countMet) + { + string name = rule.Name ?? ""; + if (_settings.RingRange <= 0) + { + if (_ringOffLogged.Add(name)) + _host.Log($"[CombatCast] rule '{name}' has Ring on, but Ring Range is {_settings.RingRange}: rings are off (Settings > Ring Range)"); + return; + } + int need = Math.Max(1, _settings.MinRingTargets); + if (countMet || near >= need) return; // the count was met: no ring known (ReportNoRingKnown) + string key = name + "|count"; + DateTime now = TargetClock(); + if (_ringNotCastLoggedAt.TryGetValue(key, out DateTime last) && (now - last).TotalMilliseconds < RingNotCastLogMs) return; + _ringNotCastLoggedAt[key] = now; + _host.Log($"[CombatCast] rule '{name}' has Ring on: no ring yet, {near} monster{(near == 1 ? "" : "s")} within Ring Range " + + $"{_settings.RingRange} and Min Ring Targets is {need} (counted from the character, the target included)"); + } + private int FindBestRingSpell(string element, AcSkillType skill) { if (skill == AcSkillType.VoidMagic) @@ -8337,17 +8740,8 @@ public partial class CombatManager : IDisposable } } - // Reached from every element probe (CanCastElement inside GetPreferredElement) as well - // as the cast itself, several times per attack cycle while a pack stands in ring range: - // say it (chat + file log) once per element per NoSpellChatIntervalMs. - DateTime nowRing = RynthClock.Now; - if (!_ringMissingChatAt.TryGetValue(element, out DateTime lastRing) - || (nowRing - lastRing).TotalMilliseconds >= NoSpellChatIntervalMs) - { - _ringMissingChatAt[element] = nowRing; - _host.WriteToChat($"[RynthAi] Ring spell not found for {element} (tried: {loreNames[1]}, {loreNames[0]})", 2); - _host.Log($"[CombatCast] ring spell not found for {element} (tried: {loreNames[1]}, {loreNames[0]})"); - } + // None known: the cast's caller says why (ReportNoRingKnown). This is reached from every + // element probe as well, which used to chat about rings of elements never cast. return 0; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs index 88747c2..b1761bf 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs @@ -147,6 +147,10 @@ internal sealed class CombatStallWatchdog /// step still settling (the step-4 re-wield), so the hold isn't read as a tick gap. public void Hold(DateTime now) => _lastTick = now; + /// The stall is explained and dealt with (a target it can't reach): the next target + /// starts from step 1, not from where this one left the ladder. + public void EndEpisode() => ResetEpisode(); + private StallAction Fire(DateTime now) { _step++; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MeleeReachWatch.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MeleeReachWatch.cs new file mode 100644 index 0000000..8754ae4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MeleeReachWatch.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +// A melee target the server can't walk us to (2026-11-06, Olthoi beside a wall, flight recorder +// 19:09-19:12): each attack came back as a MoveToObject to a mob 4.5 m off with a wall between, +// so the character ran on the spot against the wall and never swung, while the mob's own reach +// went through and hit him about once a second. The stall ladder then took him to peace and took +// his weapon off, which costs spells and can't help: nothing is wrong with the client. +// +// The rule: the step-1 re-issue has had its 3 s to walk (at 3 m/s that closes 9 m) and the target +// is no closer and not next to us. That target is left for a while, longer each time. +// +// A wedged client also doesn't close on anything, and the ladder is what recovers that. So the +// rule gives way once MaxStreak targets in a row failed with no swing in between. +internal sealed class MeleeReachWatch +{ + /// At or under this we are next to it: a stall here is not about walking. + public const double NextToM = 2.0; + /// The re-issue must close at least this much for the walk to count as working. + public const double MustCloseM = 0.75; + public const int FirstSkipSec = 60; + public const int MaxSkipSec = 300; + public const int MaxStreak = 5; + + private readonly Dictionary _failures = new(); + private int _reissueTarget; + private double _reissueDist; + private int _streak; + private DateTime _lastFailureAt = DateTime.MinValue; + + /// Step 1 went out: the walk is measured from here. + public void NoteReissue(int targetId, double dist) + { + _reissueTarget = targetId; + _reissueDist = dist; + } + + /// At step 2: true when the target can't be reached. + public bool CantReach(int targetId, double dist, DateTime lastSwingEvidenceAt) + { + if (lastSwingEvidenceAt > _lastFailureAt) _streak = 0; // something swung since: not a wedge + if (targetId == 0 || targetId != _reissueTarget) return false; + if (dist <= NextToM) return false; + if (dist <= _reissueDist - MustCloseM) return false; + return _streak < MaxStreak; + } + + /// Records the failure. Returns how long to leave the target: 60 s, doubling to 5 min. + public int NoteFailure(int targetId, DateTime now) + { + _streak++; + _lastFailureAt = now; + _reissueTarget = 0; + _failures.TryGetValue(targetId, out int n); + _failures[targetId] = n + 1; + long secs = (long)FirstSkipSec << Math.Min(n, 8); + return (int)Math.Min(secs, MaxSkipSec); + } + + /// It took a hit or died: it can be reached after all, or its id is free again. + public void Forget(int targetId) => _failures.Remove(targetId); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileAmmo.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileAmmo.cs index e473416..afb62cb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileAmmo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileAmmo.cs @@ -4,16 +4,20 @@ using System.Collections.Generic; namespace RynthCore.Plugin.RynthAi; /// One stack of arrows, quarrels or darts the character carries. -/// AC AmmoType (int 50): 1 arrow, 2 quarrel, 4 dart; 0 = not known. +/// AC AmmoType (int 50): 1 arrow, 2 quarrel, 4 dart; 0 = none (an ammunition-slot +/// item with no AmmoType and no ammo name: a server's own ammo, see ). /// Normalized element ("" = none known). /// Takes the launcher's element (DamageType Base, or named Prismatic). /// AmmoRecipes rank: Deadly beats Greater beats plain; 1 for ammo no recipe makes. /// Position in the Items list; -1 = not listed. /// In the ammunition slot now. +/// Never runs out (UnlimitedUse, or a single item that doesn't stack): see . internal sealed record AmmoCandidate(int Id, string Name, int AmmoType, string Element, bool Prismatic, - int Quality, int ListIndex, bool Wielded) + int Quality, int ListIndex, bool Wielded, bool Infinite = false) { public bool Listed => ListIndex >= 0; + /// No AmmoType: fits any launcher in hand, but must come off before a launcher is wielded. + public bool Untyped => AmmoType == 0; } /// @@ -23,6 +27,9 @@ internal sealed record AmmoCandidate(int Id, string Name, int AmmoType, string E /// and crystal / chorizite variants. The server refuses to wield a launcher while ammo of /// another type is in the ammunition slot (0x00800000), and refuses ammo that doesn't match /// the launcher in hand. So a bow-to-crossbow swap must take the arrows off first. +/// * The ammo check is skipped when either side has no AmmoType, the launcher check is not: ammo +/// with none goes on with any launcher in hand, but must come off before a launcher is wielded +/// (2026-11-07, servers' custom infinite ammo). /// * Thrown weapons (stackable, in the missile-weapon slot) are their own ammo: no AmmoType rule. /// * A launcher's missile damage takes the AMMO's element. Prismatic ammo (DamageType Base) /// takes the launcher's element instead (Pierce when the launcher has none). @@ -77,9 +84,38 @@ internal static class MissileAmmo _ => "arrows", }; - /// The server's rule: the types must be equal (a crystal arrow is not an arrow). + /// + /// The server's rule for wielding a launcher: the ammo already on must be of the launcher's type + /// (a crystal arrow is not an arrow). Ammo with no AmmoType does not fit: ACE compares the + /// launcher's type with the ammo's (none), so it must come off first. + /// public static bool Fits(int launcherType, int ammoType) => launcherType != 0 && ammoType == launcherType; + /// + /// The launcher in hand can shoot it: ammo of its type, or ammo with no AmmoType at all (ACE checks + /// ammo going into the ammunition slot against the launcher only when both have a type). Custom + /// infinite ammo is sometimes made that way. + /// + public static bool CanShoot(int launcherType, int ammoType) => launcherType != 0 && (ammoType == launcherType || ammoType == 0); + + /// PropertyBool UnlimitedUse: ammo the server never uses up (ACE Player_Missile.UpdateAmmoAfterLaunch). + public const uint PropUnlimitedUse = 63; + + /// + /// Ammo that never runs out: UnlimitedUse (known once the item is appraised), or a single item that + /// doesn't stack (every ammo the game drops or crafts stacks), or named so. Servers make their + /// infinite ammo these ways; a single custom arrow that is used up costs one shot, then the next pick. + /// + public static bool LooksInfinite(bool unlimitedUse, int stackSize, int maxStackSize, string? name) + { + if (unlimitedUse) return true; + if (maxStackSize <= 1 && stackSize <= 1) return true; + string n = name ?? ""; + return n.IndexOf("Infinite", StringComparison.OrdinalIgnoreCase) >= 0 + || n.IndexOf("Unlimited", StringComparison.OrdinalIgnoreCase) >= 0 + || n.IndexOf("Endless", StringComparison.OrdinalIgnoreCase) >= 0; + } + /// Prismatic: DamageType has the Base bit, or the name says so. public static bool IsPrismatic(int? damageType, string? name) => (damageType is int dt && (dt & DamageTypeBase) != 0) @@ -97,23 +133,29 @@ internal static class MissileAmmo /// /// The stack to wield in 's launcher, null when the pack has - /// none that fits. Order: + /// none it can shoot (). Order: /// 1. listed ammo (the Items list) before anything else; - /// 2. the element: (lower = better) of the element the + /// 2. infinite ammo (it never runs out, owner 2026-11-07) before ammo that is used up; + /// 3. ammo of the launcher's own type before ammo with no AmmoType, and of those, not + /// (the stack just taken off the other launcher: it is that one's); + /// 4. the element: (lower = better) of the element the /// launcher would do with it; ammo of no known element counts as Pierce; - /// 3. quality (Deadly > Greater > plain), then the stack already wielded, then list / pack order. + /// 5. quality (Deadly > Greater > plain), then the stack already wielded, then list / pack order. /// public static AmmoCandidate? Choose(int launcherType, string launcherElement, IReadOnlyList pack, - Func elementRank) + Func elementRank, int demoteId = 0) { AmmoCandidate? best = null; - (int, int, int, int, int) bestKey = default; + (int, int, int, int, int, int, int, int) bestKey = default; for (int i = 0; i < pack.Count; i++) { var a = pack[i]; - if (!Fits(launcherType, a.AmmoType)) continue; + if (!CanShoot(launcherType, a.AmmoType)) continue; string e = EffectiveElement(a, launcherElement); var key = (a.Listed ? 0 : 1, + a.Infinite ? 0 : 1, + a.Untyped ? 1 : 0, + demoteId != 0 && a.Id == demoteId ? 1 : 0, elementRank(e.Length > 0 ? e : "Pierce"), -a.Quality, a.Wielded ? 0 : 1, diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs index ffd4982..8ce1e82 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs @@ -417,6 +417,7 @@ public class MissileCraftingManager } _host.UseFor((uint)targetId, "Crafting", "missile crafting: wield the new ammo"); + LastAmmoEquipAt = RynthClock.Now; ChatLog($"Equipped ammo (id=0x{targetId:X8})"); Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}"); } @@ -469,16 +470,26 @@ public class MissileCraftingManager if (WorldObjectCache.IsAmmo(item) || !IsPlayerWielded(item) || !LooksLikeMissileWeapon(item)) continue; - category = GetWeaponCategory(item.Name); + // The launcher's AmmoType when known (a crossbow not named so is still a crossbow), else its name. + int lt = CombatManager.LauncherTypeOf(item); + category = lt != 0 ? MissileAmmo.CategoryOf(lt) : GetWeaponCategory(item.Name); + _launcherType = lt; launcher = item; return true; } category = WeaponCategory.Bow; launcher = null; + _launcherType = 0; return false; } + // The ammo type of the launcher last seen in hand (0 = not known: by name only). + private int _launcherType; + + /// When crafting last sent an ammo wield (combat's ammo step waits a moment after it). + public DateTime LastAmmoEquipAt { get; private set; } = DateTime.MinValue; + private bool HasWieldedAmmo(List inventory, WeaponCategory category) { foreach (var item in WornCandidates(inventory)) @@ -583,8 +594,20 @@ public class MissileCraftingManager return WeaponCategory.Bow; } - private static bool IsLooseAmmo(WorldObject item, WeaponCategory category) => - AmmoRecipes.IsLooseAmmoName(item.Name, category); + /// + /// Ammo for the launcher: by name as before, or (2026-11-07) an ammunition-slot item whose AmmoType + /// fits the launcher's, or that has no AmmoType (servers' own ammo, often named nothing like + /// arrows; its wield is refused by the server when it doesn't fit, and backs off). + /// + private bool IsLooseAmmo(WorldObject item, WeaponCategory category) + { + if (AmmoRecipes.IsLooseAmmoName(item.Name, category)) return true; + int valid = item.Values(LongValueKey.Locations, 0); + if ((valid & MissileAmmo.AmmoSlot) == 0) return false; + int type = CombatManager.AmmoTypeOfItem(item); + if (type == 0) return true; + return _launcherType != 0 ? MissileAmmo.CanShoot(_launcherType, type) : MissileAmmo.CategoryOf(type) == category; + } private static int GetAmmoPriority(WorldObject item, WeaponCategory category) => AmmoRecipes.OutputRank(item.Name, category); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs index 160eabc..78ea7ab 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs @@ -37,6 +37,25 @@ namespace RynthCore.Plugin.RynthAi; /// 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 . +/// +/// Summons stopped for the rest of the session (2026-11-06 report: "keeps fighting and looting, +/// but just doesn't summon anymore" until the game is restarted), two ways: +/// +/// The client's cast-gesture gate (CanCastNow) can stay closed for good (a refused +/// action leaves a motion node that never pops; see ). Buffs and +/// combat go on through the watchdog's override, but the summon and the refill read the raw gate +/// and waited on it forever, with no log line. Past closed the gate is +/// taken as stuck here too. +/// A pet the client still shows but the server no longer has (a ghost, the same way as +/// 's monsters) or one whose delete the cache missed read as "a pet is +/// out" forever. A pet counts as out only while the client has it and the server has talked +/// about it in the last . +/// A death or a portal left the pet behind (, ): +/// it stops counting at once, and the summon state in flight is dropped. +/// An inventory rescan: a read of 0 right after one of 2+ is not believed once, an empty read +/// the server never confirmed is tried before it is parked, and an essence the client can no longer +/// name is not used. +/// /// internal sealed class PetManager { @@ -97,6 +116,40 @@ internal sealed class PetManager private const long RefillWindowMs = 120_000; // two refills inside this and the private const int RefillsPerWindow = 2; // essence still reads empty: private const long RefillLoopParkMs = 300_000; // park it this long + /// The gesture gate closed this long is stuck, not a gesture (CastGateWatchdog's 4 s). + internal const long GestureStuckMs = 4_000; + /// + /// A pet the server said nothing about for this long is a ghost. A live combat pet near monsters + /// gets motion updates every few seconds; an idle one that is silent costs one Use answered + /// "is already active", which turns this check off for . + /// + internal const long PetGhostSilentMs = 60_000; + private const long GhostCheckOffMs = 300_000; + + // The gesture gate as read every heartbeat: closed since when (0 = open), and whether it was + // taken as stuck (logged once until it reads open again). + private long _gateClosedSince; + private bool _gateStuck; + + // Pets not counted as out (ghost / gone from the client), each logged once. + private readonly HashSet _ignoredPetsLogged = new(); + private long _ghostCheckOffUntil; // the server said a pet is already active: trust the client's pets until then + + // Pets that were out when the character died or went through a portal. A pet never follows + // through either, and the server drops it without telling a player who is no longer near it, + // so the client kept showing it ("it thinks it's already summoned if you die"). Cleared when + // the server says a pet is already active. + private readonly HashSet _petsLeftBehind = new(); + // Pets the engine has no server record for (-1), since when: no record for PetGhostSilentMs of + // watching is silence too (an engine reload loses every record; a live pet gets one at once). + private readonly Dictionary _noServerRecordSince = new(); + + // Essences: the last charge count read above 0. A summon spends one charge, so a read of 0 right + // after one of 2 or more is a read in progress (a rescan, properties not back yet), not empty. + private readonly Dictionary _lastCharges = new(); + // Essences the server itself called empty ("not enough charges"). An empty read the server has + // not confirmed is tried with a summon before it is parked: an empty Use is refused harmlessly. + private readonly HashSet _serverSaidEmpty = new(); private string _playerName = string.Empty; private long _playerNameAt; @@ -144,6 +197,7 @@ internal sealed class PetManager if (!_settings.IsMacroRunning) { Reset(); return; } long now = NowMs; + ObserveGestureGate(now); // Positive completion checks for the in-flight action (don't wait for chat). if (_state == PetState.Summoning) @@ -214,6 +268,11 @@ 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)) { + // The server has a pet: a silent one the ghost check passed over is real after all. + _ghostCheckOffUntil = NowMs + GhostCheckOffMs; + _petsLeftBehind.Clear(); + _host.Log($"[RynthAi] Pet: the server says a pet is already active (essence 0x{(uint)_activeDeviceId:X8}); " + + $"pets the server has gone quiet about count as out for the next {GhostCheckOffMs / 60_000} min."); AssumePetFor(NowMs, AssumeActiveAfterSummonMs); GoIdle(); return; @@ -224,6 +283,8 @@ 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 + _lastCharges.Remove(_activeDeviceId); + if (_activeDeviceId != 0) _serverSaidEmpty.Add(_activeDeviceId); // 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) @@ -254,6 +315,47 @@ internal sealed class PetManager } } + /// The character died (RynthAiPlugin.HoldForDeath's edge): pets out now are left behind. + public void OnPlayerDeath() => ForgetPetsOut("died"); + + /// Portal space started (a portal, a recall, the death portal): pets out now are left behind. + public void OnPortal() => ForgetPetsOut("portal space"); + + /// + /// A pet never follows through a death or a portal: every pet out now stops counting as out, and + /// the summon or refill in flight, the "pet assumed out" window and the server's "already active" + /// trust are dropped, so the first fight after it gets a pet at once. The essences' cooldowns and + /// charge knowledge are the server's and stay; parks that ran out are pruned. + /// + private void ForgetPetsOut(string why) + { + long now = NowMs; + int left = 0; + string me = PlayerName(); + if (me.Length > 0) + { + string prefix = me + "'s "; + foreach (var wo in _objectCache.GetLandscape()) + if (wo != null && wo.ObjectClass != AcObjectClass.Corpse && !string.IsNullOrEmpty(wo.Name) + && wo.Name.StartsWith(prefix, StringComparison.Ordinal) && _petsLeftBehind.Add(wo.Id)) + left++; + } + if (_petsLeftBehind.Count > 64) _petsLeftBehind.Clear(); + bool inFlight = _state != PetState.Idle || now < _assumePetActiveUntil || now < _ghostCheckOffUntil; + Reset(); + _assumePetActiveUntil = 0; + _petSeenSinceSummon = false; + _ghostCheckOffUntil = 0; + _lastThinkAt = 0; + var expired = new List(); + foreach (var kv in _deviceCooldownUntil) + if (kv.Value <= now) expired.Add(kv.Key); + foreach (int id in expired) _deviceCooldownUntil.Remove(id); + if (left > 0 || inFlight) + _host.Log($"[RynthAi] Pet: {why}: {left} pet(s) out are left behind and no longer count as out" + + (inFlight ? ", the summon state was cleared" : "") + "; the next fight gets a new pet."); + } + // ── Decision ─────────────────────────────────────────────────────────────── /// Treat a pet as out until + (it may not be in the cache yet). @@ -315,6 +417,21 @@ internal sealed class PetManager if (charges == 0 && ServerSaidFull(deviceId, now)) charges = -1; + // 0 right after a read of 2 or more: a summon spends one charge, so this is a read in + // progress (an inventory rescan, a reload with properties not back yet). Summon as for + // an unreadable one instead of refilling or parking it. + if (charges > 0) + { + _lastCharges[deviceId] = charges; + _serverSaidEmpty.Remove(deviceId); + } + else if (charges == 0 && _lastCharges.TryGetValue(deviceId, out int last) && last > 1) + { + _lastCharges.Remove(deviceId); // once: the next 0 is believed + _host.Log($"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} reads 0 charges right after {last}; taken as a read in progress, summoning from it."); + charges = -1; + } + if (charges != 0) { // Has charges (or unreadable → attempt; an empty one is rejected @@ -344,6 +461,16 @@ internal sealed class PetManager continue; // parked by RefillLooping; try the next essence } + // Reads empty, no spirit (or refill off), and the server never said so: try it. An + // empty essence is refused harmlessly ("not enough charges", which then parks it); + // parking on the read alone left a stale 0 parked for as long as it stayed stale. + if (!_serverSaidEmpty.Contains(deviceId)) + { + _host.Log($"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} reads empty and nothing refills it; the server hasn't called it empty, so trying it."); + IssueSummon(deviceId, -1); + return; + } + // Out of charges and no spirit (or refill off): park this essence // briefly and move on to the next configured one. _deviceCooldownUntil[deviceId] = now + DeviceNoSpiritCooldownMs; @@ -355,7 +482,8 @@ internal sealed class PetManager // 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 the // 45 s essence cooldown for nothing. No state change; caller retries next tick. - if (!_host.CanCastNow) return; + // A gate closed past GestureStuckMs is stuck, not a gesture: the Use goes anyway. + if (!GestureGateOpen()) return; long now = NowMs; _state = PetState.Summoning; _activeDeviceId = deviceId; @@ -371,7 +499,7 @@ internal sealed class PetManager private void IssueRefill(int deviceId, int spiritId) { if (!_host.HasUseObjectOn) return; - if (!_host.CanCastNow) return; // same gesture gate as IssueSummon + if (!GestureGateOpen()) return; // same gesture gate as IssueSummon _state = PetState.Refilling; _activeDeviceId = deviceId; _activeSpiritId = spiritId; @@ -389,12 +517,36 @@ internal sealed class PetManager { if (deviceId == 0) return; _serverSaidFullUntil[deviceId] = NowMs + ServerSaidFullTrustMs; + _serverSaidEmpty.Remove(deviceId); if (_host.HasRequestId) _host.RequestId(unchecked((uint)deviceId)); _host.Log(refilled ? $"[RynthAi] Pet: refill complete (essence 0x{(uint)deviceId:X8}, server confirmed)." : $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} is already full (its charge read was stale); summoning from it."); } + /// + /// Reads the client's gesture gate (every heartbeat, so a gate that opens between two think + /// ticks restarts the count). Closed past : stuck, logged once. + /// + private void ObserveGestureGate(long now) + { + if (_host.CanCastNow) + { + if (_gateStuck) + _host.Log("[RynthAi] Pet: the gesture gate reads clear again."); + _gateClosedSince = 0; + _gateStuck = false; + return; + } + if (_gateClosedSince == 0) { _gateClosedSince = now; return; } + if (_gateStuck || now - _gateClosedSince <= GestureStuckMs) return; + _gateStuck = true; + _host.Log($"[RynthAi] Pet: the gesture gate has read busy for {(now - _gateClosedSince) / 1000}s - taken as stuck; summons and refills go on without it."); + } + + /// Clear for a summon or refill: no gesture animating, or the gate is stuck. + private bool GestureGateOpen() => _gateStuck || _host.CanCastNow; + private bool ServerSaidFull(int deviceId, long now) { if (!_serverSaidFullUntil.TryGetValue(deviceId, out long until)) return false; @@ -518,11 +670,53 @@ internal sealed class PetManager string n = wo.Name; if (string.IsNullOrEmpty(n) || !n.StartsWith(prefix, StringComparison.Ordinal)) continue; if (n.Contains("Corpse", StringComparison.OrdinalIgnoreCase)) continue; + if (!PetIsLive(wo)) continue; return true; } return false; } + /// + /// False for a pet the client no longer has (the cache missed its delete) or one the server + /// has said nothing about for (a ghost: the client still shows + /// it, the server has no such pet). Each such pet is logged once. + /// + private bool PetIsLive(WorldObject wo) + { + uint uid = unchecked((uint)wo.Id); + string? why = null; + long now = NowMs; + if (_petsLeftBehind.Contains(wo.Id)) + why = "it was out before the last death or portal (a pet never follows; left behind)"; + else if (!_host.TryGetObjectName(uid, out _) && !_host.TryGetObjectPosition(uid, out _, out _, out _, out _)) + why = "the client no longer has it (its delete was missed)"; + else if (now >= _ghostCheckOffUntil && _host.HasGetObjectServerAge) + { + int age = _host.GetObjectServerAge(uid); + if (age >= 0) + { + _noServerRecordSince.Remove(wo.Id); + if (age >= PetGhostSilentMs) + why = $"the server has said nothing about it for {age / 1000}s (a ghost the client still shows)"; + } + else + { + // No record: fine for a moment (a fresh pet, a full table just cleared), silence + // once it lasts as long as the rule's wait. + if (_noServerRecordSince.Count > 64) _noServerRecordSince.Clear(); + if (!_noServerRecordSince.TryGetValue(wo.Id, out long since)) + _noServerRecordSince[wo.Id] = since = now; + if (now - since >= PetGhostSilentMs) + why = $"the server has sent nothing about it in {(now - since) / 1000}s of watching (a ghost the client still shows)"; + } + } + if (why == null) return true; + if (_ignoredPetsLogged.Count > 64) _ignoredPetsLogged.Clear(); + if (_ignoredPetsLogged.Add(wo.Id)) + _host.Log($"[RynthAi] Pet: '{wo.Name}' (0x{uid:X8}) does not count as out: {why}; a new pet can be summoned."); + return false; + } + private string PlayerName() { long now = NowMs; @@ -550,15 +744,18 @@ internal sealed class PetManager { if (!rule.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)) continue; + // An essence the client can no longer name is gone (dropped on a death corpse that + // went away, given, destroyed): its cache entry reads as "in the pack" (container 0), + // so it was used and parked forever. The same-named search below finds its successor. var byId = _objectCache[rule.Id]; - if (byId != null && IsOwnedByPlayer(byId, playerId)) { yield return rule.Id; continue; } + if (byId != null && IsOwnedByPlayer(byId, playerId) && ClientHas(rule.Id)) { yield return rule.Id; continue; } if (string.IsNullOrWhiteSpace(rule.Name)) continue; foreach (var wo in _objectCache.AllKnownObjects()) { if (wo == null) continue; if (wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase) - && IsOwnedByPlayer(wo, playerId)) + && IsOwnedByPlayer(wo, playerId) && ClientHas(wo.Id)) { yield return wo.Id; break; @@ -628,6 +825,9 @@ internal sealed class PetManager return 0; } + /// The client still has the object (it can name it). + private bool ClientHas(int id) => _host.TryGetObjectName(unchecked((uint)id), out string n) && !string.IsNullOrEmpty(n); + /// True if the item's container chain roots at the player's pack (not a corpse). private bool IsOwnedByPlayer(WorldObject item, int playerId) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponList.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponList.cs index a9a56ce..932e937 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponList.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponList.cs @@ -141,6 +141,7 @@ internal static class WeaponList list.Add(new ItemRule { Id = r.Id, Name = fullName(r), Action = r.Action, KeepBuffed = r.KeepBuffed, + NoBuff = !r.KeepBuffed, // the face's "No buff" toggle (drawn on shield rows only) Kind = kind?.Invoke(r) ?? "", // A shield shows "Shield" in the element column (it has no element). Element = IsShieldRule(r) ? ShieldAction : r.Element.Length > 0 ? r.Element : UnknownLabel, @@ -181,7 +182,9 @@ internal static class WeaponList /// The Items panel's edited list, mapped onto the saved one by id: the saved name stays /// (the panel shows the full name; entries are matched and saved by id), an element the /// user changed becomes theirs ("set"), and "Unknown" stays unknown. Order and deletions - /// follow the panel. + /// follow the panel. The face's "noBuff" () sets KeepBuffed on a + /// shield entry only; on a weapon it is ignored, and absent (an older engine) it changes + /// nothing. /// public static List MergeEdited(IReadOnlyList saved, IEnumerable edited) { @@ -197,8 +200,9 @@ internal static class WeaponList bool changed = !elem.Equals(old.Element, StringComparison.OrdinalIgnoreCase); list.Add(new ItemRule { - // The panel carries only id, name and element: the rest stays as saved. - Id = old.Id, Name = old.Name, Action = old.Action, KeepBuffed = old.KeepBuffed, + // The panel carries id, name, element and (shields) noBuff: the rest stays as saved. + Id = old.Id, Name = old.Name, Action = old.Action, + KeepBuffed = IsShieldRule(old) && e.NoBuff is bool noBuff ? !noBuff : old.KeepBuffed, Element = changed ? elem : old.Element, ElementSource = changed ? (elem.Length > 0 ? SourceSet : "") : old.ElementSource, }); @@ -206,6 +210,8 @@ internal static class WeaponList else { e.Element = elem; + if (IsShieldRule(e) && e.NoBuff is bool noBuff) e.KeepBuffed = !noBuff; + e.NoBuff = null; // wire only: never saved list.Add(e); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapTracker.cs index d008b31..c6a486a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapTracker.cs @@ -61,9 +61,50 @@ internal sealed class WeaponSwapTracker private int _lastFrom, _lastTo; private DateTime _lastLandedAt = DateTime.MinValue; private int _askKey, _pendingKey, _lastKey; // the fight (target id) each swap was for; 0 = unknown + // Weapons seen in a wielded slot (the engine's equipment list) during their current run of + // wields. A new run (the first send after the count was cleared) forgets the sighting, so a + // weapon that later stops reaching the hand is given up on again. + private readonly HashSet _seenWielded = new(); + private DateTime _lastSentAt = DateTime.MinValue; + + /// How long after the last send counted tries keep the equipment list sampled. + public double AttemptWatchMs { get; set; } = 120_000; /// The weapon a swap is in flight for (0 = none). public int PendingId => _pendingId; + + /// + /// True while a wield is in flight, or tries are counted and the last send was under + /// before : the equipment list is worth + /// sampling. A stale count left behind does not keep the sampler reading every tick. + /// + public bool HasAttemptsAt(DateTime now) => + _pendingId != 0 || (_tries.Count > 0 && (now - _lastSentAt).TotalMilliseconds < AttemptWatchMs); + + /// True when was seen wielded while its wields were under way (see ). + public bool WasSeenWielded(int id) => _seenWielded.Contains(id); + + /// + /// is in a main-hand slot per the engine's equipment list, sampled every + /// tick while a wield is under way. When it has a wield in flight or tries counted, the wield + /// worked: its try count starts over and it is remembered as seen, so it is never taken for a + /// weapon that "never reached your hand". The swap in flight is left alone (combat lands it + /// when it sees the weapon in hand itself), so a stale hand read can never send a second + /// UseObject that would take the weapon off again. A weapon that reached the hand and was + /// swapped out for the buff wand before combat looked again had each of those wields counted + /// as a failed try, until it was left out of the weapon choice for 30 min. + /// + public void SeenWielded(int id) + { + if (id == 0 || (_pendingId != id && !_tries.ContainsKey(id))) return; + _seenWielded.Add(id); + _tries.Remove(id); + _busyRefunds.Remove(id); + } + /// A wield was sent less than ago and hasn't been answered. + public bool InFlight(DateTime now) => _pendingId != 0 && (now - _pendingAt).TotalMilliseconds < ResolveMs; + /// is resting after its failed tries. + public bool Resting(int id, DateTime now) => _restUntil.TryGetValue(id, out DateTime rest) && now < rest; /// Wields sent for since it was last in hand. public int TriesFor(int id) => _tries.TryGetValue(id, out int t) ? t : 0; /// Why the last Hold happened, for the log ("" = none). @@ -140,6 +181,9 @@ internal sealed class WeaponSwapTracker _pendingId = id; _pendingFrom = fromId; _pendingAt = now; + _lastSentAt = now; + // A fresh run of wields: an earlier sighting says nothing about this one. + if (!_tries.ContainsKey(id)) _seenWielded.Remove(id); _tries[id] = (_tries.TryGetValue(id, out int t) ? t : 0) + 1; } @@ -179,6 +223,7 @@ internal sealed class WeaponSwapTracker _tries.Clear(); _busyRefunds.Clear(); _restUntil.Clear(); + _seenWielded.Clear(); _busyUntil = DateTime.MinValue; } @@ -196,9 +241,11 @@ internal sealed class WeaponSwapTracker _busyRefunds.Clear(); _busyUntil = DateTime.MinValue; _restUntil.Clear(); + _seenWielded.Clear(); _landed.Clear(); _lastFrom = _lastTo = 0; _lastLandedAt = DateTime.MinValue; + _lastSentAt = DateTime.MinValue; _askKey = _pendingKey = _lastKey = 0; HoldReason = ""; Notice = null; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index 7234850..5f04e30 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -47,6 +47,11 @@ public class WorldObjectCache // targets: the server sends health only for the selected target). A real health update replaces // the estimate and takes the id out of this set. private readonly HashSet _estimatedHealth = new(); + // When the server's health for an id last arrived here (Clock), for ranking only: CombatManager's + // Lowest health compares it with the age of the engine plates' reading (API v93, 2026-11-07). + private readonly Dictionary _serverHealthAt = new(); + /// The clock stamps with (host tests set their own). + internal Func Clock { get; set; } = () => RynthClock.Now; /// The lowest an estimate goes: 0 means dead to every reader, and only the server says that. internal const float EstimatedHealthFloor = 0.01f; @@ -206,6 +211,7 @@ public class WorldObjectCache _landscape.Remove(sid); _healthRatios.Remove(sid); _estimatedHealth.Remove(sid); + _serverHealthAt.Remove(sid); _classifyRetry.Remove(id); _slowRetry.Remove(id); _reclassifySkipState.Remove(id); @@ -272,6 +278,14 @@ public class WorldObjectCache return _estimatedHealth.Contains(id); } + /// When the server's health for last arrived (OnUpdateHealth, on + /// ); false when it never did. An estimate doesn't move it. + public bool TryGetServerHealthTime(int id, out DateTime at) + { + lock (_gate) + return _serverHealthAt.TryGetValue(id, out at); + } + public void OnUpdateHealth(uint id, float healthRatio) { lock (_gate) @@ -282,6 +296,7 @@ public class WorldObjectCache int sid = (int)id; _healthRatios[sid] = Math.Clamp(healthRatio, 0f, 1f); _estimatedHealth.Remove(sid); // the server's number replaces any estimate + _serverHealthAt[sid] = Clock(); if (!_creatures.Add(sid)) return; // creature already known — ratio updated above, nothing more to do @@ -355,6 +370,8 @@ public class WorldObjectCache private readonly Dictionary _directInventoryIndex = new(); private DateTime _lastDirectInventoryScan = DateTime.MinValue; private const int DirectInventoryCooldownMs = 1000; + /// The clock GetDirectInventory's reuse runs on (tests freeze it; RynthClock otherwise). + internal Func WalkClock { get; set; } = static () => RynthClock.Now; private const int DirectInventoryForceRefreshMinMs = 250; /// Mark inventory as changed — triggers a full container scan on next Tick. @@ -952,6 +969,7 @@ public class WorldObjectCache // an object filed before its name or flag was readable still can, so the bags in the // inventory list (a handful) are re-checked here. Packs we carry aren't corpses. List<(int id, AcObjectClass was)>? invCorpses = null; + List<(int Id, uint Flags)>? invLoose = null; // filed as carried, but lying in the world foreach (int id in _inventory) { uint uid = unchecked((uint)id); @@ -961,7 +979,19 @@ public class WorldObjectCache if (IsCorpseName(wo.Name) || (_host.TryGetObjectName(uid, out string invName) && IsCorpseName(invName)) || HasCorpseFlag(uid)) + { (invCorpses ??= new()).Add((id, wo.ObjectClass)); + continue; + } + + // A chest that appeared before its position was known (the Dreamweave dig's Unearthed Cache) + // is filed here as something carried; the server says nobody holds it and it now has a + // position: it lies in the world. Without this it was never on the landscape, so no + // "use " search, Loot by name or chest scan could find it (2026-11-02). + if (WhoHas(id) == Holder.Nobody + && _host.TryGetObjectPosition(uid, out _, out _, out _, out _) + && _host.TryGetItemType(uid, out uint looseFlags)) + (invLoose ??= new()).Add((id, looseFlags)); } if (invCorpses != null) { @@ -974,6 +1004,21 @@ public class WorldObjectCache } } + if (invLoose != null) + { + int moved = 0; + foreach (var (id, flags) in invLoose) + { + if (!_byId.TryGetValue(id, out var lw)) continue; + uint uid = unchecked((uint)id); + AcObjectClass lc = ClassifyItem(uid, flags); + if (lc == AcObjectClass.Unknown || !FileTypedObject(uid, id, lw.Name ?? string.Empty, lc, flags)) continue; + moved++; + } + if (moved > 0) + _host.Log($"[RynthAi] ReclassifyUnknownDynamics: {moved} object(s) filed as carried lie loose in the world -> landscape"); + } + if (statics != null) foreach (var (id, name, cls) in statics) _byId[id] = Make(id, name, cls); @@ -1390,7 +1435,7 @@ public class WorldObjectCache // snapshot copy so the caller never iterates the live list a later call will clear. lock (_gate) { - DateTime now = RynthClock.Now; + DateTime now = WalkClock(); if (!_host.HasGetContainerContents) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/ConsumableLookup.cs b/Plugins/RynthCore.Plugin.RynthAi/ConsumableLookup.cs index 0304562..07cbcc7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ConsumableLookup.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ConsumableLookup.cs @@ -18,31 +18,37 @@ namespace RynthCore.Plugin.RynthAi; /// nothing happening (2026-11-03, DreamWeave: a used-up Treated Healing Kit was picked 70 times /// after a respawn, every use answered at once with no heal, and only natural regeneration /// raised health). Without the walk (an engine without GetContainerContents) the cache is used. +/// +/// : ids the caller knows are gone although the walk may still list them (a kit +/// its result line called used up, inside the walk's 1 s reuse; BuffManager.KitUsedUp). A skipped +/// listed id falls through to the name match, so the next stack of that name is used. /// internal static class ConsumableLookup { - public static WorldObject? Resolve(WorldObjectCache cache, ConsumableRule rule) + public static WorldObject? Resolve(WorldObjectCache cache, ConsumableRule rule, Func? skip = null) { IReadOnlyList carried = cache.GetDirectInventory(); if (carried.Count == 0) - return ResolveFromCache(cache, rule); // no walk yet (or none possible): the cache's view + return ResolveFromCache(cache, rule, skip); // no walk yet (or none possible): the cache's view if (rule.Id != 0) foreach (WorldObject wo in carried) - if (wo != null && wo.Id == rule.Id) return wo; + if (wo != null && wo.Id == rule.Id && !Skipped(skip, wo.Id)) return wo; if (string.IsNullOrWhiteSpace(rule.Name)) return null; foreach (WorldObject wo in carried) - if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase)) + if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase) && !Skipped(skip, wo.Id)) return wo; return null; } - private static WorldObject? ResolveFromCache(WorldObjectCache cache, ConsumableRule rule) + private static WorldObject? ResolveFromCache(WorldObjectCache cache, ConsumableRule rule, Func? skip) { - if (rule.Id != 0 && cache[rule.Id] is WorldObject byId) return byId; + if (rule.Id != 0 && !Skipped(skip, rule.Id) && cache[rule.Id] is WorldObject byId) return byId; if (string.IsNullOrWhiteSpace(rule.Name)) return null; foreach (WorldObject wo in cache.GetInventory()) - if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase)) + if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase) && !Skipped(skip, wo.Id)) return wo; return null; } + + private static bool Skipped(Func? skip, int id) => skip != null && skip(id); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 94164dc..46d47ba 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -156,6 +156,8 @@ public sealed partial class RynthAiPlugin private bool _currentLootItemSawAnim; private bool _currentLootItemStackable; // a stack at send: it may merge into a pack stack and vanish private bool _currentLootItemPipelined; // sent while the last pickup's Return played (ACE queues it) + private bool _currentLootItemJumped; // jump-loot: sent in the air, its own jump or the last one's (not a resend) + private bool _currentLootItemSentInAirWindow; // sent on the strength of the last no-bend-down pickup (JumpPickupInAir) private int _currentLootItemErrSeqAtSend; // TryGetLastWeenieError seq at the send (0 = unknown) private int _currentLootItemFreeRetries; // resends after a too-busy answer (not counted as attempts) // 2026-10-29 (R-20261029-122319-321f): what the server said to the last send, and what the @@ -194,6 +196,33 @@ public sealed partial class RynthAiPlugin private bool _settlingSawAnim; private bool _settlingAllowsPipeline; private int _pipelinedAfterItemId; // the answered pickup a move was already queued behind + // A jump-loot pickup answered with no bend-down (JumpPickupHadNoMotion): until this CorpseNowMs + // the client's motion queue is the jump's own (take-off, fall, landing), not a server pickup. + private long _jumpPickupAirUntil; + // The no-bend-down call is off until this CorpseNowMs (DistrustJumpNoMotion): the server turned a + // move or open away as too busy that went out on it, so it had played a bend-down after all. + private long _jumpNoMotionOffUntil; + // The UseDone count before a corpse open sent inside the no-bend-down window (-1: none watched). + private int _openInAirWindowSeq = -1; + /// How long the no-bend-down call stays off after the server proved it wrong. + internal const long JumpNoMotionDistrustMs = 5 * 60_000; + + // Flight budget. A pickup sent in the air with no fresh jump is a no-bend-down pickup only if the + // server still sees the character jumping when it processes the move. Prediction: jumpAge (ms + // since the loot jump) + the recent send-to-off-corpse time of no-bend-down pickups must stay + // within this budget, else the send waits for the landing and takes a fresh jump (a landing and + // a jump cost about 0.5 s; a late in-air send got the whole bend-down and Return, about 2 s). + // Measured in client logs from one ACE server: of 56 in-air sends answered with no bend-down, + // the largest jumpAge + off-corpse ms was 809. + internal const long LootJumpFlightBudgetMs = 809; + + /// The send-to-off-corpse time assumed until a no-bend-down pickup has been measured (log median 203 ms). + internal const long DefaultNoMotionOffCorpseMs = 200; + + // The send-to-off-corpse ms of the last 4 pickups answered with no bend-down (ConfirmCurrentLootItem). + private readonly long[] _noMotionOffCorpse = new long[4]; + private int _noMotionOffCorpseCount, _noMotionOffCorpseNext; + private bool _flightHoldLogged; // the hold for the current send has been logged // [LootEval] lines: one per item per open (a matched item was re-printed before every pickup). private readonly Dictionary _lootEvalLogged = new(); private int _manaStoneCapLoggedFor; // container the "ManaStone count for cap check" line was logged for @@ -825,6 +854,10 @@ public sealed partial class RynthAiPlugin if (_targetCorpseId == 0 && _chestCandidateId != 0 && TryTakeOpenChest(settings, CorpseNowMs)) return; + // A named object (Loot by name) when no corpse is claimed and nothing is open. + if (_targetCorpseId == 0 && _lootNameTargetId != 0 && TryLootByName(settings, CorpseNowMs)) + return; + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); double minMeters = GetCorpseApproachRangeMinMeters(settings, maxMeters); if (maxMeters <= 0.25) @@ -1832,9 +1865,11 @@ public sealed partial class RynthAiPlugin // The character still animates. Right after a pickup's answer that is its "Return" // (standing up): ACE queues a move that arrives then and runs it the moment the // Return ends (Player.HandleActionPutItemInContainer_Verify, NextPickup), so the next - // move goes out now - one, never two. Any other animation: wait until it ends. + // move goes out now - one, never two. Any other animation: wait until it ends. Not the + // jump's own motion after a jump-loot pickup the server answered with no bend-down: ACE + // has nothing to play then (no Return, not busy) and takes a pickup in the air. bool pipelined = false; - if (PickupAnimating(now)) + if (PickupAnimating(now) && !JumpPickupInAir(now)) { if (!CanPipelinePickup(now)) return; @@ -1845,6 +1880,25 @@ public sealed partial class RynthAiPlugin if (PickupHeldByServerAction()) return; + // Jump-loot (see the jump below): the settings and the flight are read first, so a send + // held for the landing does nothing else this tick (no chat line, no selection). + bool jumpLoot = !pipelined && ShouldJumpLoot(settings); + long jumpAge = jumpLoot ? ActionPacer.LootJumpAgeMs() : -1; + bool stillInAir = jumpLoot && ActionPacer.LootJumpAirborne(Host, out _); + if (stillInAir && FlightBudgetSpent(jumpAge, out long expectedAnswerMs)) + { + // A pickup sent now would reach the server after the flight is over and get the + // whole bend-down and Return: hold until LootJumpAirborne says landed (JumpLandMaxMs + // at most); the path below then jumps and sends. + if (!_flightHoldLogged) + { + _flightHoldLogged = true; + LootDiag($"[RynthAi] {LootTag}: jump-loot: holding 0x{(uint)firstMatchId:X8} '{matchItemName}' for the landing - {jumpAge} ms into the flight and an answer takes about {expectedAnswerMs} ms, over the {LootJumpFlightBudgetMs} ms flight budget."); + } + return; + } + _flightHoldLogged = false; + ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}"); _currentLootItemId = firstMatchId; RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId)); @@ -1861,9 +1915,16 @@ public sealed partial class RynthAiPlugin // corpses hold one match, so a multi-item gate meant jump-loot almost never ran), with // stamina > 5 to cover the cost. Not for a pipelined move: it is already queued behind // the last pickup's Return, and a jump there would only disturb that queue. The tap jump - // has a fixed height, so LootJumpHeight no longer has an effect. - if (!pipelined && ShouldJumpLoot(settings)) - Host.TapJump(); + // has a fixed height, so LootJumpHeight no longer has an effect. No second jump while + // still in the air (on ACE an air jump only costs stamina); a jump taken is noted, so + // combat and buffs wait for the landing (ACE refuses them in the air). A send late in + // the flight was held above (FlightBudgetSpent). + bool jumped = false; + if (jumpLoot && !stillInAir) + { + try { jumped = Host.TapJump(); } catch { jumped = false; } + if (jumped) ActionPacer.NoteLootJump(Host); + } // Always a move into a pack, never a use: a use on a wearable corpse item is // get-and-wield, which put salvage jewellery on the character (2026-10-02). @@ -1914,6 +1975,8 @@ public sealed partial class RynthAiPlugin // slot still held, or "You're too busy") must not cost the item one of its 3 tries. _currentLootItemMoveAttempts = pipelined ? 0 : 1; _currentLootItemPipelined = pipelined; + _currentLootItemJumped = jumped || stillInAir; + _currentLootItemSentInAirWindow = JumpPickupInAir(now); _currentLootItemStackable = stackable; _currentLootItemErrSeqAtSend = errSeqAtSend; NoteLootMoveSent(); @@ -1985,6 +2048,8 @@ public sealed partial class RynthAiPlugin /// /// An answer sooner than this after the send isn't believed: ACE plays the whole pickup /// motion (about 0.75 s standing, longer in a combat stance) before it moves the item. + /// Not for a jump-loot send's item seen in a pack (TickPendingCorpsePickup): with no motion + /// it comes in about the round trip. /// internal const long PickupAnswerMinMs = 500; @@ -2227,6 +2292,35 @@ public sealed partial class RynthAiPlugin _currentLootItemRefusalBusy = !IsQuestPickupRefusal(err) && (err == WeenieErrorYoureTooBusy || after < PickupAnswerMinMs); if (!_currentLootItemRefusalBusy && !_currentLootItemTimedOut) NotePickupAnswerLatency(after); + if (_currentLootItemSentInAirWindow && RefusedAsTooBusy(err)) + DistrustJumpNoMotion(now, $"0x{(uint)_currentLootItemId:X8}, sent on it, was refused as too busy {after} ms after the send"); + } + + /// + /// The refusal of the current send was ACE's "too busy", not another one (a full pack, a quest + /// item) that only came fast. ACE sends YoureTooBusy (0x1D) and then InventoryServerSaveFailed + /// with no code (Player_Inventory HandleActionPutItemInContainer_Verify); the engine keeps only + /// the last refusal but counts each, so the 0x1D is either the last code or the first of two + /// refusals since the send. A full pack sends one save-failed. + /// + private bool RefusedAsTooBusy(uint err) => + err == WeenieErrorYoureTooBusy + || (err == 0 && LastWeenieErrorSeq() - _currentLootItemErrSeqAtSend >= 2); + + /// + /// The server turned away as too busy a move or open that went out on a no-bend-down call: the + /// last pickup had a bend-down and a Return after all (on a fast server it can be 0.25-0.4 s, + /// inside PickupAnswerMinMs). The window ends and JumpPickupHadNoMotion says no for + /// JumpNoMotionDistrustMs, so every pickup waits its Return as without jump-loot. + /// + private void DistrustJumpNoMotion(long now, string why) + { + _jumpPickupAirUntil = 0; + _openInAirWindowSeq = -1; + bool was = now < _jumpNoMotionOffUntil; + _jumpNoMotionOffUntil = now + JumpNoMotionDistrustMs; + if (!was) + LootDiag($"[RynthAi] {LootTag}: jump-loot: {why}; the server played a bend-down after all - every pickup waits its Return for {JumpNoMotionDistrustMs / 60_000} min."); } /// @@ -2375,12 +2469,27 @@ public sealed partial class RynthAiPlugin internal const long PickupHoldMaxGapMs = 500; /// Jump-loot for this pickup: the setting, the keyboard jump and the move call, stamina for - /// the jump. + /// the jump, and no fight or heal it could delay (). private bool ShouldJumpLoot(LegacyUiSettings settings) => settings.LootJumpEnabled && Host.HasTapJump && Host.HasMoveItemExternal - && _vitals.CurrentStamina > 5; + && _vitals.CurrentStamina > 5 + && !JumpLootWouldDelayFight(settings); + + /// + /// The jump's flight holds attacks, buffs and heals (ACE refuses them in the air: ActionPacer + /// LootJumpAirborne), so a pickup goes without one while monsters are near (looting can run in a + /// fight with Boost Loot Priority or a loot turn) or health is under Heal At: the bend-down costs + /// about a second, a heal held in the air could cost the character. + /// + private bool JumpLootWouldDelayFight(LegacyUiSettings settings) + { + if (_combatManager?.HasNearbyMonsters == true) + return true; + uint max = _vitals.MaxHealth; + return max > 0 && settings.HealAt > 0 && _vitals.CurrentHealth * 100 < (uint)settings.HealAt * max; + } /// /// True while the server owes an answer to a cast or use (ActionPacer): ACE refuses a pickup @@ -2553,7 +2662,11 @@ public sealed partial class RynthAiPlugin && (currentItem == null || ObjectGoneFromClient(_currentLootItemId) || (currentContainer == 0 && _currentLootItemStackable) || MergedIntoInventoryStack(out mergedInto)); bool landed = inPack || mergedAway; - bool believable = now - _currentLootItemMoveRequestedAt >= PickupAnswerMinMs; + // The floor is ACE's motion time; a jump send skips it only for the item seen in a pack, + // the server's answer about that object, which also frees the client's one request slot + // (a merged-away object can leave the slot held, so a merge keeps the floor). + bool jumpAnswer = _currentLootItemJumped && inPack; + bool believable = jumpAnswer || now - _currentLootItemMoveRequestedAt >= PickupAnswerMinMs; long since = now - _currentLootItemLeftAt; bool answered = landed && believable; if (!answered && since < PickupArriveMaxMs) @@ -2750,6 +2863,8 @@ public sealed partial class RynthAiPlugin _currentLootItemFightHeld = false; _currentLootItemErrSeqAtSend = errSeqAtSend; _currentLootItemMoveRequestedAt = now; + _currentLootItemJumped = false; // a resend goes without a jump (the floor applies) + _currentLootItemSentInAirWindow = false; if (retried) NoteLootMoveSent(); _currentLootItemStillSince = 0; _currentLootItemSawAnim = false; @@ -2874,8 +2989,12 @@ public sealed partial class RynthAiPlugin if (answered) _currentLootItemDestsTried.Clear(); // landed: nothing to watch for (ResetCurrentLootItem) _processedCorpseItems.Add(_currentLootItemId); _corpseItemsLooted++; + bool noMotion = answered && JumpPickupHadNoMotion(); + long jumpSentAt = _currentLootItemMoveRequestedAt; LootDiag($"[RynthAi] {LootTag}: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}" + - $" ({now - _currentLootItemMoveRequestedAt} ms after the send{(_currentLootItemPipelined ? ", queued" : "")})."); + $" ({now - _currentLootItemMoveRequestedAt} ms after the send{(_currentLootItemPipelined ? ", queued" : "")}" + + $"{(noMotion ? $", jump-loot: off the corpse {_currentLootItemLeftAt - _currentLootItemMoveRequestedAt} ms after the send, no bend-down or Return to wait for" : "")})."); + if (noMotion) NoteNoMotionOffCorpse(_currentLootItemLeftAt - _currentLootItemMoveRequestedAt); // sizes the flight-budget prediction // Each item taken is progress, so the corpse/chest timeout counts from the last pickup: // a chest gets its 2 minutes per pickup, and a corpse with many keeps is no longer // closed part way through by the 12 s timeout (SK, 2026-10-11). Not while a hold @@ -2886,7 +3005,7 @@ public sealed partial class RynthAiPlugin if (_openedContainerId != 0 && _openedContainerId == _ownRecoveryCorpseId) NoteOwnCorpseItemRecovered(now); if (_currentLootItemChat is { } described) - Host.WriteToChat(described.Line, described.ChatType); + WriteItemInfoLine(described.Line, described.ChatType); else if (!string.IsNullOrWhiteSpace(_currentLootItemName)) ChatLine($"[RynthAi] Looted [{_currentLootItemActionLabel}] {_currentLootItemName}"); @@ -2900,13 +3019,85 @@ public sealed partial class RynthAiPlugin ResetCurrentLootItem(); _lastLootActionAt = now; - // Its Return now plays: the close waits for it, and one move may be queued behind it. + _pickupAnimSince = 0; // the next pickup's animation gets its own PickupAnimMaxMs + if (noMotion) + { + // Jump-loot, answered with no bend-down: ACE played no pickup motion, so EnqueuePickupDone + // has no Return to play and the server is no longer busy. Nothing to settle: the corpse + // can close and the next pickup or open can go now, in the air. What the server refuses + // in the air (a cast, an attack) waits on its own gates (ActionPacer.LootJumpAirborne). + // Still one move at a time: the next goes only after this one's answer. + _settlingLootItemId = 0; + _settlingContainerId = 0; + _settlingAllowsPipeline = false; + // The flight ends JumpLandMaxMs after the JUMP, not after this send: a send that rode an + // earlier jump (the in-air path) is later than its jump. Looked up as an age so the + // pacer's clock and the loot clock need not agree; -1 (no jump noted: it has landed, or + // the pacer was reset) falls back to the send time. + long flightAge = ActionPacer.LootJumpAgeMs(); + _jumpPickupAirUntil = flightAge >= 0 + ? now + (ActionPacer.JumpLandMaxMs - flightAge) + : jumpSentAt + ActionPacer.JumpLandMaxMs; + return; + } + + // Its Return now plays: the close waits for it, and one move may be queued behind it. A + // busy motion queue is that Return now, not an earlier jump's flight. + _jumpPickupAirUntil = 0; _settlingLootItemId = itemId; _settlingContainerId = _openedContainerId; _settlingSince = now; _settlingSawAnim = false; _settlingAllowsPipeline = answered; - _pickupAnimSince = 0; // the next pickup's animation gets its own PickupAnimMaxMs + } + + /// + /// The current pickup was a jump-loot pickup the server ran with no bend-down: its jump went + /// out with this very send or it was sent in the air from the last one (not a resend), and the + /// item was off the corpse sooner than PickupAnswerMinMs after it - quicker than ACE's pickup + /// motion, so ACE skipped it (in the air, Player_Inventory.GetPickupMotion returns Invalid under + /// allow_jump_loot). A jump pickup answered later (the character had landed, or allow_jump_loot + /// is off) had a bend-down and gets its Return waited out as before. Off for + /// JumpNoMotionDistrustMs after the server proved the call wrong (DistrustJumpNoMotion). + /// + private bool JumpPickupHadNoMotion() => + _currentLootItemJumped + && CorpseNowMs >= _jumpNoMotionOffUntil + && _currentLootItemLeftAt != 0 + && _currentLootItemLeftAt - _currentLootItemMoveRequestedAt < PickupAnswerMinMs; + + /// + /// Inside the flight of the last jump pickup that had no bend-down (at most + /// ActionPacer.JumpLandMaxMs from its jump): a busy motion queue now is the jump's take-off, + /// fall or landing, not a server pickup motion. + /// + private bool JumpPickupInAir(long now) => _jumpPickupAirUntil != 0 && now < _jumpPickupAirUntil; + + /// + /// A pickup sent in the air now is predicted to reach the server after the loot jump's flight: + /// jumpAge + the expected answer time is over . + /// + private bool FlightBudgetSpent(long jumpAge, out long expectedAnswerMs) + { + expectedAnswerMs = ExpectedNoMotionAnswerMs(); + return jumpAge >= 0 && jumpAge + expectedAnswerMs > LootJumpFlightBudgetMs; + } + + /// The recent send-to-off-corpse time of pickups answered with no bend-down (mean of the last 4), or the default. + internal long ExpectedNoMotionAnswerMs() + { + if (_noMotionOffCorpseCount == 0) return DefaultNoMotionOffCorpseMs; + long sum = 0; + for (int i = 0; i < _noMotionOffCorpseCount; i++) sum += _noMotionOffCorpse[i]; + return sum / _noMotionOffCorpseCount; + } + + private void NoteNoMotionOffCorpse(long ms) + { + if (ms <= 0) return; + _noMotionOffCorpse[_noMotionOffCorpseNext] = ms; + _noMotionOffCorpseNext = (_noMotionOffCorpseNext + 1) % _noMotionOffCorpse.Length; + if (_noMotionOffCorpseCount < _noMotionOffCorpse.Length) _noMotionOffCorpseCount++; } /// @@ -2933,6 +3124,7 @@ public sealed partial class RynthAiPlugin { _lootStarved = false; _lootWorkWhy = string.Empty; + _deathWaitHeld = false; if (!settings.IsMacroRunning || (!settings.EnableLooting && !ForcedLootHolds())) return false; @@ -2954,6 +3146,7 @@ public sealed partial class RynthAiPlugin && _corpseWaitingSince.TryGetValue(current, out long since) && CorpseNowMs - since >= LootStarveMs; _lootWorkWhy = _openedContainerId != 0 ? "a container is open" : _targetCorpseId != 0 ? "a corpse is claimed" : "corpse autorun"; + _deathWaitHeld = DeathWaitHolds(settings); // the kill's corpse being looted: the wait goes on (RynthAiPlugin.DeathWait.cs) return true; } @@ -2969,6 +3162,13 @@ public sealed partial class RynthAiPlugin return true; } + // A named object in range (Loot by name, RynthAiPlugin.LootByName.cs): used so the client walks there. + if (HasLootNameWork(settings, CorpseNowMs)) + { + _lootWorkWhy = "a named item"; + return true; + } + // Loot grace: combat just ended and the corpse CreateObject has not // arrived yet. Hold Looting across that gap so nav doesn't walk away // from a body that is about to exist. @@ -2985,9 +3185,24 @@ public sealed partial class RynthAiPlugin double range = GetCorpseApproachRangeMaxMeters(settings); if (range > 0.25) HasUnlootedCorpsesInRange(range); // keeps _lootableInRange current _lootWorkWhy = "Boost Loot: the kill's corpse is forming"; + _deathWaitHeld = DeathWaitHolds(settings); return true; } + // The death wait (2026-11-08, RynthAiPlugin.DeathWait.cs): our kill's corpse is on its way, or + // here and being looted. Looting holds the tick, so nothing walks off meanwhile. + if (_deathWaitAt != 0) + { + double range = GetCorpseApproachRangeMaxMeters(settings); + if (range > 0.25) HasUnlootedCorpsesInRange(range); // keeps _lootableInRange current + _deathWaitHeld = DeathWaitHolds(settings); + if (_deathWaitHeld) + { + _lootWorkWhy = _deathCorpseId == 0 ? "the kill's corpse is on its way (death animation)" : "the kill's corpse is being looted"; + return true; + } + } + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); if (maxMeters <= 0.25) return false; @@ -3379,6 +3594,14 @@ public sealed partial class RynthAiPlugin ruleLabel = string.Empty; builtIn = string.Empty; + // An Eternal Mana Charge in the pack: tapping is ignored, so stones are not needed. + if (_manaStoneManager?.HasEternalChargeCached() == true && !ManaStoneManager.IsEternalCharge(item)) + { + builtIn = "a mana stone, but an Eternal Mana Charge is in the pack: mana tapping is ignored"; + if (!preview) _corpseCappedIds.Add(item.Id); + return false; + } + // Count stones already in the pack against the KeepCount cap, using // the SAME IsManaStone predicate as the loot gate above — if these // diverged the cap would silently stop working (e.g. gate loots by @@ -3779,6 +4002,7 @@ public sealed partial class RynthAiPlugin _completedCorpses[corpseId] = CorpseNowMs; EndBoostLootKillWait(corpseId); + EndDeathWaitFor(corpseId); _corpseCooldownUntil.Remove(corpseId); _processedCorpseItems.Clear(); _corpseItemAttempts.Clear(); @@ -3870,6 +4094,9 @@ public sealed partial class RynthAiPlugin _currentLootItemSawAnim = false; _currentLootItemStackable = false; _currentLootItemPipelined = false; + _currentLootItemJumped = false; + _currentLootItemSentInAirWindow = false; + _flightHoldLogged = false; // a hold is logged once per send; a corpse completed or abandoned starts fresh _currentLootItemErrSeqAtSend = 0; _currentLootItemFreeRetries = 0; _currentLootItemFightHeld = false; @@ -3994,8 +4221,14 @@ public sealed partial class RynthAiPlugin int seqBefore = watch ? Host.GetUseDoneSeq() : 0; RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.SelectAsBot(Host, unchecked((uint)corpseId)); bool sent = Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse"); - if (watch && sent) + // Not with monsters about: a swing, a hit or a stance change cancels the server's walk to the + // corpse, and the use is answered with nothing opened. That says nothing about the server, and + // four of them in a wave fight paused looting for 5 minutes and told the player to relog + // (2026-11-06). The check is for a calm character whose opens still don't work. + if (watch && sent && _combatManager?.HasNearbyMonsters != true) _useRefusals.OnOpenSent(corpseId, now, seqBefore); + // An open on a no-bend-down call: its answer says whether the server was free (DistrustJumpNoMotion). + _openInAirWindowSeq = watch && sent && JumpPickupInAir(now) ? seqBefore : -1; LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}."); // The finished corpse held open (MarkCorpseCompleted): this use closes it on the server. if (sent && _closeDeferredFor != 0 && _closeDeferredFor != corpseId) @@ -4018,6 +4251,12 @@ public sealed partial class RynthAiPlugin return; int seq = Host.GetUseDoneSeq(); bool haveErr = Host.TryGetLastUseDone(out int lastSeq, out uint err) && lastSeq == seq; + if (_openInAirWindowSeq >= 0 && seq != _openInAirWindowSeq) + { + if (haveErr && err == WeenieErrorYoureTooBusy) + DistrustJumpNoMotion(now, "the next corpse's open, sent on it, was refused as too busy"); + _openInAirWindowSeq = -1; + } ApplyUseRefusalVerdict(_useRefusals.OnTick(now, seq, err, haveErr), now); } @@ -4067,18 +4306,18 @@ public sealed partial class RynthAiPlugin case UseRefusalWatch.Verdict.Stuck: { FlightRecorderSignal.Dump(Host, "use check: server refuses every use"); - Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop{(_useCheckJumpAt != 0 ? ", the jump" : "")} and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again{(Host.HasTapJump ? " after a jump" : "")}."); + Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop{(_useCheckJumpAt != 0 ? ", the jump" : "")} and retry didn't help - looting paused {_useRefusals.BackoffMs / 1000} s, then one corpse is tried again{(Host.HasTapJump ? " after a jump" : "")}."); _useCheckJumpAt = 0; if (!_useStuckAnnounced) { _useStuckAnnounced = true; - ChatLine($"[RynthAi] The server isn't letting this character use objects; a relog fixes it. Looting is paused and tried again every few minutes."); + ChatLine($"[RynthAi] The server isn't letting this character use objects; a relog fixes it. Looting is paused and tried again every minute or two."); } ResetCorpseTarget(); break; } case UseRefusalWatch.Verdict.StillStuck: - Log($"[RynthAi] Use check: still refused{(_useCheckJumpAt != 0 ? " after the jump" : "")} - next try in {_useRefusals.BackoffMs / 60_000} min."); + Log($"[RynthAi] Use check: still refused{(_useCheckJumpAt != 0 ? " after the jump" : "")} - next try in {_useRefusals.BackoffMs / 1000} s."); _useCheckJumpAt = 0; ResetCorpseTarget(); break; @@ -4245,6 +4484,11 @@ public sealed partial class RynthAiPlugin private void ResetCorpseTarget() { StopCorpseMovement(); + // The no-bend-down window belongs to the loot that set it (the macro off, a claim dropped). + // ActionPacer's air hold is the character's own flight: it ends on the landing, or at death, + // portal space and logout (RynthAiPlugin), not with a corpse. + _jumpPickupAirUntil = 0; + _openInAirWindowSeq = -1; _targetCorpseId = 0; _corpseTargetSince = 0; _openedContainerAt = 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs index 649d519..6a81045 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs @@ -45,6 +45,15 @@ namespace RynthCore.Plugin.RynthAi.CreatureData; /// AU|<tier>|<wcid>|<name>|<weaponId>|<hits>|<misses>|<secAvg>|<secSamples> /// APK|<tier>|<wcid>|<name>|<element>|<kills>|<secAvg> /// AT|<tier>|<wcid>|<name>|<element>|<hits>|<avg>|<max> +/// ATS|<tier>|<wcid>|<name>|<shield>|<facing>|<hits>|<avg>|<max> +/// +/// Damage taken split by shield and facing (2026-11-08: does a shield cut a boss's hits?): +/// TS|<wcid>|<name>|<shield 0/1>|<facing front/behind/unknown>|<hits>|<avg>|<max> +/// shield 1 = a shield in the off hand in a combat stance (ACE ignores one in peace); facing = the +/// attacker within 90 degrees of our facing (front: ACE counts the shield), outside it (behind), or +/// not measurable (unknown, never guessed; ). Its avg is the mean of every +/// hit (T's is a running average). An older loader skips TS rows (no branch matches "TS"); ATS goes +/// through its tier-row switch and matches no case. /// Records go to (the tier where the player stands, set each tick); /// readers without a tier argument read it too, and the Damage panel passes the tier it shows. /// @@ -104,6 +113,7 @@ internal sealed class MonsterDamageStore public readonly Dictionary Weapons = new(); public readonly Dictionary Pets = new(StringComparer.OrdinalIgnoreCase); public readonly Dictionary Taken = new(StringComparer.OrdinalIgnoreCase); + public readonly Dictionary<(bool Shield, HitFacing Facing), TakenStat> ShieldTaken = new(); } private const int NoTier = int.MinValue; // sentinel: no cast observed for this wcid yet @@ -125,6 +135,7 @@ internal sealed class MonsterDamageStore public readonly Dictionary Weapons = new(); public readonly Dictionary Pets = new(StringComparer.OrdinalIgnoreCase); public readonly Dictionary Taken = new(StringComparer.OrdinalIgnoreCase); + public readonly Dictionary<(bool Shield, HitFacing Facing), TakenStat> ShieldTaken = new(); } private readonly object _lock = new(); @@ -306,6 +317,18 @@ internal sealed class MonsterDamageStore p.Taken[f[3]] = t; } } + else if (f.Length >= 8 && f[0] == "TS") + { + // TS|wcid|name|shield|facing|hits|avg|max + if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint sw) + && TryShieldKey(f[3], f[4], out var key) + && TryTaken(f, 5, out var t)) + { + var p = Get(sw); + if (f[2].Length > 0) p.Name = f[2]; + p.ShieldTaken[key] = t; + } + } else if (f.Length >= 9 && f[0] == "D") { // New: D|wcid|name|weaponId|element|tier|avg|dmgS|avgCasts|killS|critAvg|critS|nonCritAvg|nonCritS (14 fields) @@ -418,9 +441,52 @@ internal sealed class MonsterDamageStore tp.Taken[f[4]] = t; break; } + case "ATS" when f.Length >= 9: + if (TryShieldKey(f[4], f[5], out var key) && TryTaken(f, 6, out var st)) + tp.ShieldTaken[key] = st; + break; } } + /// A TS/ATS row's "shield|facing" pair: shield 0 or 1, facing front/behind/unknown. + private static bool TryShieldKey(string shield, string facing, out (bool Shield, HitFacing Facing) key) + { + key = default; + bool s; + if (shield == "1") s = true; + else if (shield == "0") s = false; + else return false; + if (!ShieldFacing.TryParse(facing, out HitFacing f)) return false; + key = (s, f); + return true; + } + + /// "hits|avg|max" from ; a row with no hits is dropped. + private static bool TryTaken(string[] f, int at, out TakenStat t) + { + var inv = CultureInfo.InvariantCulture; + t = new TakenStat(); + if (f.Length < at + 3 + || !int.TryParse(f[at], NumberStyles.Integer, inv, out t.Hits) || t.Hits <= 0 + || !double.TryParse(f[at + 1], NumberStyles.Float, inv, out t.Avg) + || !double.TryParse(f[at + 2], NumberStyles.Float, inv, out t.Max)) + return false; + return true; + } + + private static string ShieldKeyText((bool Shield, HitFacing Facing) k) => (k.Shield ? "1|" : "0|") + ShieldFacing.Word(k.Facing); + + /// The TS/ATS rows in a stable order: shield first, then front, behind, unknown. + private static List> ShieldRowsInOrder( + Dictionary<(bool Shield, HitFacing Facing), TakenStat> d) + { + var list = new List>(d); + list.Sort((a, b) => a.Key.Shield != b.Key.Shield ? (a.Key.Shield ? -1 : 1) : FacingOrder(a.Key.Facing).CompareTo(FacingOrder(b.Key.Facing))); + return list; + } + + private static int FacingOrder(HitFacing f) => f switch { HitFacing.Front => 0, HitFacing.Behind => 1, _ => 2 }; + /// The tier rows of the file (empty when there are none). Caller holds _lock. private void AppendTierRows(StringBuilder sb) { @@ -431,6 +497,7 @@ internal sealed class MonsterDamageStore sb.Append("# AU|tier|wcid|name|weaponId|hits|misses|secToKillAvg|secSamples\n"); sb.Append("# APK|tier|wcid|name|summonElement|kills|secToKillAvg\n"); sb.Append("# AT|tier|wcid|name|element|hitsTaken|avgDamageTaken|maxDamageTaken\n"); + sb.Append("# ATS|tier|wcid|name|shield|facing|hitsTaken|avgDamageTaken|maxDamageTaken (as TS)\n"); var keys = new List<(uint Wcid, int Difficulty)>(_byTier.Keys); keys.Sort((a, b) => a.Difficulty != b.Difficulty ? a.Difficulty.CompareTo(b.Difficulty) : a.Wcid.CompareTo(b.Wcid)); foreach (var key in keys) @@ -457,6 +524,9 @@ internal sealed class MonsterDamageStore foreach (var t in tp.Taken) sb.Append("AT|").Append(head).Append('|').Append(t.Key).Append('|') .Append(t.Value.Hits).Append('|').Append(Num(t.Value.Avg)).Append('|').Append(Num(t.Value.Max)).Append('\n'); + foreach (var s in ShieldRowsInOrder(tp.ShieldTaken)) + sb.Append("ATS|").Append(head).Append('|').Append(ShieldKeyText(s.Key)).Append('|') + .Append(s.Value.Hits).Append('|').Append(Num(s.Value.Avg)).Append('|').Append(Num(s.Value.Max)).Append('\n'); } } @@ -483,6 +553,9 @@ internal sealed class MonsterDamageStore sb.Append("# U|wcid|name|weaponId|hits|misses|secToKillAvg|secSamples (accuracy and fight length per weapon)\n"); sb.Append("# PK|wcid|name|summonElement (none = no summon)|kills|secToKillAvg\n"); sb.Append("# T|wcid|name|element|hitsTaken|avgDamageTaken|maxDamageTaken\n"); + sb.Append("# TS|wcid|name|shield|facing|hitsTaken|avgDamageTaken|maxDamageTaken (damage taken by shield and facing:\n"); + sb.Append("# shield 1 = a shield in the off hand in a combat stance, 0 = none; facing front = the attacker within\n"); + sb.Append("# 90 deg of your facing (ACE counts the shield), behind = outside it, unknown = not measurable; avg = mean)\n"); if (_defaultWeapon != 0) sb.Append("DEF|").Append(_defaultWeapon).Append('\n'); foreach (var kv in _byWcid) @@ -515,6 +588,9 @@ internal sealed class MonsterDamageStore foreach (var t in p.Taken) sb.Append("T|").Append(kv.Key).Append('|').Append(name).Append('|').Append(t.Key).Append('|') .Append(t.Value.Hits).Append('|').Append(Num(t.Value.Avg)).Append('|').Append(Num(t.Value.Max)).Append('\n'); + foreach (var s in ShieldRowsInOrder(p.ShieldTaken)) + sb.Append("TS|").Append(kv.Key).Append('|').Append(name).Append('|').Append(ShieldKeyText(s.Key)).Append('|') + .Append(s.Value.Hits).Append('|').Append(Num(s.Value.Avg)).Append('|').Append(Num(s.Value.Max)).Append('\n'); foreach (var c in p.Casts) { string[] kp = c.Key.Split('|'); // weaponId|element|tier @@ -684,6 +760,46 @@ internal sealed class MonsterDamageStore } } + /// + /// The same hit as , split by whether a shield counted + /// (: one in the off hand in a combat stance) and where the attacker + /// stood (). The average is the mean of every hit, so the cells add up. + /// + public void RecordTakenSplit(uint wcid, string name, bool shield, HitFacing facing, double damage) + { + if (NotMonster(wcid) || damage <= 0 || !double.IsFinite(damage)) return; + int d = Difficulty; + lock (_lock) + { + SetNameLocked(wcid, name); + var split = d > 0 ? Tier(wcid, d).ShieldTaken : Get(wcid).ShieldTaken; // monster damage scales + var key = (shield, facing); + if (!split.TryGetValue(key, out var t)) split[key] = t = new TakenStat(); + t.Hits++; + t.Avg += (damage - t.Avg) / t.Hits; + if (damage > t.Max) t.Max = damage; + _dirty = true; + } + } + + public readonly record struct ShieldTakenRow(bool Shield, HitFacing Facing, int Hits, double Avg, double Max); + + /// Damage taken by shield and facing at one difficulty tier (0 = real Dereth); shield first, then front, behind, unknown. + public List GetShieldTaken(uint wcid, int difficulty) + { + var list = new List(); + lock (_lock) + { + Dictionary<(bool Shield, HitFacing Facing), TakenStat>? d = null; + if (difficulty > 0) { if (_byTier.TryGetValue((wcid, difficulty), out var tp)) d = tp.ShieldTaken; } + else if (_byWcid.TryGetValue(wcid, out var p)) d = p.ShieldTaken; + if (d != null) + foreach (var kv in ShieldRowsInOrder(d)) + list.Add(new ShieldTakenRow(kv.Key.Shield, kv.Key.Facing, kv.Value.Hits, kv.Value.Avg, kv.Value.Max)); + } + return list; + } + /// Seconds per kill over every timed fight with this monster (kills-weighted), and hit rate /// over every weapon (-1 when unknown). For the Damage tab's main row. public (double SecPerKill, double HitRate) GetSummary(uint wcid) => GetSummary(wcid, Difficulty); @@ -1089,7 +1205,7 @@ internal sealed class MonsterDamageStore { if (!anyTier && p.Casts.Count == 0 && p.HpSamples == 0 && p.HpManual <= 0 && p.HpPool <= 0 && p.WeaponManual == 0 && p.OffhandManual == 0 && p.PetManual.Length == 0 - && p.Weapons.Count == 0 && p.Pets.Count == 0 && p.Taken.Count == 0) + && p.Weapons.Count == 0 && p.Pets.Count == 0 && p.Taken.Count == 0 && p.ShieldTaken.Count == 0) _byWcid.Remove(wcid); _dirty = true; } @@ -1129,6 +1245,7 @@ internal sealed class MonsterDamageStore p.Weapons.Clear(); p.Pets.Clear(); p.Taken.Clear(); + p.ShieldTaken.Clear(); foreach (var c in p.Casts.Values) { c.Avg = 0; c.Samples = 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/ShieldFacing.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/ShieldFacing.cs new file mode 100644 index 0000000..81b5c5d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/ShieldFacing.cs @@ -0,0 +1,131 @@ +using System; + +namespace RynthCore.Plugin.RynthAi.CreatureData; + +/// Where a monster stood when it hit us, as ACE's shield rule sees it. +internal enum HitFacing +{ + /// Not measurable: no heading or position, the attacker not found, or several of + /// its name around that disagree. Never a guess. + Unknown = 0, + /// Within 90 degrees either side of our facing: a shield counts. + Front = 1, + /// Outside that arc: a shield does nothing. + Behind = 2, +} + +/// +/// The facing half of "does the shield help?" (2026-11-08): ACE counts a shield only when the +/// attacker is within +-90 degrees of the defender's facing (Creature_Combat.GetShieldMod, +/// effectiveAngle 180; SpellProjectile.GetShieldMod the same for spells), and only in a combat +/// stance. Facing is the 2D angle between the defender's forward vector (the orientation +/// applied to +Y) and the direction to the attacker; |angle| <= 90 is in front. +/// +/// Headings here are compass bearings (0 = North, clockwise) from the pose quaternion, the basis +/// of ; never Host.TryGetPlayerHeading (0 = East, counter-clockwise). +/// Positions are landblock-local (cell + x/y) and made global the way WorldObjectCache.Distance +/// does (192 m per landblock). Pure: the host tests call it directly. +/// +internal static class ShieldFacing +{ + /// ACE's shield arc in degrees (half of it either side of the facing). + public const double ShieldArcDeg = 180.0; + + /// Attackers farther than this are not the one that just hit (stale or another of the name). + public const double MaxAttackerRange = 80.0; + + public static string Word(HitFacing f) => f switch + { + HitFacing.Front => "front", + HitFacing.Behind => "behind", + _ => "unknown", + }; + + public static bool TryParse(string? s, out HitFacing f) + { + switch ((s ?? "").Trim().ToLowerInvariant()) + { + case "front": f = HitFacing.Front; return true; + case "behind": f = HitFacing.Behind; return true; + case "unknown": f = HitFacing.Unknown; return true; + default: f = HitFacing.Unknown; return false; + } + } + + /// The compass heading (0 = North, clockwise) of the yaw quaternion (w, z), as PlayerCompass. + public static double CompassFromQuaternion(double qw, double qz) + { + double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + return ((-yaw) % 360.0 + 720.0) % 360.0; + } + + /// A cell's landblock-local x/y as global metres (192 m per landblock). + public static (double X, double Y) Global(uint cell, float x, float y) + => (((cell >> 24) & 0xFF) * 192.0 + x, ((cell >> 16) & 0xFF) * 192.0 + y); + + /// A dungeon or building cell (cell index 0x100 and up): its own frame. + public static bool IsIndoorCell(uint cell) => (cell & 0xFFFF) >= 0x100; + + /// + /// Signed angle in degrees (-180..180] from to the bearing of the + /// point (dx east, dy north); NaN when the point is on top of us or a number isn't finite. + /// + public static double AngleTo(double headingDeg, double dx, double dy) + { + if (!double.IsFinite(headingDeg) || !double.IsFinite(dx) || !double.IsFinite(dy)) return double.NaN; + if (dx * dx + dy * dy < 0.0001) return double.NaN; // under a centimetre: no direction + double bearing = Math.Atan2(dx, dy) * (180.0 / Math.PI); // compass: 0 = North, clockwise + double diff = (bearing - headingDeg) % 360.0; + if (diff > 180.0) diff -= 360.0; + if (diff <= -180.0) diff += 360.0; + return diff; + } + + /// In front (|angle| <= 90, ACE's "not greater than half the arc"), behind, or unknown. + public static HitFacing Classify(double headingDeg, double px, double py, double ax, double ay) + { + double a = AngleTo(headingDeg, ax - px, ay - py); + if (double.IsNaN(a)) return HitFacing.Unknown; + return Math.Abs(a) > ShieldArcDeg / 2.0 ? HitFacing.Behind : HitFacing.Front; + } + + /// + /// from two landblock-local positions. + /// Different landblocks with a dungeon or building cell on either side have no shared frame: + /// unknown. So is an attacker beyond . + /// + public static HitFacing Classify(double headingDeg, uint playerCell, float px, float py, uint attackerCell, float ax, float ay) + { + double d = Distance2D(playerCell, px, py, attackerCell, ax, ay); + if (double.IsNaN(d) || d > MaxAttackerRange) return HitFacing.Unknown; + var (gpx, gpy) = Global(playerCell, px, py); + var (gax, gay) = Global(attackerCell, ax, ay); + return Classify(headingDeg, gpx, gpy, gax, gay); + } + + /// Flat distance between two landblock-local positions; NaN when they share no frame + /// (different landblocks with a dungeon or building cell on either side) or a number isn't finite. + public static double Distance2D(uint cellA, float xa, float ya, uint cellB, float xb, float yb) + { + if ((cellA >> 16) != (cellB >> 16) && (IsIndoorCell(cellA) || IsIndoorCell(cellB))) return double.NaN; + var (gax, gay) = Global(cellA, xa, ya); + var (gbx, gby) = Global(cellB, xb, yb); + double dx = gbx - gax, dy = gby - gay; + double d = Math.Sqrt(dx * dx + dy * dy); + return double.IsFinite(d) ? d : double.NaN; + } + + /// Several monsters of the attacker's name: the facing when every one agrees, else unknown. + /// None at all is unknown too. The caller leaves out the ones beyond range. + public static HitFacing Agree(System.Collections.Generic.IEnumerable each) + { + HitFacing? seen = null; + foreach (HitFacing f in each) + { + if (f == HitFacing.Unknown) return HitFacing.Unknown; + if (seen == null) seen = f; + else if (seen != f) return HitFacing.Unknown; + } + return seen ?? HitFacing.Unknown; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs index 9107e73..c377ee9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs @@ -10,6 +10,7 @@ internal enum TickStep DataWriteProblems, CombatHook, DelayedCommands, + FellowOpen, GameInput, EngineCommands, PropertyDump, @@ -24,6 +25,7 @@ internal enum TickStep WatchedFiles, QuestTracker, LocalFeatures, + RouteJobs, GiveQueue, ItemTool, Jumper, @@ -98,6 +100,7 @@ internal sealed class TickGuard Add(TickStep.DataWriteProblems, "save problem report", LogCat.General); Add(TickStep.CombatHook, "script hook cast results", LogCat.Combat); Add(TickStep.DelayedCommands, "delayed commands", LogCat.Commands); + Add(TickStep.FellowOpen, "open fellowship on create", LogCat.Commands); Add(TickStep.GameInput, "held keys", LogCat.Commands, essential: true); Add(TickStep.EngineCommands, "engine commands", LogCat.Commands); Add(TickStep.PropertyDump, "property dump", LogCat.Commands); @@ -112,6 +115,7 @@ internal sealed class TickGuard Add(TickStep.WatchedFiles, "monster and nav files", LogCat.UI); Add(TickStep.QuestTracker, "quest tracker", LogCat.Quests); Add(TickStep.LocalFeatures, "HUDs and panels", LogCat.Huds); + Add(TickStep.RouteJobs, "dungeon route jobs", LogCat.Navigation); Add(TickStep.GiveQueue, "give queue", LogCat.Inventory); Add(TickStep.ItemTool, "item tool", LogCat.Inventory); Add(TickStep.Jumper, "jumper", LogCat.Jumper, essential: true); diff --git a/Plugins/RynthCore.Plugin.RynthAi/DunRouteSidecar.cs b/Plugins/RynthCore.Plugin.RynthAi/DunRouteSidecar.cs new file mode 100644 index 0000000..3e8a338 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/DunRouteSidecar.cs @@ -0,0 +1,288 @@ +// DunRouteSidecar: the doorway points of the dungeon routes RynthAi's route maker saved +// (/ra dunroute, /ra dunpatrol-save, RynthAi.Routes), kept beside them (2026-10-30). +// +// Why: the route maker lays the points dunnav-patrol walks, and the ones centred in front of and +// beyond a narrow opening carry NavPoint.Doorway (a 1 yd reach, no corner cut: the character +// lines up and goes through straight). The VTank .nav format has no field for it, and the format +// stays as it is (VTank and other tools read these files), so a route run from its file lost the +// flag and cut doorway corners as routes did before the doorway work. +// +// So NavProfiles\.rynthai-routes.json lists the routes the route maker wrote: the file name, its +// SHA-256 when it was saved, the dungeon's landblock, its point count and the indexes of its +// doorway points. VTank ignores it (not a .nav). When a nav is loaded (any way: the Nav picker, +// /ra nav load, /vt nav load, a meta), RynthAi's tick (RynthAiPlugin.DunRoutes.cs, TickDunDoorways) +// looks it up: the same name and hash, and the character in that dungeon, and the flags go back +// on those points. A file edited since (another hash) gets none, and one log line says why. Navs +// the route maker didn't write are never touched. Saving a route again replaces its entry; an +// entry whose file is gone is dropped at the next save (RynthAi has no nav delete). A missing, +// locked or corrupt list only means no flags: loading never depends on it. +// +// Several clients share NavProfiles, so the read-merge-write holds the list open exclusively +// (a few tries if another client has it). Pump thread. + +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +internal static class DunRouteSidecar +{ + public const string FileName = ".rynthai-routes.json"; + public const int Version = 1; + /// The list is ignored past this size (it holds a few hundred bytes a route). + public const int MaxBytes = 4 * 1024 * 1024; + + private const int OpenTries = 6, OpenRetryMs = 15; + + /// One route the route maker wrote. + internal sealed class Entry + { + public string File = ""; + public string Sha256 = ""; + public uint Landblock; + public int Points; + public List Doorways = new(); + } + + internal static string PathIn(string folder) => Path.Combine(folder, FileName); + + internal static string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + + // ── Reading ────────────────────────────────────────────────────────────── + + /// The entries in 's list; empty when there is none. A list that + /// can't be read or isn't one: empty, says why. Never throws. + internal static List Read(string folder, out string? problem) + { + problem = null; + try + { + string path = PathIn(folder); + if (!File.Exists(path)) return new List(); + byte[]? bytes = null; + for (int i = 0; i < OpenTries && bytes == null; i++) + { + try + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + if (fs.Length > MaxBytes) { problem = $"{FileName} is over {MaxBytes / 1024 / 1024} MB: ignored"; return new List(); } + bytes = new byte[fs.Length]; + fs.ReadExactly(bytes); + } + catch (IOException) when (i + 1 < OpenTries) { Thread.Sleep(OpenRetryMs); } + } + return Parse(bytes ?? Array.Empty(), out problem); + } + catch (Exception ex) + { + problem = $"{FileName} couldn't be read ({ex.GetType().Name}: {ex.Message}): ignored"; + return new List(); + } + } + + /// The list's JSON: {"version":1,"routes":[{file, sha256, landblock, points, doorways}]}. + /// An entry with a wrong field is skipped; anything else wrong: empty, with the reason. + internal static List Parse(byte[] bytes, out string? problem) + { + problem = null; + var list = new List(); + if (bytes.Length == 0) return list; + try + { + using var doc = JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 8 }); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("routes", out var routes) || routes.ValueKind != JsonValueKind.Array) + { + problem = $"{FileName} isn't RynthAi's route list: ignored"; + return list; + } + int skipped = 0; + foreach (var r in routes.EnumerateArray()) + { + if (TryEntry(r, out var e)) list.Add(e); + else skipped++; + } + if (skipped > 0) problem = $"{FileName}: {skipped} entry(ies) not understood, skipped"; + } + catch (Exception ex) + { + problem = $"{FileName} is corrupt ({ex.Message}): ignored"; + list.Clear(); + } + return list; + } + + private static bool TryEntry(JsonElement r, out Entry e) + { + e = new Entry(); + if (r.ValueKind != JsonValueKind.Object) return false; + if (!r.TryGetProperty("file", out var f) || f.ValueKind != JsonValueKind.String) return false; + if (!r.TryGetProperty("sha256", out var h) || h.ValueKind != JsonValueKind.String) return false; + if (!r.TryGetProperty("landblock", out var lb) || lb.ValueKind != JsonValueKind.String + || !uint.TryParse(lb.GetString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out e.Landblock) || e.Landblock > 0xFFFF) return false; + if (!r.TryGetProperty("points", out var n) || n.ValueKind != JsonValueKind.Number || !n.TryGetInt32(out e.Points) || e.Points < 0) return false; + if (!r.TryGetProperty("doorways", out var d) || d.ValueKind != JsonValueKind.Array) return false; + foreach (var i in d.EnumerateArray()) + { + if (i.ValueKind != JsonValueKind.Number || !i.TryGetInt32(out int k) || k < 0 || k >= e.Points) return false; + e.Doorways.Add(k); + } + e.File = f.GetString() ?? ""; + e.Sha256 = (h.GetString() ?? "").ToLowerInvariant(); + return e.File.Length > 0 && e.Sha256.Length == 64; + } + + // ── Writing ────────────────────────────────────────────────────────────── + + /// + /// Records the route just written to \ + /// (: the file as written): its entry replaces any of that name, and + /// entries whose file is gone are dropped. False with the reason when the list couldn't be + /// written (the route itself is saved; from its file it runs without doorway flags). + /// + internal static bool Record(string folder, string fileName, byte[] bytes, uint landblock, NavRouteParser route, out string? problem) + { + problem = null; + var entry = new Entry + { + File = fileName, + Sha256 = Hash(bytes), + Landblock = landblock & 0xFFFF, + Points = route.Points.Count, + Doorways = Enumerable.Range(0, route.Points.Count).Where(i => route.Points[i].Doorway && NavRouteParser.IsPlainWaypoint(route.Points[i].Type)).ToList(), + }; + string path = PathIn(folder); + try + { + Directory.CreateDirectory(folder); + FileStream? fs = null; + for (int i = 0; i < OpenTries && fs == null; i++) + { + try { fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } + catch (IOException) when (i + 1 < OpenTries) { Thread.Sleep(OpenRetryMs); } + } + using (fs!) + { + var old = new byte[Math.Min(fs!.Length, MaxBytes)]; + fs.ReadExactly(old); + var list = Parse(old, out string? readProblem); + if (readProblem != null) problem = readProblem + " (written again)"; + list.RemoveAll(e => e.File.Equals(fileName, StringComparison.OrdinalIgnoreCase) + || !File.Exists(Path.Combine(folder, e.File))); + list.Add(entry); + list.Sort((a, b) => string.Compare(a.File, b.File, StringComparison.OrdinalIgnoreCase)); + byte[] json = Write(list); + fs.SetLength(0); + fs.Position = 0; + fs.Write(json); + } + return true; + } + catch (Exception ex) + { + problem = $"{FileName} couldn't be written ({ex.GetType().Name}: {ex.Message})"; + return false; + } + } + + private static byte[] Write(List list) + { + var buffer = new ArrayBufferWriter(256 + list.Count * 160); + using (var w = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping })) + { + w.WriteStartObject(); + w.WriteString("about", "RynthAi's dungeon route maker: the doorway points of the routes it saved here (/ra dunroute, /ra dunpatrol-save). Not a nav file."); + w.WriteNumber("version", Version); + w.WriteStartArray("routes"); + foreach (var e in list) + { + w.WriteStartObject(); + w.WriteString("file", e.File); + w.WriteString("sha256", e.Sha256); + w.WriteString("landblock", e.Landblock.ToString("X4", CultureInfo.InvariantCulture)); + w.WriteNumber("points", e.Points); + w.WriteStartArray("doorways"); + foreach (int i in e.Doorways) w.WriteNumberValue(i); + w.WriteEndArray(); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + return buffer.WrittenSpan.ToArray(); + } + + // ── A loaded route ─────────────────────────────────────────────────────── + + /// + /// The entry for the route loaded from when the route maker wrote that + /// file and it hasn't changed since (same name in the list's folder, same SHA-256, same point + /// count); else null. : one line when it is in the list but doesn't match + /// (edited), or the list couldn't be read; null when it simply isn't one of the route maker's. + /// Never throws. + /// + internal static Entry? Match(string folder, string? navPath, NavRouteParser route, out string? log) + { + log = null; + try + { + if (string.IsNullOrEmpty(navPath) || route.Points.Count == 0) return null; + string full = Path.GetFullPath(navPath); + if (!string.Equals(Path.GetDirectoryName(full), Path.GetFullPath(folder).TrimEnd('\\', '/'), StringComparison.OrdinalIgnoreCase)) return null; + if (!File.Exists(PathIn(folder)) || !File.Exists(full)) return null; + string name = Path.GetFileName(full); + var entries = Read(folder, out string? problem); + var e = entries.FirstOrDefault(x => x.File.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (e == null) + { + if (problem != null) log = $"[RynthAi] DunRoute: {problem}; '{name}' runs without doorway points"; + return null; + } + byte[] bytes = File.ReadAllBytes(full); + // The route in hand must be this file's (/ra dunnav puts a route of its own in and leaves the + // last file's path): line for line what the file holds. Not this file: nothing to say. + var lines = Encoding.UTF8.GetString(bytes).TrimStart('').Split('\n').Select(l => l.TrimEnd('\r')).ToList(); + if (lines.Count > 0 && lines[^1].Length == 0) lines.RemoveAt(lines.Count - 1); + if (!route.ToLines().SequenceEqual(lines)) return null; + string hash = Hash(bytes); + if (hash != e.Sha256) + { + log = $"[RynthAi] DunRoute: '{name}' was changed since the route maker saved it: its doorway points aren't restored (it runs with the ordinary point reach)"; + return null; + } + if (e.Points != route.Points.Count) + { + log = $"[RynthAi] DunRoute: '{name}' has {route.Points.Count} points, the route maker saved {e.Points}: its doorway points aren't restored"; + return null; + } + return e; + } + catch (Exception ex) + { + log = $"[RynthAi] DunRoute: doorway points of '{Path.GetFileName(navPath ?? "")}' not restored ({ex.GetType().Name}: {ex.Message})"; + return null; + } + } + + /// Puts the doorway flag back on the entry's points (plain waypoints only). How many. + internal static int Apply(NavRouteParser route, Entry e) + { + int n = 0; + foreach (int i in e.Doorways) + { + if (i < 0 || i >= route.Points.Count || !NavRouteParser.IsPlainWaypoint(route.Points[i].Type)) continue; + route.Points[i].Doorway = true; + n++; + } + return n; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs index f57283a..0d221bc 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs @@ -115,8 +115,11 @@ internal static partial class DungeonPathfinder /// the same origin) into rooms. A cell in /// (a hazard) never merges: it stays a room of its own. /// + /// False for a building: AC gives several walled rooms and corridors + /// one origin there, and read as one open room their openings got no doorway points, so a route + /// cut the corners into the walls between them (2026-11-06, Outdoor Hunt, B470). internal static DungeonRooms BuildRooms(Dictionary graph, DungeonGeometry geo, - IReadOnlySet? excluded = null) + IReadOnlySet? excluded = null, bool mergeSamePieces = true) { var parent = new Dictionary(graph.Count); foreach (uint c in graph.Keys) parent[c] = c; @@ -139,7 +142,8 @@ internal static partial class DungeonPathfinder // Pieces of one junction: AC builds a crossing or a corner from several cells // with the same origin (0x6544 has clusters of three). Their openings to each // other are inside the junction; kept apart, the patrol looped round them. - bool samePiece = Math.Abs(node.NS - other.NS) * 240.0 < SamePieceMeters + bool samePiece = mergeSamePieces + && Math.Abs(node.NS - other.NS) * 240.0 < SamePieceMeters && Math.Abs(node.EW - other.EW) * 240.0 < SamePieceMeters && Math.Abs(node.Z - other.Z) < SamePieceMeters; if (!wide && !samePiece) continue; @@ -309,7 +313,8 @@ internal static partial class DungeonPathfinder IReadOnlySet? hazardCells, double startNS, double startEW, double startZ, double destNS, double destEW, double destZ, - out int doorways) + out int doorways, + bool mergeSamePieces = true) { doorways = 0; var pts = new List(); @@ -324,7 +329,7 @@ internal static partial class DungeonPathfinder return tmp.Points; } - var rooms = BuildRooms(graph, geo, hazardCells); + var rooms = BuildRooms(graph, geo, hazardCells, mergeSamePieces); var steps = new List(); for (int i = 0; i + 1 < cellPath.Count; i++) { @@ -857,7 +862,8 @@ internal static partial class DungeonPathfinder // The point a patrol visits to look into a room: the middle of its cell centres when that // is on its floor, else the cell centre nearest that middle; then pushed off the walls. - private static NavPoint? RoomMiddle(Dictionary graph, DungeonGeometry geo, List cells, double wall, out uint midCell) + // (Also where /ra dunroute ... to room and "far" end: DungeonRouteMaker.) + internal static NavPoint? RoomMiddle(Dictionary graph, DungeonGeometry geo, List cells, double wall, out uint midCell) { midCell = 0; double sx = 0, sy = 0, sz = 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs index 9196e0d..4cea5c6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs @@ -58,7 +58,7 @@ internal static partial class DungeonPathfinder // same scale as Z. // - atan2(|dZ|, dHoriz) > DropAngleDeg → drop. // Near-zero horizontal distance (rooms stacked vertically) is always a drop. - private static bool IsDropEdge(DungeonNavNode a, DungeonNavNode b) + internal static bool IsDropEdge(DungeonNavNode a, DungeonNavNode b) { double dZ = Math.Abs(b.Z - a.Z); if (dZ < 0.5) return false; // trivially flat @@ -85,6 +85,11 @@ internal static partial class DungeonPathfinder return _cachedGraph; } + /// Another landblock's graph without touching the cache (the current dungeon's stays): + /// /ra dunroute info on a route made elsewhere. + internal static Dictionary GraphOf(uint landblockKey, DatDatabase cellDat) + => _cachedLandblockKey == landblockKey && _cachedGraph != null ? _cachedGraph : BuildGraph(landblockKey, cellDat); + public static void InvalidateCache() { _cachedGraph = null; diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonRouteJobs.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonRouteJobs.cs new file mode 100644 index 0000000..0a250f6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonRouteJobs.cs @@ -0,0 +1,163 @@ +// DungeonRouteJobs: the "RynthAi.Routes" interface's jobs (Shared/RynthAiRoutesApi.cs). Request +// queues one; RynthAi's tick works the oldest unfinished one (RynthAiPlugin.DunRoutes.cs, +// TickRouteJobs); Poll reads its state. The last MaxJobs are kept: a new job drops the oldest finished +// one, and with every kept job unfinished a request is refused. Ids count up from 1 and are never +// reused while this object lives (one per plugin instance: a reload forgets every job). +// Pump thread (the interface's rule); the lock only guards against a caller that breaks it. + +using System; +using System.Collections.Generic; +using System.Text.Json; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +internal enum DunJobState { Queued, Working, Done, Failed } + +internal sealed class DunRouteJob +{ + public uint Id; + public DunRouteRequest Request = null!; + public DunJobState State = DunJobState.Queued; + /// One line: what it waits for, or the answer (the chat command's line). + public string Detail = "queued"; + /// The result object (JSON) once done. + public string? ResultJson; + public long QueuedAt, StartedAt; + + public bool Finished => State is DunJobState.Done or DunJobState.Failed; +} + +internal sealed class DunRouteJobs +{ + public const int MaxJobs = RynthAiRoutesApiV1.MaxJobs; + /// A working job that still waits on the client after this long fails. + public const long WaitLimitMs = 30_000; + + private readonly object _gate = new(); + private readonly List _jobs = new(); + private uint _nextId = 1; + + /// Milliseconds clock; tests replace it. + internal Func Clock = static () => Environment.TickCount64; + + public int Count { get { lock (_gate) return _jobs.Count; } } + + /// Queues a checked request: its id, or 0 with the reason (every kept job unfinished). + public uint Add(DunRouteRequest request, out string error) + { + error = ""; + lock (_gate) + { + if (_jobs.Count >= MaxJobs) + { + int oldest = _jobs.FindIndex(j => j.Finished); + if (oldest < 0) { error = $"{MaxJobs} jobs are still unfinished: poll them until they are done, then ask again"; return 0; } + _jobs.RemoveAt(oldest); + } + var job = new DunRouteJob { Id = _nextId++, Request = request, QueuedAt = Clock() }; + if (_nextId == 0) _nextId = 1; + _jobs.Add(job); + return job.Id; + } + } + + /// The job to work this tick: the oldest unfinished one (a working job first, it is older). + public DunRouteJob? Next() + { + lock (_gate) + { + foreach (var j in _jobs) if (!j.Finished) return j; + return null; + } + } + + /// The job's work began (or still waits on the client: says what). + public void Working(DunRouteJob job, string detail) + { + lock (_gate) + { + if (job.Finished) return; + if (job.State == DunJobState.Queued) { job.State = DunJobState.Working; job.StartedAt = Clock(); } + job.Detail = detail; + } + } + + /// True when a working job has waited on the client longer than WaitLimitMs. + public bool WaitedTooLong(DunRouteJob job) => job.State == DunJobState.Working && Clock() - job.StartedAt > WaitLimitMs; + + public void Finish(DunRouteJob job, bool ok, string detail, string? resultJson) + { + lock (_gate) + { + job.State = ok ? DunJobState.Done : DunJobState.Failed; + job.Detail = detail; + job.ResultJson = ok ? resultJson : null; + } + } + + public DunRouteJob? Find(uint id) + { + lock (_gate) + foreach (var j in _jobs) if (j.Id == id) return j; + return null; + } + + public static string StateName(DunJobState s) => s switch + { + DunJobState.Queued => "queued", + DunJobState.Working => "working", + DunJobState.Done => "done", + _ => "failed", + }; + + /// Poll's answer: {"id","op","state","detail","result"}; false (and state "unknown") for an id not kept. + public bool TryPoll(uint id, out string json) + { + DunRouteJob? job; + string state, detail, op; + string? result; + lock (_gate) + { + job = null; + foreach (var j in _jobs) if (j.Id == id) { job = j; break; } + state = job != null ? StateName(job.State) : "unknown"; + detail = job?.Detail ?? (id == 0 ? "0 is never a job id (Request answers 0 when it refuses)" + : "no such job: only the last 32 are kept, and a RynthAi reload forgets them all; ask again"); + op = job != null ? DunRouteRequest.OpName(job.Request.Op) : ""; + result = job?.ResultJson; + } + json = DungeonRouteMaker.Json(w => + { + w.WriteStartObject(); + w.WriteNumber("id", id); + if (job != null) w.WriteString("op", op); + w.WriteString("state", state); + w.WriteString("detail", detail); + if (job != null) + { + w.WritePropertyName("result"); + if (result != null) w.WriteRawValue(result, skipInputValidation: true); + else w.WriteNullValue(); + } + w.WriteEndObject(); + }); + return job != null; + } + + /// Request's answer: {"id":N,"state":"queued"} or {"error":"..."}. + public static string QueuedJson(uint id) => DungeonRouteMaker.Json(w => + { + w.WriteStartObject(); + w.WriteNumber("id", id); + w.WriteString("state", "queued"); + w.WriteEndObject(); + }); + + public static string ErrorJson(string error) => DungeonRouteMaker.Json(w => + { + w.WriteStartObject(); + w.WriteString("error", error); + w.WriteEndObject(); + }); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonRouteMaker.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonRouteMaker.cs new file mode 100644 index 0000000..ec9d977 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonRouteMaker.cs @@ -0,0 +1,1051 @@ +// DungeonRouteMaker: dungeon nav routes made on demand (2026-10-30), for players (/ra dunroute, +// /ra dunpatrol-save) and for other plugins (the "RynthAi.Routes" interface, Shared/RynthAiRoutesApi.cs, +// whose header has the JSON). One implementation: RynthAiPlugin.DunRoutes.cs gathers where the +// character is (DunRouteWorld) and runs the request through here; the chat command and the +// interface only word the answer differently. +// +// A route is laid with DungeonPathfinder's own paths: A* over the cell graph (no drops, no lava/acid +// cells), then the points every dungeon path gets (BuildPathPoints: centred on narrow openings, +// straight across rooms, off the walls; without the dungeon map, cell-centre midpoints). The +// character's spot is the route's first point, so a saved route says where it starts. Portals the +// route isn't going to are kept out of (DungeonPathfinder.Portals.cs); a route to a portal stops at +// its edge and ends with a Portal step that uses it. Saved as a Once route, VTank's format, in +// NavProfiles, where RynthAi's Nav picker lists it and /ra nav load runs it. +// +// The doorway flag (NavPoint.Doorway: a tight reach, no corner cut) isn't in the .nav format, which +// stays VTank's: the flagged points are listed in NavProfiles\.rynthai-routes.json (DunRouteSidecar), +// and RynthAi puts the flags back when the unchanged file is loaded in its dungeon. +// +// Host-free: everything comes in through DunRouteWorld, so the host tests build worlds from fixtures. +// Pump thread only (DungeonPathfinder's caches). + +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// What a dungeon route goes to. +internal enum DunTargetKind { Exit, Portal, Position, Room, Far } + +/// A route's target: the exit, a portal by name, a spot (landblock-local metres), a room, the far end. +internal sealed record DunTarget(DunTargetKind Kind, string Portal = "", double X = 0, double Y = 0, double Z = 0, int Room = -1) +{ + public static readonly DunTarget Exit = new(DunTargetKind.Exit); + public static readonly DunTarget Far = new(DunTargetKind.Far); + + public static string KindName(DunTargetKind k) => k switch + { + DunTargetKind.Exit => "exit", + DunTargetKind.Portal => "portal", + DunTargetKind.Position => "position", + DunTargetKind.Room => "room", + _ => "far", + }; + + /// The target as the command takes it ("portal Surface Portal", "110.5 -3.2 -24"). + public string Words() => Kind switch + { + DunTargetKind.Portal => "portal " + Portal, + DunTargetKind.Position => string.Format(CultureInfo.InvariantCulture, "{0:0.##} {1:0.##} {2:0.##}", X, Y, Z), + DunTargetKind.Room => "room " + Room.ToString(CultureInfo.InvariantCulture), + _ => KindName(Kind), + }; + + /// + /// The words after "to" in /ra dunroute: exit, far, portal <name>, <x> <y> <z> + /// (landblock-local metres; brackets and commas round them are fine), room <n>. + /// + public static bool TryParseWords(IReadOnlyList words, out DunTarget target, out string error) + { + target = Exit; + error = ""; + if (words.Count == 0) { error = "no target after \"to\""; return false; } + string first = words[0].ToLowerInvariant(); + if (words.Count == 1 && first == "exit") { target = Exit; return true; } + if (words.Count == 1 && first == "far") { target = Far; return true; } + if (first == "portal") + { + string name = string.Join(" ", words.Skip(1)).Trim().Trim('"', '\'').Trim(); + if (name.Length == 0) { error = "\"portal\" needs the portal's name (/ra dunroute where lists them)"; return false; } + if (name.Length > DunRouteRequest.MaxPortalName) { error = $"a portal name is at most {DunRouteRequest.MaxPortalName} characters"; return false; } + target = new DunTarget(DunTargetKind.Portal, Portal: name); + return true; + } + if (first == "room") + { + if (words.Count != 2 || !int.TryParse(words[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 0) + { error = "\"room\" needs a room number, 0 or more (/ra dunroute where shows yours)"; return false; } + target = new DunTarget(DunTargetKind.Room, Room: n); + return true; + } + // Coordinates: three numbers, as /ra navdebug's local=(x,y,z) or "[110.5 -3.2 -24]". + var nums = new List(); + foreach (string w in words) + foreach (string piece in w.Split(',', StringSplitOptions.RemoveEmptyEntries)) + { + string s = piece.Trim('[', ']', '(', ')', ' '); + if (s.Length == 0) continue; + if (!double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) || !double.IsFinite(v)) + { error = $"'{string.Join(" ", words)}' isn't a target: exit, far, portal , or room "; return false; } + nums.Add(v); + } + if (nums.Count != 3) { error = $"a spot is three numbers, x y z (landblock-local metres); got {nums.Count}"; return false; } + if (nums.Any(v => Math.Abs(v) > DunRouteRequest.MaxCoordinate)) { error = $"x, y and z are landblock-local metres (within {DunRouteRequest.MaxCoordinate:0})"; return false; } + target = new DunTarget(DunTargetKind.Position, X: nums[0], Y: nums[1], Z: nums[2]); + return true; + } +} + +/// The four requests: a route to somewhere, the patrol, a saved route described, where the character is. +internal enum DunRouteOp { DunRoute, DunPatrol, Info, Where } + +/// One request, from the chat command or the interface's JSON (checked: ). +internal sealed class DunRouteRequest +{ + public const int MaxPortalName = 120; + public const double MaxCoordinate = 100_000; + + public DunRouteOp Op; + /// The route's file name in NavProfiles, without ".nav" (checked by ). + public string Name = ""; + public DunTarget? To; + public bool Overwrite; + + public static string OpName(DunRouteOp op) => op switch + { + DunRouteOp.DunRoute => "dunroute", + DunRouteOp.DunPatrol => "dunpatrol", + DunRouteOp.Info => "info", + _ => "where", + }; + + /// The name rules of every nav RynthAi saves (NewProfileFiles): tidied, then checked. + public static bool TryName(string? raw, out string name, out string error) + { + name = NewProfileFiles.Tidy(raw, NewProfileFiles.NavExtensions, out _); + error = NewProfileFiles.Validate(name) ?? ""; + if (error.Length > 0) { error = $"'{name}' can't be a route name: {error}"; return false; } + return true; + } + + private static readonly Dictionary Fields = new() + { + [DunRouteOp.DunRoute] = new[] { "op", "name", "to", "overwrite" }, + [DunRouteOp.DunPatrol] = new[] { "op", "name", "overwrite" }, + [DunRouteOp.Info] = new[] { "op", "name" }, + [DunRouteOp.Where] = new[] { "op" }, + }; + + /// + /// The interface's request (RynthAiRoutesApi.cs): one JSON object, its fields checked by op. A wrong + /// type, an unknown or repeated field, a bad name or target: false with the reason. + /// + public static bool TryParseJson(string? json, out DunRouteRequest request, out string error) + { + request = new DunRouteRequest(); + error = ""; + if (string.IsNullOrWhiteSpace(json)) { error = "no request: send a JSON object, e.g. {\"op\":\"where\"}"; return false; } + if (Encoding.UTF8.GetByteCount(json) > RynthAiRoutesApiV1.MaxRequestBytes) { error = $"the request is longer than {RynthAiRoutesApiV1.MaxRequestBytes} bytes"; return false; } + JsonDocument doc; + try { doc = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 8 }); } + catch (Exception ex) { error = "not JSON: " + ex.Message; return false; } + using (doc) + { + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) { error = "the request must be a JSON object, e.g. {\"op\":\"where\"}"; return false; } + var seen = new HashSet(StringComparer.Ordinal); + foreach (var p in root.EnumerateObject()) + if (!seen.Add(p.Name)) { error = $"\"{p.Name}\" is given twice"; return false; } + + if (!root.TryGetProperty("op", out var opEl)) { error = "\"op\" is missing: dunroute, dunpatrol, info or where"; return false; } + if (opEl.ValueKind != JsonValueKind.String) { error = "\"op\" must be a string: dunroute, dunpatrol, info or where"; return false; } + string opText = opEl.GetString() ?? ""; + DunRouteOp? op = opText switch + { + "dunroute" => DunRouteOp.DunRoute, + "dunpatrol" => DunRouteOp.DunPatrol, + "info" => DunRouteOp.Info, + "where" => DunRouteOp.Where, + _ => null, + }; + if (op is not DunRouteOp o) { error = $"\"op\" must be dunroute, dunpatrol, info or where (got \"{Clip(opText)}\")"; return false; } + request.Op = o; + + string[] allowed = Fields[o]; + foreach (var p in root.EnumerateObject()) + if (Array.IndexOf(allowed, p.Name) < 0) + { error = $"\"{Clip(p.Name)}\" isn't a field of {opText} (it takes {string.Join(", ", allowed)})"; return false; } + + if (o != DunRouteOp.Where) + { + if (!root.TryGetProperty("name", out var nameEl)) { error = $"\"name\" is missing: {opText} needs the route's name"; return false; } + if (nameEl.ValueKind != JsonValueKind.String) { error = "\"name\" must be a string"; return false; } + if (!TryName(nameEl.GetString(), out request.Name, out error)) return false; + } + if (root.TryGetProperty("overwrite", out var owEl)) + { + if (owEl.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) { error = "\"overwrite\" must be true or false"; return false; } + request.Overwrite = owEl.GetBoolean(); + } + if (o == DunRouteOp.DunRoute) + { + if (!root.TryGetProperty("to", out var toEl)) { error = "\"to\" is missing: \"exit\", \"far\", {\"portal\":name}, {\"x\":..,\"y\":..,\"z\":..} or {\"room\":n}"; return false; } + if (!TryParseTarget(toEl, out var to, out error)) return false; + request.To = to; + } + } + return true; + } + + private static bool TryParseTarget(JsonElement el, out DunTarget target, out string error) + { + target = DunTarget.Exit; + error = ""; + const string forms = "\"exit\", \"far\", {\"portal\":name}, {\"x\":..,\"y\":..,\"z\":..} or {\"room\":n}"; + if (el.ValueKind == JsonValueKind.String) + { + string s = (el.GetString() ?? "").Trim().ToLowerInvariant(); + if (s == "exit") { target = DunTarget.Exit; return true; } + if (s == "far") { target = DunTarget.Far; return true; } + error = $"\"to\" must be {forms} (got \"{Clip(el.GetString() ?? "")}\")"; + return false; + } + if (el.ValueKind != JsonValueKind.Object) { error = $"\"to\" must be {forms}"; return false; } + var seen = new HashSet(StringComparer.Ordinal); + foreach (var p in el.EnumerateObject()) + { + if (!seen.Add(p.Name)) { error = $"\"to\".\"{p.Name}\" is given twice"; return false; } + if (p.Name is not ("portal" or "x" or "y" or "z" or "room")) { error = $"\"to\" doesn't take \"{Clip(p.Name)}\": {forms}"; return false; } + } + bool hasPortal = seen.Contains("portal"), hasRoom = seen.Contains("room"); + bool hasXyz = seen.Contains("x") || seen.Contains("y") || seen.Contains("z"); + if ((hasPortal ? 1 : 0) + (hasRoom ? 1 : 0) + (hasXyz ? 1 : 0) != 1) { error = $"\"to\" is one of {forms}"; return false; } + if (hasPortal) + { + var p = el.GetProperty("portal"); + string name = p.ValueKind == JsonValueKind.String ? (p.GetString() ?? "").Trim() : ""; + if (name.Length == 0) { error = "\"to\".\"portal\" must be the portal's name (a string)"; return false; } + if (name.Length > MaxPortalName) { error = $"a portal name is at most {MaxPortalName} characters"; return false; } + target = new DunTarget(DunTargetKind.Portal, Portal: name); + return true; + } + if (hasRoom) + { + var r = el.GetProperty("room"); + if (r.ValueKind != JsonValueKind.Number || !r.TryGetInt32(out int n) || n < 0) { error = "\"to\".\"room\" must be a room number, 0 or more"; return false; } + target = new DunTarget(DunTargetKind.Room, Room: n); + return true; + } + var v = new double[3]; + string[] axes = { "x", "y", "z" }; + for (int i = 0; i < 3; i++) + { + if (!el.TryGetProperty(axes[i], out var a)) { error = $"\"to\" needs all of x, y and z (\"{axes[i]}\" is missing)"; return false; } + if (a.ValueKind != JsonValueKind.Number || !a.TryGetDouble(out v[i]) || !double.IsFinite(v[i])) + { error = $"\"to\".\"{axes[i]}\" must be a number"; return false; } + if (Math.Abs(v[i]) > MaxCoordinate) { error = $"\"to\".\"{axes[i]}\" is landblock-local metres (within {MaxCoordinate:0})"; return false; } + } + target = new DunTarget(DunTargetKind.Position, X: v[0], Y: v[1], Z: v[2]); + return true; + } + + private static string Clip(string s) => s.Length <= 40 ? s : s[..40] + "..."; +} + +/// Where the character is, for a route: the dungeon's map and what is known in it. Built by the plugin. +internal sealed class DunRouteWorld +{ + public uint Landblock; + /// The engine's cell for the character. + public uint PlayerCell; + /// The cell the route starts in: the character's when the map has it, else the nearest. + public uint StartCell; + /// The character, world metres (x east, y north, z up). + public double X, Y, Z; + public Dictionary Graph = new(); + public DungeonGeometry? Geo; + /// Lava/acid cells kept out of (the patrol's set: Settings > Dungeon Patrol decides about floors). + public IReadOnlySet? Hazards; + /// Every portal the client knows in this dungeon (their keep-out circles from the nav settings). + public List Portals = new(); + /// A portal's appraised destination text (string property 38), when the client has it. + public Func? PortalDestination; + /// Where RynthAi saw the character come into this dungeon (world metres), when it did. + public (uint Cell, double X, double Y, double Z)? Arrival; + /// The share of the floor the radar has painted as visited (null: not known). + public double? Explored; + public double Wall = DungeonPathfinder.WallClearance; + + public double OriginX => ((Landblock >> 8) & 0xFF) * 192.0; + public double OriginY => (Landblock & 0xFF) * 192.0; + + /// The hazard cells in this landblock. + public int HazardsHere => Hazards?.Count(c => c >> 16 == Landblock) ?? 0; +} + +/// A route laid to a target (before it is saved). +internal sealed class DunRouteBuild +{ + public NavRouteParser Route = new() { RouteType = NavRouteType.Once }; + public DunTargetKind Kind; + /// "the exit portal 'Surface Portal' (named like an exit)", for chat. + public string TargetText = ""; + public string Why = ""; + public PatrolPortal? Portal; + public int Room = -1; + public uint StartCell, GoalCell; + /// Where it ends (world metres): the spot, the room's middle, the portal. + public double GoalX, GoalY, GoalZ; + public int PathCells, Doorways; + public double Yards; + public readonly List LeftOut = new(); + public readonly List Notes = new(); +} + +/// A saved route described (/ra dunroute info, the interface's "info"). +internal sealed class DunRouteInfo +{ + public string Name = "", File = ""; + public NavRouteType Type; + public int Points, Waypoints; + public readonly SortedDictionary Steps = new(StringComparer.Ordinal) + { + ["portal"] = 0, ["recall"] = 0, ["pause"] = 0, ["chat"] = 0, ["jump"] = 0, ["npc"] = 0, ["vendor"] = 0, ["checkpoint"] = 0, + }; + public double Yards; + public uint? Landblock; + public readonly List Landblocks = new(); + public bool? Dungeon; + public int? Cells; + public uint StartCell, EndCell; + /// "yes", "partly", "no", "unknown" (the character isn't in a dungeon). + public string ForThisDungeon = "unknown"; + public int PointsHere; + public readonly List Notes = new(); +} + +/// One portal the client knows, as "where" lists it. +internal sealed class DunWherePortal +{ + public PatrolPortal Portal = null!; + public double Yards; + public double? WalkYards; + public string? Exit; + public string? Destination; +} + +internal static class DungeonRouteMaker +{ + /// A position target this far (yd) from every cell centre isn't in the dungeon (as NavRecovery's reach). + internal const double PositionReachYd = 30.0; + /// The exit is the portal nearest where the character came in, when it is this close (metres) to it. + internal const double ArrivalReachMeters = 40.0; + /// The object class a Portal step names (Decal's ObjectClass.Portal; VTank writes it, as RynthNav's routes). + internal const int PortalObjectClass = 14; + // Points closer than this (yd) to the one before are dropped. + private const double MinSpacingYd = 0.3; + + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + + /// Names an exit portal has: "Surface Portal", "Exit Portal", "Portal Out", "Leave the Hive". + internal static readonly Regex ExitWords = new(@"\b(exit|surface|leave|outside|out|return)\b", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// An appraised destination that is a spot on the landscape: "12.3N, 45.6E". + internal static readonly Regex LandscapeCoords = new(@"\d+(\.\d+)?\s*[NS]\s*,?\s*\d+(\.\d+)?\s*[EW]\b", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + // ── Targets ────────────────────────────────────────────────────────────── + + /// + /// Why each known portal would be the exit, best first: rank 0 its destination is a spot on the + /// landscape, 1 named like an exit, 2 the nearest to where the character came in (within + /// ArrivalReachMeters), 3 the only portal known. Wrecked portals ("Destroyed ...") never are. + /// Ties: the nearest to the character. + /// + internal static List<(PatrolPortal Portal, int Rank, string Why)> ExitCandidates(DunRouteWorld w) + { + var usable = w.Portals.Where(p => !p.Name.StartsWith("Destroyed", StringComparison.OrdinalIgnoreCase)).ToList(); + PatrolPortal? byArrival = null; + if (w.Arrival is { } a) + { + double best = ArrivalReachMeters; + foreach (var p in usable) + { + double d = Dist3(p.X, p.Y, p.Z, a.X, a.Y, a.Z); + if (d <= best) { best = d; byArrival = p; } + } + } + var list = new List<(PatrolPortal, int, string)>(); + foreach (var p in usable) + { + string? dest = Destination(w, p); + if (dest != null && LandscapeCoords.IsMatch(dest)) list.Add((p, 0, $"its destination is on the landscape ({dest})")); + else if (ExitWords.IsMatch(p.Name)) list.Add((p, 1, "named like an exit")); + else if (ReferenceEquals(p, byArrival)) list.Add((p, 2, "the portal nearest where you came in")); + else if (usable.Count == 1) list.Add((p, 3, "the only portal known here")); + } + list.Sort((x, y) => x.Item2 != y.Item2 ? x.Item2.CompareTo(y.Item2) + : DistTo(w, x.Item1).CompareTo(DistTo(w, y.Item1))); + return list; + } + + private static string? Destination(DunRouteWorld w, PatrolPortal p) + { + try + { + string? d = w.PortalDestination?.Invoke(p.Id); + return string.IsNullOrWhiteSpace(d) ? null : d.Trim(); + } + catch { return null; } + } + + private static PatrolPortal? PickExit(DunRouteWorld w, out string why, out string error) + { + why = error = ""; + var c = ExitCandidates(w); + if (c.Count > 0) { why = c[0].Why; return c[0].Portal; } + error = w.Portals.Count == 0 + ? "no portal is known in this dungeon yet. The client only knows the objects it has been sent: walk on until the exit portal shows (the radar draws portals), then try again" + : $"can't tell which portal is the exit: none is named like one, and RynthAi didn't see where you came in. Portals known: {PortalNames(w)}. Ask for one: to portal "; + return null; + } + + private static PatrolPortal? PickPortal(DunRouteWorld w, string name, out string why, out string error) + { + why = error = ""; + var exact = w.Portals.Where(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).ToList(); + var list = exact.Count > 0 ? exact : w.Portals.Where(p => p.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); + if (list.Count == 0) + { + error = w.Portals.Count == 0 + ? $"no portal named '{name}' is known: the client knows no portal in this dungeon yet (it only knows the objects it has been sent)" + : $"no portal named '{name}' is known here. Portals known: {PortalNames(w)}"; + return null; + } + var pick = list.OrderBy(p => DistTo(w, p)).First(); + why = list.Count > 1 ? $"{list.Count} portals match '{name}': the nearest" : exact.Count > 0 ? "" : $"its name has '{name}' in it"; + return pick; + } + + private static string PortalNames(DunRouteWorld w) + => string.Join(", ", w.Portals.OrderBy(p => DistTo(w, p)).Select(p => $"'{p.Name}' ({DistTo(w, p):0} yd)")); + + private static double DistTo(DunRouteWorld w, PatrolPortal p) => Dist3(p.X, p.Y, p.Z, w.X, w.Y, w.Z); + + private static uint CellOfPortal(DunRouteWorld w, PatrolPortal p) + => p.Cell != 0 && w.Graph.ContainsKey(p.Cell) ? p.Cell : DungeonPathfinder.CellAt(w.Graph, w.Geo, WorldPt(p.X, p.Y, p.Z)); + + /// + /// The cell farthest from on foot (Dijkstra over the walkable edges: no + /// drops, no hazard cells; centre to centre, climbs counted), and how far. 0 when the start has no + /// way anywhere. + /// + internal static uint FarthestCell(Dictionary graph, uint start, IReadOnlySet? hazards, out double yards) + { + yards = 0; + if (!graph.ContainsKey(start)) return 0; + var dist = WalkDistances(graph, start, hazards); + uint best = 0; + foreach (var (c, d) in dist) + if (c != start && (d > yards || (d == yards && c < best))) { yards = d; best = c; } + return best; + } + + /// Walking distance (yd, centre to centre, climbs counted) from start to every cell it reaches. + internal static Dictionary WalkDistances(Dictionary graph, uint start, IReadOnlySet? hazards) + { + var dist = new Dictionary { [start] = 0 }; + var pq = new PriorityQueue(); + pq.Enqueue(start, 0); + while (pq.TryDequeue(out uint c, out double d)) + { + if (d > dist[c] || !graph.TryGetValue(c, out var n)) continue; + foreach (uint nb in n.Neighbors) + { + if (!graph.TryGetValue(nb, out var o) || DungeonPathfinder.IsDropEdge(n, o)) continue; + if (hazards != null && hazards.Contains(nb)) continue; + double nd = d + Math.Sqrt(Sq((o.NS - n.NS) * 240.0) + Sq((o.EW - n.EW) * 240.0)) + Math.Abs(o.Z - n.Z); + if (dist.TryGetValue(nb, out double old) && old <= nd) continue; + dist[nb] = nd; + pq.Enqueue(nb, nd); + } + } + return dist; + } + + // ── Laying the route ───────────────────────────────────────────────────── + + /// + /// The route from the character to : a Once route, the character's spot first; + /// null with the reason when there is no target or no walkable way. + /// + internal static DunRouteBuild? TryBuildRoute(DunRouteWorld w, DunTarget t, out string error) + { + error = ""; + if (w.Graph.Count == 0) { error = "this dungeon has no cells on the map"; return null; } + if (!w.Graph.ContainsKey(w.StartCell)) { error = "can't place you on the dungeon map"; return null; } + var b = new DunRouteBuild { Kind = t.Kind, StartCell = w.StartCell }; + uint goal; + PatrolPortal? portal = null; + switch (t.Kind) + { + case DunTargetKind.Exit: + case DunTargetKind.Portal: + { + portal = t.Kind == DunTargetKind.Exit ? PickExit(w, out string why, out error) : PickPortal(w, t.Portal, out why, out error); + if (portal == null) return null; + b.Portal = portal; + b.Why = why; + goal = CellOfPortal(w, portal); + (b.GoalX, b.GoalY, b.GoalZ) = (portal.X, portal.Y, portal.Z); + b.TargetText = (t.Kind == DunTargetKind.Exit ? "the exit portal" : "portal") + $" '{portal.Name}'" + (why.Length > 0 ? $" ({why})" : ""); + break; + } + case DunTargetKind.Position: + { + double gx = w.OriginX + t.X, gy = w.OriginY + t.Y, gz = t.Z; + var spot = WorldPt(gx, gy, gz); + goal = DungeonPathfinder.CellAt(w.Graph, w.Geo, spot); + if (goal == 0 || !w.Graph.TryGetValue(goal, out var gn)) { error = "can't place that spot on the dungeon map"; return null; } + double off = NavYd(gn.NS - spot.NS, gn.EW - spot.EW); + bool onFloor = w.Geo != null && w.Geo.OnCellFloor(goal, gx, gy, gz); + if (!onFloor && off > PositionReachYd) + { + error = string.Format(Inv, "({0:0.##}, {1:0.##}, {2:0.##}) isn't inside this dungeon: its nearest cell is {3:0} yd away", t.X, t.Y, t.Z, off); + return null; + } + if (w.Geo != null && w.Geo.FloorCellCount > 0 && !w.Geo.OnWalkableFloor(gx, gy, gz)) + b.Notes.Add("that spot isn't on a floor the dungeon map knows (in a wall, or another height): the route still ends on it"); + (b.GoalX, b.GoalY, b.GoalZ) = (gx, gy, gz); + b.TargetText = string.Format(Inv, "({0:0.##}, {1:0.##}, {2:0.##}) in cell {3:X8}", t.X, t.Y, t.Z, goal); + break; + } + case DunTargetKind.Room: + { + if (w.Geo == null) { error = "rooms are numbered from the dungeon map, which isn't loaded yet: try again in a moment"; return null; } + var rooms = DungeonPathfinder.BuildRooms(w.Graph, w.Geo); + if (t.Room >= rooms.Cells.Count) { error = $"there is no room {t.Room}: this dungeon's rooms are 0 to {rooms.Cells.Count - 1} (/ra dunroute where says which you are in)"; return null; } + var mid = DungeonPathfinder.RoomMiddle(w.Graph, w.Geo, rooms.Cells[t.Room], w.Wall, out goal); + if (mid == null || !w.Graph.ContainsKey(goal)) { error = $"room {t.Room} has no point to go to"; return null; } + (b.GoalX, b.GoalY, b.GoalZ) = (X(mid), Y(mid), mid.Z * 240.0); + b.Room = t.Room; + b.TargetText = $"room {t.Room} ({rooms.Cells[t.Room].Count} cell{(rooms.Cells[t.Room].Count == 1 ? "" : "s")}), its middle"; + break; + } + default: + { + uint far = FarthestCell(w.Graph, w.StartCell, w.Hazards, out double walk); + if (far == 0) { error = "there is nowhere to walk to from here (no walkable way out of this cell)"; return null; } + goal = far; + var node = w.Graph[far]; + var mid = w.Geo != null ? DungeonPathfinder.RoomMiddle(w.Graph, w.Geo, new List { far }, w.Wall, out _) : null; + (b.GoalX, b.GoalY, b.GoalZ) = mid != null ? (X(mid), Y(mid), mid.Z * 240.0) + : (DungeonGeometry.NavToWorld(node.EW), DungeonGeometry.NavToWorld(node.NS), (double)node.Z); + b.TargetText = string.Format(Inv, "the farthest spot on foot, cell {0:X8} (about {1:0} yd away walking)", far, walk); + break; + } + } + b.GoalCell = goal; + if (!w.Graph.ContainsKey(goal)) { error = "the target isn't on the dungeon map"; return null; } + + // The cell path: A* without drops or hazard cells (the goal may be one). + var path = goal == w.StartCell ? new List { goal } : DungeonPathfinder.FindPath(w.StartCell, goal, w.Graph, w.Hazards); + if (path.Count == 0) + { + bool viaHazard = w.Hazards is { Count: > 0 } && DungeonPathfinder.FindPath(w.StartCell, goal, w.Graph, null).Count > 0; + error = $"{b.TargetText} can't be walked to from here: " + (viaHazard + ? "the only ways go through lava/acid cells, which routes keep out of" + : "it is only reached by a drop (a jump down the bot can't walk), or isn't joined to where you stand"); + return null; + } + b.PathCells = path.Count; + + // The points DungeonPathfinder lays on every dungeon path (as /ra dunnav, BuildNavRoute). + double sNs = DungeonGeometry.WorldToNav(w.Y), sEw = DungeonGeometry.WorldToNav(w.X); + double dNs = DungeonGeometry.WorldToNav(b.GoalY), dEw = DungeonGeometry.WorldToNav(b.GoalX); + var pts = new List { WorldPt(w.X, w.Y, w.Z) }; + if (w.Geo != null && w.Geo.DoorwayCount > 0) + { + var laid = DungeonPathfinder.BuildPathPoints(path, w.Graph, w.Geo, w.Hazards, sNs, sEw, w.Z, dNs, dEw, b.GoalZ, out int doorways); + foreach (var p in laid) Append(pts, p); + b.Doorways = doorways; + Append(pts, WorldPt(b.GoalX, b.GoalY, b.GoalZ)); + } + else + { + var cellRoute = DungeonPathfinder.BuildNavRoute(path, w.Graph, dNs, dEw); + if (cellRoute.Points.Count > 0) cellRoute.Points[^1].Z = b.GoalZ / 240.0; // the cell walk leaves the end's height out + foreach (var p in cellRoute.Points) Append(pts, p); + if (w.Geo == null) b.Notes.Add("the dungeon map isn't loaded yet: the points are cell-centre midpoints, not lined up on doorways (make it again in a moment for a better one)"); + } + if (pts.Count == 1) pts.Add(WorldPt(b.GoalX, b.GoalY, b.GoalZ)); + + // A portal target: the route stops at its edge, and a Portal step uses it. + NavPoint? step = null; + if (portal != null) + { + Append(pts, WorldPt(portal.X, portal.Y, portal.Z)); // the centre (already the end when the map laid the path) + var approach = StopAtPortal(pts, portal); + step = new NavPoint + { + Type = NavPointType.PortalNPC, NS = approach.NS, EW = approach.EW, Z = approach.Z, + TargetName = portal.Name, ObjectClass = PortalObjectClass, IsTie = true, + PortalExitNS = DungeonGeometry.WorldToNav(portal.Y), PortalExitEW = DungeonGeometry.WorldToNav(portal.X), PortalExitZ = portal.Z / 240.0, + }; + } + + // The portals it isn't going to: kept out of, as the patrol is (a portal fires at a touch). + var others = w.Portals.Where(p => !ReferenceEquals(p, portal)).ToList(); + if (others.Count > 0) + { + var reports = others.Select(p => new PortalAvoidance { Portal = p }).ToList(); + var unresolved = DungeonPathfinder.KeepOutOfPortals(pts, closed: false, w.Graph, w.Geo, others, reports, w.Wall); + foreach (var r in reports) + if (r.Moved + r.Dropped + r.Bent > 0) b.LeftOut.Add($"kept out of portal '{r.Portal.Name}' ({r.Bent} leg(s) bent round it, {r.Moved + r.Dropped} point(s) moved)"); + foreach (var (k, _) in unresolved.GroupBy(u => u.Portal).Select(g => g.First())) + b.Notes.Add($"a leg passes portal '{others[k].Name}' closer than {others[k].Radius:0.#} m: no way round was found, and touching it takes you through"); + } + if (step != null) pts.Add(step); + + b.Route = new NavRouteParser { RouteType = NavRouteType.Once, Points = pts }; + b.Yards = RouteYards(b.Route); + int hz = w.HazardsHere; + if (hz > 0) b.LeftOut.Add($"{hz} lava/acid cell{(hz == 1 ? "" : "s")} kept out of"); + AddKnownNotes(w, b.Notes); + return b; + } + + /// + /// Cuts (the character first, the portal's centre last) where it first comes + /// to the portal's circle on its level, and returns the spot: the route ends there and the Portal + /// step uses the portal (the client walks the last metres itself). + /// + internal static NavPoint StopAtPortal(List pts, PatrolPortal p) + { + if (DungeonPathfinder.InsidePortal(p, X(pts[0]), Y(pts[0]), pts[0].Z * 240.0)) + { + pts.RemoveRange(1, pts.Count - 1); + return pts[0]; + } + for (int i = 0; i + 1 < pts.Count; i++) + { + var a = pts[i]; var b = pts[i + 1]; + if (DungeonPathfinder.LegDistance(p, a, b, out _) >= p.Radius - 0.01) continue; + double ax = X(a), ay = Y(a), az = a.Z * 240.0, bx = X(b), by = Y(b), bz = b.Z * 240.0; + double len = Math.Sqrt(Sq(bx - ax) + Sq(by - ay)); + int n = Math.Max(1, (int)Math.Ceiling(len / 0.1)); + NavPoint last = a; + for (int k = 1; k <= n; k++) + { + double s = (double)k / n; + double x = ax + (bx - ax) * s, y = ay + (by - ay) * s, z = az + (bz - az) * s; + if (DungeonPathfinder.InsidePortal(p, x, y, z)) break; + last = WorldPt(x, y, z); + } + pts.RemoveRange(i + 1, pts.Count - i - 1); + if (!ReferenceEquals(last, a)) Append(pts, last); + return pts[^1]; + } + pts.RemoveAt(pts.Count - 1); // never in the circle (another level): the route ends where it got to + return pts[^1]; + } + + /// The notes every answer carries about what isn't known yet. + internal static void AddKnownNotes(DunRouteWorld w, List notes) + { + notes.Add(w.Portals.Count == 0 + ? "no portal is known here yet (the client only knows the ones it has been sent)" + : $"{w.Portals.Count} portal{(w.Portals.Count == 1 ? "" : "s")} known here (the client only knows the ones it has been sent)"); + if (w.Explored is double e && e < 0.995) + notes.Add(string.Format(Inv, "{0:0}% of this dungeon's floor explored: lava/acid not sighted yet isn't kept out of", e * 100)); + } + + /// The walked length of a route (yd): legs between plain waypoints, a step (portal, recall, + /// chat...) breaks the walk; a Circular route's closing leg counted. + internal static double RouteYards(NavRouteParser route) + { + double total = 0; + var p = route.Points; + for (int i = 0; i + 1 < p.Count; i++) + if (NavRouteParser.IsPlainWaypoint(p[i].Type) && NavRouteParser.IsPlainWaypoint(p[i + 1].Type)) + total += Leg3(p[i], p[i + 1]); + if (route.RouteType == NavRouteType.Circular && p.Count > 2 + && NavRouteParser.IsPlainWaypoint(p[^1].Type) && NavRouteParser.IsPlainWaypoint(p[0].Type)) + total += Leg3(p[^1], p[0]); + return total; + } + + /// Cells the walkable graph reaches from (no drops, no hazard cells). + internal static int ReachableCount(Dictionary graph, uint start, IReadOnlySet? hazards) + => graph.ContainsKey(start) ? WalkDistances(graph, start, hazards).Count : 0; + + // ── Info ───────────────────────────────────────────────────────────────── + + /// + /// A saved route described: its points and steps, walked length, the landblock(s) its points are + /// in, the cells under them, and whether it was made for the dungeon the character is in + /// (: 0 or a landscape cell = not in one), judged as NavigationEngine's + /// area hold judges each waypoint (NavRecoveryPlanner.ClassifyArea). : + /// a landblock's cell graph (null: the dats aren't loaded); : whether + /// a landblock is a dungeon (null: can't tell). + /// + internal static DunRouteInfo DescribeRoute(string name, string file, NavRouteParser route, uint playerCell, + Func?> graphOf, Func isDungeon) + { + var info = new DunRouteInfo { Name = name, File = file, Type = route.RouteType, Points = route.Points.Count }; + foreach (var p in route.Points) + { + if (NavRouteParser.IsPlainWaypoint(p.Type)) info.Waypoints++; + string? key = p.Type switch + { + NavPointType.PortalNPC => "portal", + NavPointType.Recall => "recall", + NavPointType.Pause => "pause", + NavPointType.Chat => "chat", + NavPointType.Jump => "jump", + NavPointType.Npc => "npc", + NavPointType.OpenVendor => "vendor", + NavPointType.Checkpoint => "checkpoint", + _ => null, + }; + if (key != null) info.Steps[key]++; + } + info.Yards = RouteYards(route); + if (route.RouteType == NavRouteType.Follow) info.Notes.Add($"a Follow route: it follows '{route.FollowTargetName}' and has no points"); + + var walk = route.Points.Where(p => NavRouteParser.IsPlainWaypoint(p.Type)).ToList(); + var byLb = new Dictionary(); + foreach (var p in walk) + if (LandblockOf(p) is uint lb) byLb[lb] = byLb.GetValueOrDefault(lb) + 1; + foreach (var kv in byLb.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key)) info.Landblocks.Add(kv.Key); + + // The character's dungeon, as the engine's area hold sees it (the same landblock, or within reach of its cells). + uint pLb = playerCell >> 16; + bool playerInDungeon = playerCell != 0 && (playerCell & 0xFFFF) >= 0x0100 && isDungeon(pLb) == true; + Dictionary? playerGraph = playerInDungeon ? graphOf(pLb) : null; + if (playerInDungeon && playerGraph != null) + { + foreach (var p in walk) + { + var a = NavRecoveryPlanner.ClassifyArea(playerCell, p.NS, p.EW, lb => lb == pLb || isDungeon(lb) == true, + (lb, ns, ew) => lb == pLb && NearCell(playerGraph, ns, ew, NavRecoveryPlanner.AreaCellReachYd), out _, out _); + if (a == NavAreaCheck.Match) info.PointsHere++; + } + info.ForThisDungeon = walk.Count == 0 ? "unknown" : info.PointsHere == walk.Count ? "yes" : info.PointsHere == 0 ? "no" : "partly"; + } + else if (playerCell != 0 && (playerCell & 0xFFFF) >= 0x0100 && playerGraph == null && isDungeon(pLb) == true) + info.Notes.Add("the dungeon data isn't loaded yet: whether it is this dungeon's can't be told"); + else info.Notes.Add("you aren't in a dungeon: \"forThisDungeon\" is unknown"); + + // The route's landblock: the character's dungeon when its points are there. Else the dungeon whose + // cells most of its points are near, of the landblocks they fall in and the ones round them (a + // dungeon's cells can lie outside its own 192 m square: Tiny Hive 0x0289's are in 0x0288's), else + // where most of them are (a landscape route). + uint? routeLb = null; + Dictionary? g = null; + if (playerGraph != null && info.PointsHere > 0 && info.PointsHere * 2 >= walk.Count) { routeLb = pLb; g = playerGraph; } + else + { + var candidates = new SortedSet(); + foreach (uint lb in info.Landblocks) + for (int dx = -1; dx <= 1; dx++) + for (int dy = -1; dy <= 1; dy++) + { + int x = (int)(lb >> 8) + dx, y = (int)(lb & 0xFF) + dy; + if (x >= 0 && x < 256 && y >= 0 && y < 256) candidates.Add(((uint)x << 8) | (uint)y); + } + // Most points in one of its cells (height counted: dungeons next to each other overlap in plan, + // at other depths), and at least half of them. + int bestNear = 0; + foreach (uint c in candidates) + { + if (isDungeon(c) != true) continue; + var cg = c == pLb && playerGraph != null ? playerGraph : graphOf(c); + if (cg == null || cg.Count == 0) continue; + int near = walk.Count(p => InCellOf(cg, p, out _)); + if (near > bestNear && near * 2 >= walk.Count) { bestNear = near; routeLb = c; g = cg; } + } + if (routeLb == null && info.Landblocks.Count > 0) routeLb = info.Landblocks[0]; + } + info.Landblock = routeLb; + if (routeLb is uint rl) + { + info.Dungeon = g != null ? true : isDungeon(rl); + if (g != null && g.Count > 0) + { + var cells = new HashSet(); + uint first = 0, last = 0; + foreach (var p in walk) + { + if (!InCellOf(g, p, out uint c)) continue; + cells.Add(c); + if (first == 0) first = c; + last = c; + } + info.Cells = cells.Count; + info.StartCell = first; + info.EndCell = last; + } + if (info.Dungeon == false) info.Notes.Add($"landblock {rl:X4} isn't a dungeon: a landscape (or town) route"); + if (info.ForThisDungeon is "no" or "partly" && rl != pLb) + info.Notes.Add($"it was made in landblock {rl:X4}; you are in {pLb:X4}"); + } + return info; + } + + /// The landblock a nav point's coordinates fall in (null: off the map). + internal static uint? LandblockOf(NavPoint p) + { + double wx = DungeonGeometry.NavToWorld(p.EW), wy = DungeonGeometry.NavToWorld(p.NS); + if (wx < 0 || wy < 0 || wx >= 256 * 192.0 || wy >= 256 * 192.0) return null; + return ((uint)(wx / 192.0) << 8) | (uint)(wy / 192.0); + } + + // A point is in a cell when the nearest cell origin on its level is this close (a big cell's corner is + // ~15 m from its origin) and within this much height. Z 0 is "not recorded" (old routes): plan only. + private const double InCellReachYd = 20.0, InCellRise = 8.0; + + /// The cell of a route point is in, by its origin's distance and height. + private static bool InCellOf(Dictionary graph, NavPoint p, out uint cell) + { + cell = DungeonPathfinder.NearestCell(graph, p.NS, p.EW, p.Z != 0 ? (float)(p.Z * 240.0) : float.NaN); + if (cell == 0 || !graph.TryGetValue(cell, out var n)) return false; + if (NavYd(n.NS - p.NS, n.EW - p.EW) > InCellReachYd) return false; + return p.Z == 0 || Math.Abs(n.Z - p.Z * 240.0) <= InCellRise; + } + + private static bool NearCell(Dictionary graph, double ns, double ew, double reachYd) + { + foreach (var n in graph.Values) + if (NavYd(n.NS - ns, n.EW - ew) <= reachYd) return true; + return false; + } + + // ── Where ──────────────────────────────────────────────────────────────── + + /// Every known portal with its distance (straight, and on foot along the cell path), why it + /// would be the exit, and its appraised destination; nearest first. + internal static List PortalsWhere(DunRouteWorld w) + { + var exits = new Dictionary(); // PatrolPortal is compared by reference + foreach (var c in ExitCandidates(w)) exits[c.Portal] = c.Why; + var list = new List(); + foreach (var p in w.Portals) + { + var e = new DunWherePortal { Portal = p, Yards = DistTo(w, p), Destination = Destination(w, p) }; + if (exits.TryGetValue(p, out string? why)) e.Exit = why; + uint cell = CellOfPortal(w, p); + if (w.Graph.ContainsKey(w.StartCell) && w.Graph.ContainsKey(cell)) + { + var path = cell == w.StartCell ? new List { cell } : DungeonPathfinder.FindPath(w.StartCell, cell, w.Graph, w.Hazards); + if (path.Count > 0) + { + double len = 0, px = w.X, py = w.Y, pz = w.Z; + for (int i = 1; i < path.Count; i++) + { + var n = w.Graph[path[i]]; + double nx = DungeonGeometry.NavToWorld(n.EW), ny = DungeonGeometry.NavToWorld(n.NS); + len += Dist3(px, py, pz, nx, ny, n.Z); + (px, py, pz) = (nx, ny, n.Z); + } + e.WalkYards = len + Dist3(px, py, pz, p.X, p.Y, p.Z); + } + } + list.Add(e); + } + list.Sort((a, b) => a.Yards.CompareTo(b.Yards)); + return list; + } + + // ── Files ──────────────────────────────────────────────────────────────── + + /// RynthAi's route folder (what its Nav picker lists). Settable: the host tests point it at their scratch folder. + internal static string Folder = LegacyNavigationUi.NavFolder; + + internal static string PathFor(string name) => Path.Combine(Folder, name + ".nav"); + + /// + /// Writes to NavProfiles\<name>.nav. An existing file is replaced only + /// with ; otherwise nothing is written and the error says so. A failed + /// write says why (DataWriteGuard: access denied, read-only, in use... and the fix). Then its + /// doorway points (and , the dungeon) go into NavProfiles' + /// .rynthai-routes.json (DunRouteSidecar), which the .nav format can't hold; a problem there goes + /// to , the route is saved either way. + /// + internal static bool TrySave(string name, NavRouteParser route, bool overwrite, uint landblock, out string path, out bool overwrote, + out string error, List? notes = null) + { + path = ""; + overwrote = false; + if (!DunRouteRequest.TryName(name, out name, out error)) return false; + path = PathFor(name); + overwrote = File.Exists(path); + if (overwrote && !overwrite) { error = AlreadyThere(name); return false; } + string target = path; + if (!DataWriteGuard.TrySave("the route", target, () => route.Save(target), out string why, callerShows: true)) + { + error = $"{name}.nav NOT saved: {why}"; + overwrote = false; + return false; + } + string? problem; + try + { + if (!DunRouteSidecar.Record(Folder, Path.GetFileName(target), File.ReadAllBytes(target), landblock, route, out problem)) + problem = $"its doorway points couldn't be recorded ({problem}): from the file it runs with the ordinary point reach"; + } + catch (Exception ex) { problem = $"its doorway points couldn't be recorded ({ex.Message}): from the file it runs with the ordinary point reach"; } + if (problem != null) notes?.Add(problem); + return true; + } + + /// The route's doorway points (the ones the sidecar keeps). + internal static int DoorwayPoints(NavRouteParser route) => route.Points.Count(p => p.Doorway && NavRouteParser.IsPlainWaypoint(p.Type)); + + internal static string AlreadyThere(string name) => $"{name}.nav is already in NavProfiles: add overwrite to replace it"; + + // ── JSON answers (RynthAiRoutesApi.cs has the shapes) ──────────────────── + + // Text as written ("isn't", "Settings > Dungeon Patrol"): the answers go to another plugin, not into a web page. + // Quotes, backslashes and control characters are still escaped. + private static readonly JsonWriterOptions JsonOptions = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + + internal static string Json(Action write) + { + var buffer = new ArrayBufferWriter(512); + using (var w = new Utf8JsonWriter(buffer, JsonOptions)) write(w); + return Encoding.UTF8.GetString(buffer.WrittenSpan); + } + + internal static string Hex(uint v, int digits) => v.ToString(digits == 4 ? "X4" : "X8", Inv); + + private static double R2(double v) => Math.Round(v, 2); + + /// {"cell","x","y","z"} for a world spot, x/y/z landblock-local. + internal static void WriteSpot(Utf8JsonWriter j, DunRouteWorld w, uint cell, double x, double y, double z) + { + j.WriteStartObject(); + j.WriteString("cell", Hex(cell, 8)); + j.WriteNumber("x", R2(x - w.OriginX)); + j.WriteNumber("y", R2(y - w.OriginY)); + j.WriteNumber("z", R2(z)); + j.WriteEndObject(); + } + + private static void WriteList(Utf8JsonWriter j, string key, IEnumerable items) + { + j.WriteStartArray(key); + foreach (string s in items) j.WriteStringValue(s); + j.WriteEndArray(); + } + + internal static void WriteCounts(Utf8JsonWriter j, NavRouteParser route, string type) + { + j.WriteString("type", type); + j.WriteNumber("points", route.Points.Count); + j.WriteNumber("waypoints", route.Points.Count(p => NavRouteParser.IsPlainWaypoint(p.Type))); + j.WriteNumber("yards", Math.Round(RouteYards(route), 1)); + } + + internal static string RouteJson(DunRouteWorld w, DunRouteBuild b, string name, string file, bool overwrote) => Json(j => + { + j.WriteStartObject(); + j.WriteString("file", file); + j.WriteString("name", name); + WriteCounts(j, b.Route, "once"); + j.WriteString("landblock", Hex(w.Landblock, 4)); + j.WritePropertyName("from"); + WriteSpot(j, w, w.PlayerCell, w.X, w.Y, w.Z); + j.WriteStartObject("to"); + j.WriteString("kind", DunTarget.KindName(b.Kind)); + if (b.Portal != null) { j.WriteString("portal", b.Portal.Name); j.WriteString("id", Hex(b.Portal.Id, 8)); } + else { j.WriteNull("portal"); j.WriteNull("id"); } + if (b.Room >= 0) j.WriteNumber("room", b.Room); + j.WriteString("cell", Hex(b.GoalCell, 8)); + j.WriteNumber("x", R2(b.GoalX - w.OriginX)); + j.WriteNumber("y", R2(b.GoalY - w.OriginY)); + j.WriteNumber("z", R2(b.GoalZ)); + j.WriteString("why", b.Why); + j.WriteEndObject(); + j.WriteNumber("cells", b.PathCells); + j.WriteNumber("doorways", b.Doorways); + j.WriteNumber("doorwayPoints", DoorwayPoints(b.Route)); + j.WriteBoolean("overwrote", overwrote); + WriteList(j, "leftOut", b.LeftOut); + WriteList(j, "notes", b.Notes); + j.WriteEndObject(); + }); + + internal static string InfoJson(DunRouteInfo i) => Json(j => + { + j.WriteStartObject(); + j.WriteString("file", i.File); + j.WriteString("name", i.Name); + j.WriteString("type", TypeName(i.Type)); + j.WriteNumber("points", i.Points); + j.WriteNumber("waypoints", i.Waypoints); + j.WriteStartObject("steps"); + foreach (var (k, v) in i.Steps) j.WriteNumber(k, v); + j.WriteEndObject(); + j.WriteNumber("yards", Math.Round(i.Yards, 1)); + if (i.Landblock is uint lb) j.WriteString("landblock", Hex(lb, 4)); else j.WriteNull("landblock"); + WriteList(j, "landblocks", i.Landblocks.Select(l => Hex(l, 4))); + if (i.Dungeon is bool d) j.WriteBoolean("dungeon", d); else j.WriteNull("dungeon"); + if (i.Cells is int c) j.WriteNumber("cells", c); else j.WriteNull("cells"); + if (i.StartCell != 0) j.WriteString("startCell", Hex(i.StartCell, 8)); else j.WriteNull("startCell"); + if (i.EndCell != 0) j.WriteString("endCell", Hex(i.EndCell, 8)); else j.WriteNull("endCell"); + j.WriteString("forThisDungeon", i.ForThisDungeon); + j.WriteNumber("pointsHere", i.PointsHere); + WriteList(j, "notes", i.Notes); + j.WriteEndObject(); + }); + + internal static string TypeName(NavRouteType t) => t switch + { + NavRouteType.Circular => "circular", + NavRouteType.Linear => "linear", + NavRouteType.Follow => "follow", + NavRouteType.Once => "once", + _ => ((int)t).ToString(Inv), + }; + + // ── Helpers ────────────────────────────────────────────────────────────── + + // Adds p unless it is on top of the last point. + private static void Append(List pts, NavPoint p) + { + if (pts.Count > 0 && NavYd(pts[^1].NS - p.NS, pts[^1].EW - p.EW) < MinSpacingYd && Math.Abs(pts[^1].Z - p.Z) * 240.0 < 0.5) + { + pts[^1].Doorway |= p.Doorway; + return; + } + pts.Add(p); + } + + internal static NavPoint WorldPt(double x, double y, double z) => new() + { + Type = NavPointType.Point, + EW = DungeonGeometry.WorldToNav(x), + NS = DungeonGeometry.WorldToNav(y), + Z = z / 240.0, + }; + + private static double Leg3(NavPoint a, NavPoint b) + => Math.Sqrt(Sq((a.NS - b.NS) * 240.0) + Sq((a.EW - b.EW) * 240.0) + Sq((a.Z - b.Z) * 240.0)); + + private static double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW); + private static double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS); + private static double NavYd(double dNs, double dEw) => Math.Sqrt(dNs * dNs + dEw * dEw) * 240.0; + private static double Dist3(double ax, double ay, double az, double bx, double by, double bz) => Math.Sqrt(Sq(ax - bx) + Sq(ay - by) + Sq(az - bz)); + private static double Sq(double v) => v * v; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs index 250126f..3626d83 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs @@ -216,7 +216,7 @@ public sealed partial class RynthAiPlugin LootDiag($"[RynthAi] Ground loot: pickup confirmed for 0x{(uint)id:X8} '{_groundTargetName}'."); if (DescribeLootPickup(id, _groundTargetAction, _groundTargetName, _groundTargetRule, _groundTargetIsSalvage, IsStackAtSend(id), where: "ground") is { } described) - Host.WriteToChat(described.Line, described.ChatType); + WriteItemInfoLine(described.Line, described.ChatType); else ChatLine($"[RynthAi] Looted [{_groundTargetAction}] {_groundTargetName} (ground)"); if (_groundTargetIsSalvage) diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs index 904a480..9975639 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs @@ -99,6 +99,13 @@ public sealed class MagItemInfoSettings /// Chat type for pet-style lines 2+, or . public int DetailChatType = SameAsHeader; /// + /// "Info text colour" (2026-11-05): "#RRGGBB" draws every item info line (name, details, the + /// described "Looted" line, your ratings) in that colour in RynthCore's chat, whatever its chat + /// type; the type still picks the tab and AC's own chat window, which can only show the type's + /// colour. "" = the type's own colour (the default, and every profile before it). + /// + public string TextColor = string.Empty; + /// /// Text put in front of every line. RynthChat files lines starting "[RynthAi Item] " under /// its Items tab (ChatClassifier.IsItemInfo). /// @@ -131,6 +138,7 @@ public sealed class MagItemInfoSettings if (Layout is not (LayoutOneLine or LayoutPetLines)) Layout = LayoutPetLines; Prefix ??= string.Empty; if (Prefix.Length > 32) Prefix = Prefix[..32]; + TextColor = MagItemInfoCatalog.NormalizeTextColor(TextColor) ?? string.Empty; } /// Back to first-run defaults (window stays open). @@ -148,7 +156,7 @@ public sealed class MagItemInfoSettings HiddenFields = d.HiddenFields; HiddenRatings = d.HiddenRatings; ShowValueAndBurden = d.ShowValueAndBurden; SpellMode = d.SpellMode; MaxListedSpells = d.MaxListedSpells; - ChatType = d.ChatType; Prefix = d.Prefix; + ChatType = d.ChatType; Prefix = d.Prefix; TextColor = d.TextColor; } } @@ -240,6 +248,84 @@ public static class MagItemInfoCatalog (25, "25 - Salvaging"), }; + /// + /// Named choices for ("" first: the chat type's own + /// colour). The chat ones are AC's own colours for those chat types, as RynthCore's chat draws + /// them with Retail colours on (the engine's ChatLineColors.RetailArgbByType); the last two are + /// RynthCore's own tab colours. Word is what /ra iteminfo color takes. + /// + public static readonly (string Word, string Label, string Color)[] TextColors = + { + ("default", "Chat type's own colour", ""), + ("allegiance", "Allegiance (orange)", "#EE921E"), + ("fellowship", "Fellowship / tell (yellow)", "#FFFF3F"), + ("tellout", "Tell you send (olive)", "#D2D264"), + ("speech", "Speech (white)", "#FFFFFF"), + ("emote", "Emote (grey)", "#D2D2C8"), + ("system", "System (purple)", "#FF7FFF"), + ("channels", "Channels (rose)", "#FF9696"), + ("combat", "Combat (red)", "#FF3F3F"), + ("magic", "Magic (light blue)", "#3FBFFF"), + ("advancement", "Advancement (cyan)", "#3FDCDC"), + ("broadcast", "Broadcast (green)", "#80FF7F"), + ("items", "Items tab (teal)", "#9FD8C8"), + ("rynth", "Rynth tab (amber)", "#E6B450"), + }; + + /// + /// "#RRGGBB" (upper case) for "#rrggbb", "rrggbb" or "0xRRGGBB"; "" for ""; null for anything else. + /// + public static string? NormalizeTextColor(string? s) + { + string v = (s ?? string.Empty).Trim(); + if (v.Length == 0) return string.Empty; + if (v.StartsWith('#')) v = v[1..]; + else if (v.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) v = v[2..]; + if (v.Length != 6) return null; + foreach (char c in v) + if (!Uri.IsHexDigit(c)) return null; + return "#" + v.ToUpperInvariant(); + } + + /// + /// /ra iteminfo color's argument: a word ("allegiance", "default", + /// "none" / "off" / "type" / "" = ""), or a colour code. Null when it is neither. + /// + public static string? ParseTextColor(string arg) + { + string a = arg.Trim(); + if (a.Length == 0 || a.Equals("none", StringComparison.OrdinalIgnoreCase) || a.Equals("off", StringComparison.OrdinalIgnoreCase) + || a.Equals("type", StringComparison.OrdinalIgnoreCase)) + return string.Empty; + foreach (var c in TextColors) + if (c.Word.Equals(a, StringComparison.OrdinalIgnoreCase)) return c.Color; + return NormalizeTextColor(a); + } + + /// A colour as the window and the command reply name it: its label, else the code. + public static string TextColorLabel(string color) + { + foreach (var c in TextColors) + if (string.Equals(c.Color, color, StringComparison.OrdinalIgnoreCase)) return c.Color.Length > 0 ? $"{c.Label} {c.Color}" : c.Label; + return color; + } + + /// "#RRGGBB" as 0..1 RGB for ImGui's colour picker (white when it isn't a colour). + public static System.Numerics.Vector3 TextColorRgb(string color) + { + string? n = NormalizeTextColor(color); + if (string.IsNullOrEmpty(n)) return System.Numerics.Vector3.One; + int v = Convert.ToInt32(n[1..], 16); + return new System.Numerics.Vector3(((v >> 16) & 0xFF) / 255f, ((v >> 8) & 0xFF) / 255f, (v & 0xFF) / 255f); + } + + /// 0..1 RGB from ImGui's colour picker as "#RRGGBB". + public static string TextColorFromRgb(System.Numerics.Vector3 rgb) + { + static int B(float f) => (int)MathF.Round(Math.Clamp(f, 0f, 1f) * 255f); + return $"#{B(rgb.X):X2}{B(rgb.Y):X2}{B(rgb.Z):X2}"; + } + /// Field by enum name or label word, case-insensitive ("ratings", "slayer", "typemastery"). public static bool TryFindField(string key, out MagItemInfoField field) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs index 28b6f65..9c8929c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs @@ -17,11 +17,15 @@ // proof (ChestOpenedAt). // * Looting: the chest is handed to the corpse looter (the CURRENT loot profile's rules, the // same TickOpenCorpseLooting as a corpse) and this waits for it to finish and close it. -// * Waiting: a chest re-locks and regenerates on a timer after it was opened (ACE Chest.Reset, -// ResetInterval, default 120 s). The next cycle starts after RegenWaitMs; where the client -// reads the chest as locked it starts earlier. A key use that answers "already unlocked" on -// a later cycle means the timer has not run yet: it waits ProbeMs and asks again, at most -// MaxProbes times. +// * Waiting: a chest re-locks and regenerates on a timer after it was opened (ACE Chest.Open +// queues Chest.Reset ResetInterval seconds later; default 120 s, never under 15 s, and a +// ChestRegenOnClose chest resets as it closes). The next cycle starts RelockWaitSec after +// the open (the Item Tool's "Chest re-lock wait (s)", 2026-11-05; default 125 s, which +// covers ACE's default); where the client reads the chest as locked again (Reset's +// Locked=true public update) it starts earlier. A key use that answers "already unlocked" +// on a later cycle means the timer has not run yet (nothing is spent): it waits ProbeEveryMs +// (the wait, 5..30 s) and asks again, for at most MaxProbes * ProbeMs (4 min) of asking. So +// a wait shorter than the chest's own timer costs one unspent key use per probe, never a key. // // Out of keys: the key item is gone (used up: "Your key is used up."; no other carried item has // its name) after a cycle, or before one. A key with unlimited uses never runs out: MaxCycles @@ -85,13 +89,27 @@ internal sealed class ChestKeyLooter public const long ChatSettleMs = 250; /// After the chest's answer, it gets this long to read open before the open counts as failed. public const long OpenSettleMs = 1500; - /// The next cycle starts this long after the chest was opened (ACE's default chest reset is 120 s). - public const long RegenWaitMs = 125_000; + /// + /// "Chest re-lock wait (s)": the next cycle starts this long after the chest was opened. The + /// default covers ACE's default chest reset (120 s). The least, 5 s, still sends nothing faster + /// than one key use per 5 s: each waits for its answer, a too-early one answers "already + /// unlocked" and spends nothing, and the asking is bounded (MaxProbes * ProbeMs). Under 15 s + /// only a chest that resets as it closes (ChestRegenOnClose) can be ready; ACE floors every + /// timed reset at 15 s. + /// + public const int DefaultRelockWaitSec = 125, MinRelockWaitSec = 5, MaxRelockWaitSec = 600; + /// The default wait in ms (DefaultRelockWaitSec). + public const long RegenWaitMs = DefaultRelockWaitSec * 1000L; /// A chest the client reads as locked is tried again this soon after it was opened. public const long MinRelockMs = 15_000; - /// Asking a chest that was still unlocked again. + /// Asking a chest that was still unlocked again: at most this long apart (ProbeEveryMs follows a shorter wait). public const long ProbeMs = 30_000; + /// ... and at least this long apart. + public const long MinProbeMs = MinRelockWaitSec * 1000L; + /// The asking lasts MaxProbes * ProbeMs (MaxProbes asks at the default wait). public const int MaxProbes = 8; + + public static int ClampRelockWaitSec(int seconds) => Math.Clamp(seconds, MinRelockWaitSec, MaxRelockWaitSec); /// Nothing may go out for this long (combat, busy client...) before the run stops. public const long HoldMaxMs = 90_000; /// The loot session may take this long. @@ -125,11 +143,25 @@ internal sealed class ChestKeyLooter /// What the run did last, for the status line when it is not running. public string LastResult { get; private set; } = ""; + /// "Chest re-lock wait (s)" (the host sets it from the settings each tick; clamped). A change applies to a wait already running. + public int RelockWaitSec + { + get => _relockWaitSec; + set => _relockWaitSec = ClampRelockWaitSec(value); + } + private int _relockWaitSec = DefaultRelockWaitSec; + + private long RelockWaitMs => _relockWaitSec * 1000L; + /// How far apart a chest that was still unlocked is asked again: the wait, 5..30 s. + internal long ProbeEveryMs => Math.Clamp(RelockWaitMs, MinProbeMs, ProbeMs); + /// How many asks fit in MaxProbes * ProbeMs (MaxProbes at the default wait). + internal int ProbeLimit => (int)((MaxProbes * ProbeMs + ProbeEveryMs - 1) / ProbeEveryMs); + // Run state. private long _lastThink, _nextTryAt, _goneSince, _holdSince; - private long _keySentAt, _openSentAt, _answeredAt, _lootStartedAt, _waitUntil, _openedAt; + private long _keySentAt, _openSentAt, _answeredAt, _lootStartedAt, _waitUntil, _openedAt, _lootDoneAt; private int _seqAtSend; - private bool _answerSeen, _sawUnlocked, _keyUsedUp, _lootSeen, _relockExpected; + private bool _answerSeen, _sawUnlocked, _keyUsedUp, _lootSeen, _relockExpected, _regenWait; private int _timeouts, _busy, _openFails, _sendFails, _probes, _refusals, _openElsewhere, _cycles, _keyUsesThisCycle; private string _holdWhy = ""; @@ -356,13 +388,14 @@ internal sealed class ChestKeyLooter _nextTryAt = now + 400; return; } - if (++_probes > MaxProbes) + int limit = ProbeLimit; + if (++_probes > limit) { - Finish($"{ChestName} hasn't re-locked after {MaxProbes} tries ({(MaxProbes * ProbeMs + RegenWaitMs) / 60000} min): its reset timer may be longer, or it doesn't lock"); + Finish($"{ChestName} hasn't re-locked after {limit} tries ({Math.Max(1, (MaxProbes * ProbeMs + RelockWaitMs) / 60000)} min): its reset timer may be longer, or it doesn't lock"); return; } - _env.Log($"[RynthAi] Chest looter: {ChestName} is still unlocked (not reset yet); asking again in {ProbeMs / 1000} s (try {_probes} of {MaxProbes})"); - EnterWaiting(now + ProbeMs); + _env.Log($"[RynthAi] Chest looter: {ChestName} is still unlocked (not reset yet); asking again in {ProbeEveryMs / 1000} s (try {_probes} of {limit})"); + EnterWaiting(now + ProbeEveryMs); return; case ErrKeyDoesntFit: @@ -473,12 +506,18 @@ internal sealed class ChestKeyLooter if (_cycles >= MaxCycles) { Finish($"reached {MaxCycles} cycles (a key with unlimited uses never runs out)"); return; } KeyId = key; _keyUsedUp = false; // that was the old key; the one chosen now has not been used - EnterWaiting(Math.Max(now + 2000, _openedAt + RegenWaitMs)); + _lootDoneAt = now; + EnterWaiting(RegenWaitUntil()); + _regenWait = true; } + /// The re-lock wait's end: RelockWaitSec after the open, and never sooner than 2 s after the loot ended. + private long RegenWaitUntil() => Math.Max(_lootDoneAt + 2000, _openedAt + RelockWaitMs); + private void EnterWaiting(long until) { _waitUntil = until; + _regenWait = false; State = Phase.Waiting; } @@ -486,6 +525,7 @@ internal sealed class ChestKeyLooter { // The key may leave the pack meanwhile (traded, dropped): nothing to wait for then. if (_env.FindKey(KeyId, KeyName, _keyUsedUp ? KeyId : 0) == 0) { Finish($"out of keys - no '{KeyName}' left"); return; } + if (_regenWait) _waitUntil = RegenWaitUntil(); // the setting may have changed meanwhile if (now >= _waitUntil) { State = Phase.Ready; return; } if (_probes == 0 && now >= _openedAt + MinRelockMs && _env.ChestLockedHint(ChestId) == true) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 24cbb79..d497325 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -47,6 +47,11 @@ internal sealed class LegacyAdvancedSettingsUi "Off: nav carries on to the waypoint it was heading for, and a loaded route starts at its first point."; private static readonly string[] TargetSelectionNames = { "Lowest health", "Closest", "Farthest", "Least turning" }; private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; + private const string OpenFellowOnCreateTip = + "A fellowship RynthAi creates (/mt fellow create, or a meta's /fellowship create) is opened\n" + + "as soon as you lead it, so every member can recruit, not just the leader. AC makes a new\n" + + "fellowship closed.\n" + + "Only right after RynthAi creates it: one you made or closed by hand is left alone."; public LegacyAdvancedSettingsUi(LegacyUiSettings settings) { @@ -358,6 +363,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Patrol On Login", ref _settings.PatrolOnLogin); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Automatically starts dungeon patrol when RynthAi loads."); + ImGui.Checkbox("Resume Meta After Reload", ref _settings.ResumeMetaOnReload); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("After a hot reload the meta carries on in the same state, with its variables,\nfired rules and route. A real login still starts in Default."); ImGui.Checkbox("Escape Acid and Lava", ref _settings.EscapeHazards); if (ImGui.IsItemHovered()) ImGui.SetTooltip("When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose."); @@ -702,6 +710,17 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Spacing(); ImGui.Checkbox("Cast Dispel Self", ref _settings.CastDispelSelf); + ImGui.Checkbox("Auto Fellowship Management", ref _settings.AutoFellowMgmt); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("VTank's Auto Fellow Mgmt., saved with the profile. Metas read it (AutoFellowMgmt)."); + if (_settings.AutoFellowMgmt) + { + ImGui.Indent(); + ImGui.Checkbox("Open fellowship on create", ref _settings.OpenFellowOnCreate); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip(OpenFellowOnCreateTip); + ImGui.Unindent(); + } ImGui.Spacing(); ImGui.Text("Ring Spell Override"); @@ -778,7 +797,7 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SetTooltip("Which monster to attack, among those of the highest priority inside Monster Range.\nLeast turning: the one needing the smallest turn to face. Unknown health counts as full."); ImGui.Checkbox("Target Lock", ref _settings.TargetLock); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("On: keeps the target it picked until it dies, leaves Monster Range, or a higher-priority monster shows up.\nOff: switches whenever another monster is clearly better by the Targeting rule."); + ImGui.SetTooltip("On: keeps the target it picked until it dies or leaves Monster Range, even when a higher-priority monster shows up.\nOff: a higher-priority monster in range takes over at once, and it switches whenever another monster is clearly better by the Targeting rule."); ImGui.Checkbox("Fight the monster I select", ref _settings.FightSelectedTarget); if (ImGui.IsItemHovered()) ImGui.SetTooltip(LegacyUiSettings.FightSelectedTargetTip); @@ -1122,7 +1141,10 @@ internal sealed class LegacyAdvancedSettingsUi } ImGui.Checkbox("Jump When Looting", ref _settings.LootJumpEnabled); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Hop (the keyboard jump) just before each pickup,\nso the server skips the bend-down. The hop has a fixed height."); + ImGui.SetTooltip("Hop (the keyboard jump) just before each pickup, so the server skips the\n" + + "bend-down (ACE servers). The hop has a fixed height. Attacks and heals wait\n" + + "for the landing (the server refuses them in the air), so there is no hop\n" + + "with monsters near or health under Heal At."); ImGui.Spacing(); ImGui.Text("Corpse Ownership"); @@ -1153,6 +1175,12 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.EndDisabled(); if (_settings.AutoSortOn && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) ImGui.SetTooltip("Off while RynthSort's auto-sort is on: RynthSort keeps your packs sorted, and the two fight."); + ImGui.Checkbox("Unbox Aetheria When Idle", ref _settings.UnboxAetheriaWhenIdle); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("With the macro on and nothing to fight or loot, uses an Aetheria Mana Stone on each\n" + + "Coalesced Aetheria in your pack, one at a time, to reveal its sigil. The server puts\n" + + "you in peace mode for the clap; combat takes its stance again for the next fight.\n" + + "The stone isn't used up. Also /ra aetheria unbox | status."); ImGui.Checkbox("Combine Salvage Bags", ref _settings.EnableCombineSalvage); if (ImGui.IsItemHovered()) ImGui.SetTooltip("After the salvage queue empties, move same-name bags together so the server merges them."); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index a34584f..a0efc30 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1046,6 +1046,9 @@ internal sealed partial class LegacyDashboardRenderer public string BuildRadarJson(uint engineKnownMapVersion) => _rynthRadarUi.BuildSnapshotJson(engineKnownMapVersion); + /// The share of the dungeon's floor the radar painted as visited (null: not known); /ra dunroute where. + internal double? ExploredShare(uint landblock) => _rynthRadarUi?.ExploredShare(landblock); + // ── Monsters bridge (used by the engine-side Avalonia MonstersPanel) ──── /// /// Builds a JSON payload describing the current MonsterRules + ItemRules @@ -1276,6 +1279,7 @@ internal sealed partial class LegacyDashboardRenderer RearmAfterVitals = s.RearmAfterVitals, StartMacroOnLogin = s.StartMacroOnLogin, PatrolOnLogin = s.PatrolOnLogin, + ResumeMetaOnReload = s.ResumeMetaOnReload, YieldToVTank = s.YieldToVTank, EnableRaycasting = s.EnableRaycasting, UseArcs = s.UseArcs, @@ -1350,6 +1354,7 @@ internal sealed partial class LegacyDashboardRenderer CastDispelSelf = s.CastDispelSelf, UseDispelItems = s.UseDispelItems, AutoFellowMgmt = s.AutoFellowMgmt, + OpenFellowOnCreate = s.OpenFellowOnCreate, MChargesWhenOff = s.MChargesWhenOff, CustomPetRange = s.CustomPetRange, MinRingTargets = s.MinRingTargets, @@ -1411,6 +1416,7 @@ internal sealed partial class LegacyDashboardRenderer DunPatrolSightYd = s.DunPatrolSightYd, OutdoorHuntRange = s.OutdoorHuntRange, OutdoorHuntRadius = s.OutdoorHuntRadius, + OutdoorHuntPick = s.OutdoorHuntPick, T2Speed = s.T2Speed, T2WalkWithinYd = s.T2WalkWithinYd, T2DistanceTo = s.T2DistanceTo, @@ -1446,6 +1452,7 @@ internal sealed partial class LegacyDashboardRenderer LootJumpEnabled = s.LootJumpEnabled, LootChestsMacroOff = s.LootChestsMacroOff, LootChestsMacroOffLeaveOpen = s.LootChestsMacroOffLeaveOpen, + ChestRelockWaitSec = s.ChestRelockWaitSec, LootJumpHeight = s.LootJumpHeight, LootOwnership = s.LootOwnership, LootOwnCorpse = s.LootOwnCorpse, @@ -1455,6 +1462,7 @@ internal sealed partial class LegacyDashboardRenderer ItemInfoOnSelect = s.ItemInfoSettings.OnSelect, EnableAutostack = s.EnableAutostack, ReadUnknownScrolls = s.ReadUnknownScrolls, + UnboxAetheriaWhenIdle = s.UnboxAetheriaWhenIdle, EnableCombineSalvage = s.EnableCombineSalvage, CombineBagsDuringSalvage = s.CombineBagsDuringSalvage, SalvageWithoutPanel = s.SalvageWithoutPanel, @@ -1486,6 +1494,8 @@ internal sealed partial class LegacyDashboardRenderer OffhandDefault = s.OffhandDefault, PreferDualWield = s.PreferDualWield, EnableGroundLoot = s.EnableGroundLoot, + LootByNames = s.LootByNames, + LootByNameRadius = s.LootByNameRadius, // Diagnostics (per PC, RynthLog) DiagDebugToChat = RynthLog.DebugToChat, DiagFileLogAll = RynthLog.FileLogAll, @@ -1546,6 +1556,7 @@ internal sealed partial class LegacyDashboardRenderer if (p.RearmAfterVitals is bool rav) s.RearmAfterVitals = rav; s.StartMacroOnLogin = p.StartMacroOnLogin; s.PatrolOnLogin = p.PatrolOnLogin; + if (p.ResumeMetaOnReload is bool resumeMeta) s.ResumeMetaOnReload = resumeMeta; // absent = unchanged s.YieldToVTank = p.YieldToVTank; s.EnableRaycasting = p.EnableRaycasting; s.UseArcs = p.UseArcs; @@ -1625,6 +1636,7 @@ internal sealed partial class LegacyDashboardRenderer // Absent (an engine without them) = unchanged. if (p.UseDispelItems is bool useDispelItems) s.UseDispelItems = useDispelItems; if (p.AutoFellowMgmt is bool autoFellow) s.AutoFellowMgmt = autoFellow; + if (p.OpenFellowOnCreate is bool openFellow) s.OpenFellowOnCreate = openFellow; if (p.MChargesWhenOff is bool mCharges) s.MChargesWhenOff = mCharges; if (p.CustomPetRange is int petRange) s.CustomPetRange = Math.Clamp(petRange, 1, 50); s.MinRingTargets = p.MinRingTargets; @@ -1689,6 +1701,7 @@ internal sealed partial class LegacyDashboardRenderer // Outdoor hunt: absent (an older engine) = unchanged. if (p.OutdoorHuntRange is float huntRange) s.OutdoorHuntRange = (float)Math.Clamp(huntRange, RynthAiPlugin.OutdoorHuntRangeMin, RynthAiPlugin.OutdoorHuntRangeMax); if (p.OutdoorHuntRadius is float huntRadius) s.OutdoorHuntRadius = (float)Math.Clamp(huntRadius, 0, RynthAiPlugin.OutdoorHuntRadiusMax); + if (p.OutdoorHuntPick is int huntPick) s.OutdoorHuntPick = Math.Clamp(huntPick, 0, 2); s.T2Speed = p.T2Speed; s.T2WalkWithinYd = p.T2WalkWithinYd; s.T2DistanceTo = p.T2DistanceTo; @@ -1721,6 +1734,7 @@ internal sealed partial class LegacyDashboardRenderer s.LootJumpEnabled = p.LootJumpEnabled; s.LootChestsMacroOff = p.LootChestsMacroOff; s.LootChestsMacroOffLeaveOpen = p.LootChestsMacroOffLeaveOpen; + if (p.ChestRelockWaitSec is int relockSec) s.ChestRelockWaitSec = ItemTool.ChestKeyLooter.ClampRelockWaitSec(relockSec); // absent = unchanged s.LootJumpHeight = p.LootJumpHeight; s.LootOwnership = p.LootOwnership; if (p.EscapeHazards is bool escape) s.EscapeHazards = escape; // absent = unchanged @@ -1730,6 +1744,7 @@ internal sealed partial class LegacyDashboardRenderer if (p.ItemInfoOnSelect is bool infoOnSelect) s.ItemInfoSettings.OnSelect = infoOnSelect; // absent = unchanged s.EnableAutostack = p.EnableAutostack; s.ReadUnknownScrolls = p.ReadUnknownScrolls; + if (p.UnboxAetheriaWhenIdle is bool unboxAetheria) s.UnboxAetheriaWhenIdle = unboxAetheria; // absent = unchanged s.EnableCombineSalvage = p.EnableCombineSalvage; s.CombineBagsDuringSalvage = p.CombineBagsDuringSalvage; if (p.SalvageWithoutPanel is bool salvNoPanel) s.SalvageWithoutPanel = salvNoPanel; // absent = unchanged @@ -1762,6 +1777,8 @@ internal sealed partial class LegacyDashboardRenderer if (p.OffhandDefault is string od && OffhandRules.TryParse(od, out var odMode)) s.OffhandDefault = OffhandRules.SettingValue(odMode); if (p.PreferDualWield is bool pdw) s.PreferDualWield = pdw; s.EnableGroundLoot = p.EnableGroundLoot; + if (p.LootByNames is string lootNames) s.LootByNames = LootByNameList.Normalize(lootNames); + if (p.LootByNameRadius is float lootRadius) s.LootByNameRadius = (float)Math.Clamp(lootRadius, LootByNameList.MinRadius, LootByNameList.MaxRadius); // Diagnostics: each setter rewrites diagnostics.json, so only touch what changed. if (p.DiagDebugToChat != RynthLog.DebugToChat) RynthLog.DebugToChat = p.DiagDebugToChat; if (p.DiagFileLogAll != RynthLog.FileLogAll) RynthLog.FileLogAll = p.DiagFileLogAll; @@ -2066,6 +2083,7 @@ internal sealed partial class LegacyDashboardRenderer dst.DunPatrolSightYd = tmp.DunPatrolSightYd; dst.OutdoorHuntRange = tmp.OutdoorHuntRange; dst.OutdoorHuntRadius = tmp.OutdoorHuntRadius; + dst.OutdoorHuntPick = Math.Clamp(tmp.OutdoorHuntPick, 0, 2); dst.T2Speed = tmp.T2Speed; dst.T2DistanceTo = tmp.T2DistanceTo; dst.T2ReissueMs = tmp.T2ReissueMs; @@ -2086,6 +2104,7 @@ internal sealed partial class LegacyDashboardRenderer dst.EnableAutostack = tmp.EnableAutostack; dst.EnableAutocram = tmp.EnableAutocram; dst.ReadUnknownScrolls = tmp.ReadUnknownScrolls; + dst.UnboxAetheriaWhenIdle = tmp.UnboxAetheriaWhenIdle; dst.EnableCombineSalvage = tmp.EnableCombineSalvage; dst.CombineBagsDuringSalvage = tmp.CombineBagsDuringSalvage; dst.SalvageWithoutPanel = tmp.SalvageWithoutPanel; @@ -2109,6 +2128,7 @@ internal sealed partial class LegacyDashboardRenderer dst.LootJumpEnabled = tmp.LootJumpEnabled; dst.LootChestsMacroOff = tmp.LootChestsMacroOff; dst.LootChestsMacroOffLeaveOpen = tmp.LootChestsMacroOffLeaveOpen; + dst.ChestRelockWaitSec = ItemTool.ChestKeyLooter.ClampRelockWaitSec(tmp.ChestRelockWaitSec); dst.LootJumpHeight = tmp.LootJumpHeight; dst.SalvageOpenDelayFirstMs = tmp.SalvageOpenDelayFirstMs; dst.SalvageOpenDelayFastMs = tmp.SalvageOpenDelayFastMs; @@ -2120,6 +2140,7 @@ internal sealed partial class LegacyDashboardRenderer dst.UseDispelItems = tmp.UseDispelItems; dst.CastDispelSelf = tmp.CastDispelSelf; dst.AutoFellowMgmt = tmp.AutoFellowMgmt; + dst.OpenFellowOnCreate = tmp.OpenFellowOnCreate; dst.MChargesWhenOff = tmp.MChargesWhenOff; dst.HealAt = tmp.HealAt; dst.UsePotions = tmp.UsePotions; @@ -2193,6 +2214,8 @@ internal sealed partial class LegacyDashboardRenderer dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses; dst.LootMode = tmp.LootMode; // read through LootModes (an unknown value = Profile) dst.EnableGroundLoot = tmp.EnableGroundLoot; + dst.LootByNames = LootByNameList.Normalize(tmp.LootByNames); + dst.LootByNameRadius = (float)Math.Clamp(tmp.LootByNameRadius > 0 ? tmp.LootByNameRadius : LootByNameList.DefaultRadius, LootByNameList.MinRadius, LootByNameList.MaxRadius); dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle; dst.RearmAfterVitals = tmp.RearmAfterVitals; dst.FastWeaponSwap = tmp.FastWeaponSwap; @@ -2316,6 +2339,7 @@ internal sealed partial class LegacyDashboardRenderer dst.AllowMetaKeystrokes = tmp.AllowMetaKeystrokes; dst.StartMacroOnLogin = tmp.StartMacroOnLogin; dst.PatrolOnLogin = tmp.PatrolOnLogin; + dst.ResumeMetaOnReload = tmp.ResumeMetaOnReload; dst.YieldToVTank = tmp.YieldToVTank; dst.FeatureServerNames = tmp.FeatureServerNames; dst.ForceServerFeatures = tmp.ForceServerFeatures; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs index b596a30..bf1caa7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs @@ -88,7 +88,13 @@ internal sealed class LegacyItemInfoUi if (string.IsNullOrEmpty(_previewText)) ImGui.TextDisabled("Select an item to preview its info line."); else + { + // In the Info text colour when one is set, as RynthCore's chat will draw it. + bool tinted = s.TextColor.Length > 0; + if (tinted) ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(MagItemInfoCatalog.TextColorRgb(s.TextColor), 1f)); SafeImGui.TextWrapped(s.Prefix + _previewText); + if (tinted) ImGui.PopStyleColor(); + } ImGui.EndChild(); if (ImGui.Button("Print to chat##iiPrint")) _printSelected?.Invoke(); @@ -278,36 +284,94 @@ internal sealed class LegacyItemInfoUi RenderLayout(s, "##iiLayout"); - ChatTypeCombo("Chat type / colour##iiChat", ref s.ChatType, allowSameAsHeader: false); + ChatTypeCombo("Chat type##iiChat", ref s.ChatType, allowSameAsHeader: false); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("The chat type picks where the lines go (the chat tab, AC's own chat\n" + + "windows) and their colour, unless Info text colour below sets one."); ImGui.SameLine(); if (ImGui.Button("Test##iiChatTest")) _testChatType?.Invoke(s.ChatType); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Print a sample line with this chat type to see its colour."); + ImGui.SetTooltip("Print a sample line with this chat type to see where it goes and its colour."); // Pet-style only: the roster draws its detail lines in a second colour. ImGui.BeginDisabled(s.Layout != MagItemInfoSettings.LayoutPetLines); - ChatTypeCombo("Detail lines colour##iiChatDetail", ref s.DetailChatType, allowSameAsHeader: true); + ChatTypeCombo("Detail lines chat type##iiChatDetail", ref s.DetailChatType, allowSameAsHeader: true); ImGui.SameLine(); if (ImGui.Button("Test##iiChatDetailTest")) _testChatType?.Invoke(s.DetailChatType == MagItemInfoSettings.SameAsHeader ? s.ChatType : s.DetailChatType); ImGui.EndDisabled(); if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) - ImGui.SetTooltip("Chat type for lines 2-4 of the pet-style layout\n(the name line uses the colour above)."); + ImGui.SetTooltip("Chat type for lines 2-4 of the pet-style layout\n(the name line uses the chat type above)."); ImGui.BeginDisabled(!s.LootChat); - ChatTypeCombo("Loot lines colour##iiChatLoot", ref s.LootChatType, allowSameAsHeader: true); + ChatTypeCombo("Loot lines chat type##iiChatLoot", ref s.LootChatType, allowSameAsHeader: true); ImGui.SameLine(); if (ImGui.Button("Test##iiChatLootTest")) _testChatType?.Invoke(LootChatLine.ChatTypeOf(s)); ImGui.EndDisabled(); if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) ImGui.SetTooltip("Chat type of a described \"Looted\" line\n(\"Same as name line\": the chat type above)."); + RenderTextColor(s); + ImGui.SetNextItemWidth(220); ImGui.InputText("Line prefix##iiPrefix", ref s.Prefix, 32); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Text put in front of every item info line (may be empty)."); } + private const string TextColorTip = + "The colour of every item info line in RynthCore's chat: the name line, the\n" + + "detail lines, a described \"Looted\" line and your own ratings. The lines keep\n" + + "their chat type, so they stay in the same chat tab.\n" + + "\"Chat type's own colour\": as before, the chat type decides the colour.\n" + + "AC's own chat window can only show the chat type's colour.\n" + + "Also: /ra iteminfo color allegiance|fellowship|...|#RRGGBB|default."; + + /// + /// "Info text colour": the chat type's own colour (""), a named chat colour, or any colour from + /// the picker beside it. A new choice shows on the next line printed (Test prints one). + /// + private void RenderTextColor(MagItemInfoSettings s) + { + string current = s.TextColor.Length == 0 ? MagItemInfoCatalog.TextColors[0].Label : "Custom " + s.TextColor; + foreach (var (_, label, color) in MagItemInfoCatalog.TextColors) + if (color.Length > 0 && string.Equals(color, s.TextColor, StringComparison.OrdinalIgnoreCase)) { current = label; break; } + + ImGui.SetNextItemWidth(220); + if (ImGui.BeginCombo("Info text colour##iiTextColor", current)) + { + float swatch = ImGui.GetTextLineHeight(); + foreach (var (word, label, color) in MagItemInfoCatalog.TextColors) + { + if (color.Length > 0) + { + ImGui.ColorButton("##iiTcSw" + word, new Vector4(MagItemInfoCatalog.TextColorRgb(color), 1f), + ImGuiColorEditFlags.NoTooltip | ImGuiColorEditFlags.NoPicker, new Vector2(swatch, swatch)); + ImGui.SameLine(); + } + else + { + ImGui.Dummy(new Vector2(swatch, swatch)); + ImGui.SameLine(); + } + if (ImGui.Selectable(label + "##iiTc" + word, string.Equals(color, s.TextColor, StringComparison.OrdinalIgnoreCase))) + s.TextColor = color; + } + ImGui.EndCombo(); + } + if (ImGui.IsItemHovered()) ImGui.SetTooltip(TextColorTip); + + ImGui.SameLine(); + Vector3 rgb = MagItemInfoCatalog.TextColorRgb(s.TextColor); + if (ImGui.ColorEdit3("##iiTextColorPick", ref rgb, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + s.TextColor = MagItemInfoCatalog.TextColorFromRgb(rgb); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Pick any colour for the item info lines."); + + ImGui.SameLine(); + if (ImGui.Button("Test##iiTextColorTest")) _testChatType?.Invoke(s.ChatType); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Print a sample line in this colour (and the chat type above)."); + } + /// Chat type picker; adds the "same as name line" entry (-1). private static void ChatTypeCombo(string label, ref int chatType, bool allowSameAsHeader) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 39d3ab4..9cb036f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -81,6 +81,9 @@ public sealed class LegacyUiSettings // Hunt Range 192 by default since 2026-10-25: the radar's default range, so the hunt covers the radar. public float OutdoorHuntRange = (float)OutdoorHunt.DefaultRangeYd; // yd from the character: how far the next monster may be public float OutdoorHuntRadius = 0f; // yd from where the hunt started that its picks stay within (0 = anywhere) + // What the next monster is chosen by (2026-11-08, OutdoorHunt.PickMode): 0 the nearest (the hunt as + // it was), 1 the biggest pack, 2 the pack worth the most experience (learned XP per kill). + public int OutdoorHuntPick = 0; // On: macro start, loading a Circular or Linear route, and nav taking over again after a // pause that moved the character (combat, looting, buffing, doors) all head for the closest // waypoint on the route. Off: a pause carries on to the waypoint it was heading for, a macro @@ -121,6 +124,10 @@ public sealed class LegacyUiSettings // know and can learn (school trained or specialized, ACE's skill rule), then read them // at a safe moment; scrolls already in the pack too. Needs looting on for corpses. public bool ReadUnknownScrolls = true; + // Unbox Aetheria When Idle (a player's request, 2026-11-01; default off): with the macro on and + // nothing to do, an Aetheria Mana Stone is used on each Coalesced Aetheria in the pack, one at a + // time, to reveal its sigil (Loot/AetheriaUnboxer.cs). The stone isn't used up on ACE. + public bool UnboxAetheriaWhenIdle = false; public bool EnableCombineSalvage = true; public bool CombineBagsDuringSalvage = true; // Salvage (and combine bags) by sending the 0x027D salvage request straight to the server, no @@ -162,6 +169,13 @@ public sealed class LegacyUiSettings /// can't be opened again without its key or quest item). /// public bool LootChestsMacroOffLeaveOpen = false; + /// + /// Item Tool > Chest re-lock wait (s) (2026-11-05): the chest looter's next key goes on the chest + /// this long after it was opened (sooner when the client reads it locked again). 125 s covers ACE's + /// default chest reset (120 s); a chest with a shorter timer can use less. 5..600 + /// (ItemTool.ChestKeyLooter.ClampRelockWaitSec). + /// + public int ChestRelockWaitSec = ItemTool.ChestKeyLooter.DefaultRelockWaitSec; public int LootJumpHeight = 10; // kept for old profiles and metas; jump-loot uses the keyboard tap jump (fixed height) public int SalvageOpenDelayFirstMs = 400; @@ -174,6 +188,13 @@ public sealed class LegacyUiSettings public bool UseDispelItems; public bool CastDispelSelf; public bool AutoFellowMgmt; + /// + /// Auto Fellowship Management > Open fellowship on create (2026-11-04, on by default, as VTank's + /// auto fellow management does): a fellowship RynthAi creates (/mt fellow create, a meta's + /// /fellowship create) is opened once it exists. Acts only with AutoFellowMgmt on; a fellowship + /// made or closed by hand is never touched. + /// + public bool OpenFellowOnCreate = true; public bool MChargesWhenOff; public int HealAt = 60; @@ -239,10 +260,11 @@ public sealed class LegacyUiSettings // Range (CombatManager.TargetScheme): 0 lowest health (unknown counts as full), 1 closest, // 2 farthest, 3 least turning. Ties go to the closest. public int TargetSelection; - // Target Lock: keep the picked target until it dies or goes, leaves Monster Range, is - // blacklisted or skipped by a watchdog, or a higher-priority monster is in range. Off: switch - // when another is clearly better by Targeting. On by default; a profile saved before this - // setting loads it as on. + // Target Lock: keep the picked target until it dies or goes, leaves Monster Range, or is + // blacklisted or skipped by a watchdog; a higher-priority monster in range doesn't take it + // (2026-11-07). Off: a higher priority in range takes over at once, and it switches when + // another is clearly better by Targeting. On by default; a profile saved before this setting + // loads it as on. public bool TargetLock = true; // Fight the monster I select (2026-11-01): a monster the PLAYER selects in game (a click, the // radar, another plugin's Selection window) becomes the fight target ahead of the Targeting @@ -351,6 +373,10 @@ public sealed class LegacyUiSettings public int LootMode; /// Also pick up loose ground items that match the loot profile, within the corpse max range. public bool EnableGroundLoot; + /// Loot by name: names separated by |. An object in the world with one of these names inside + /// is used (a container opens, an item is picked up) while botting. + public string LootByNames = string.Empty; + public float LootByNameRadius = 30f; public bool PeaceModeWhenIdle = true; /// After a heal, restam or remana spell with no monster to fight, put the last fight's /// weapons (main hand and off hand) back on instead of waiting for the next target. @@ -459,6 +485,13 @@ public sealed class LegacyUiSettings public bool StartMacroOnLogin; public bool PatrolOnLogin; /// + /// Resume Meta After Reload (2026-11-07, Tom: "remembers which meta state you're in and restarts in + /// that state so Drakkon doesn't recall back every time"). A hot reload carries the meta's whole + /// runtime over (Meta/MetaResume.cs): state, variables, fired rules, call stack, watchdog, route. + /// A real login still starts in Default. + /// + public bool ResumeMetaOnReload = true; + /// /// Decal bridge only: when VTank's macro starts, RynthAi's macro stops, and it won't start /// while VTank runs (one bot per client). On by default; a profile saved before this /// setting existed loads it as on. Without Decal it does nothing. @@ -1035,8 +1068,27 @@ public sealed class ItemRule /// Display only (filled by WeaponList.ForDisplay for the Items panel, never read back): /// Melee, Missile, "War Magic", "Void Magic", Shield, Ammo, or "" when the item isn't known. public string Kind { get; set; } = ""; + /// + /// False = "No buff", read for a listed SHIELD only: none of the armor spells are aimed at it + /// (BuffManager.Shield.cs), and its timers never make buffing due. On a weapon or wand it does + /// nothing. True for a new entry and for every profile saved before it was read (the field was + /// only ever written true). Set from the engine's Items face through . + /// public bool KeepBuffed { get; set; } = true; + /// + /// Items bridge wire field only (ItemsBridgePayload.Weapons), never saved in a profile: true = + /// "No buff" ( off). WeaponList.ForDisplay fills it for every entry; + /// WeaponList.MergeEdited applies it back for a shield entry only, and an absent field (an + /// engine that predates it) leaves KeepBuffed as saved. + /// + [JsonPropertyName("noBuff")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? NoBuff { get; set; } + + /// True when buffing leaves this item alone ( off; shields only). + public bool ExcludedFromBuffing() => !KeepBuffed; + /// True when this row is a shield (off hand), not a main-hand weapon. public bool IsShield() => string.Equals(Action, ShieldAction, StringComparison.OrdinalIgnoreCase); } @@ -1085,6 +1137,8 @@ public sealed class ConsumableRule /// Bridge payload for the engine-side Avalonia ItemsPanel. public sealed class ItemsBridgePayload { + /// Copies for the face (WeaponList.ForDisplay). Each carries "noBuff" (ItemRule.NoBuff, + /// true = not buffed); on write-back it is applied for shield entries only. public List Weapons { get; set; } = new(); public List Consumables { get; set; } = new(); public bool EnableManaTapping { get; set; } = true; // absent from an old profile = the new default @@ -1184,6 +1238,8 @@ public sealed class SettingsBridgePayload public bool? RearmAfterVitals { get; set; } public bool StartMacroOnLogin { get; set; } public bool PatrolOnLogin { get; set; } + // Resume Meta After Reload. Nullable: an engine without the row doesn't send it (unchanged). + public bool? ResumeMetaOnReload { get; set; } // Dungeon patrol. Nullable: an engine that predates them doesn't send them, and its save // must leave them alone. public int? DunPatrolCoverage { get; set; } @@ -1195,6 +1251,10 @@ public sealed class SettingsBridgePayload // Outdoor hunt. Nullable: an engine that predates them doesn't send them. public float? OutdoorHuntRange { get; set; } public float? OutdoorHuntRadius { get; set; } + public int? OutdoorHuntPick { get; set; } // 0 Nearest, 1 Biggest pack, 2 Most XP (2026-11-08) + // Loot by name. Nullable: an engine that predates them doesn't send them. + public string? LootByNames { get; set; } + public float? LootByNameRadius { get; set; } // Absent from an older engine's payload: must not read as off. public bool YieldToVTank { get; set; } = true; public bool EnableRaycasting { get; set; } = true; // on unless the player turns it off (2026-11-05) @@ -1284,6 +1344,7 @@ public sealed class SettingsBridgePayload // without them sends none, and the saved values stay. public bool? UseDispelItems { get; set; } public bool? AutoFellowMgmt { get; set; } + public bool? OpenFellowOnCreate { get; set; } // 2026-11-04: null from an older engine leaves it alone public bool? MChargesWhenOff { get; set; } public int? CustomPetRange { get; set; } public int MinRingTargets { get; set; } @@ -1392,6 +1453,7 @@ public sealed class SettingsBridgePayload public bool LootJumpEnabled { get; set; } public bool LootChestsMacroOff { get; set; } = true; // an engine that doesn't know it leaves it on public bool LootChestsMacroOffLeaveOpen { get; set; } // off: an engine that doesn't know it closes, as before + public int? ChestRelockWaitSec { get; set; } // Item Tool's re-lock wait; absent (the engine has no row for it) = unchanged public int LootJumpHeight { get; set; } public int LootOwnership { get; set; } // Nullable, as CastBuffsOverItemBuffs: an engine that predates them doesn't send them, @@ -1404,6 +1466,7 @@ public sealed class SettingsBridgePayload public bool? ItemInfoOnSelect { get; set; } public bool EnableAutostack { get; set; } public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default + public bool? UnboxAetheriaWhenIdle { get; set; } // absent from an older engine: unchanged public bool EnableCombineSalvage { get; set; } public bool CombineBagsDuringSalvage { get; set; } public bool? SalvageWithoutPanel { get; set; } // absent from an older engine: unchanged diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs index 98e5324..023ef81 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs @@ -75,6 +75,26 @@ internal sealed class RynthRadarUi internal void SetMapData(DungeonMapUi mapData) => _mapData = mapData; public void SetWorldObjectCache(WorldObjectCache cache) => _objectCache = cache; + /// + /// The share (0..1) of the dungeon's flat floor the radar has painted as visited this visit, for + /// /ra dunroute where; null when the radar hasn't drawn this landblock (its snapshot drives the + /// painting, so a closed radar knows nothing). Pump thread, as the snapshot. + /// + internal double? ExploredShare(uint landblock) + { + var map = _mapData; + if (map?._floorCells is null || map._cachedLandblock != landblock || _visitedLandblock != landblock) return null; + int total = 0, seen = 0; + foreach (var (_, cells) in map._floorCells) + foreach (var ((gx, gy), ctype) in cells) + { + if (ctype != DungeonMapUi.CellType.Flat) continue; + total++; + if (_visitedCells.Contains((gx, gy))) seen++; + } + return total == 0 ? null : (double)seen / total; + } + // ── Visited strip cache ───────────────────────────────────────────── private void RebuildRadarVisitedStrips() diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/AetheriaUnboxer.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/AetheriaUnboxer.cs new file mode 100644 index 0000000..33990ac --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/AetheriaUnboxer.cs @@ -0,0 +1,477 @@ +// ============================================================================ +// RynthSuite - Plugins/RynthCore.Plugin.RynthAi/Loot/AetheriaUnboxer.cs +// Unbox Aetheria When Idle (a player's request, 2026-11-01: "auto aetheria +// unbox when idle option"), default off; also /ra aetheria unbox by hand. +// +// ACE's rule (ACE.Server Entity/Aetheria.cs UseObjectOnTarget, reached from +// CraftTool.HandleActionUseOnTarget): an Aetheria Mana Stone (wcid 42645) used +// on a Coalesced Aetheria (42635 blue, 42636 red, 42637 yellow) whose name is +// still "Coalesced Aetheria", both in the player's packs. Busy: UseDone +// YoureTooBusy. Otherwise the server switches the player to peace mode, claps, +// then ActivateSigil: chat "A sigil rises to the surface as you bathe the +// aetheria in mana.", the item's name becomes "Aetheria", UseDone (no error), +// and the server stays busy for the return-to-ready animation. The mana stone +// is NOT consumed (ActivateSigil never touches the source), so one stone +// unboxes every coalesced piece. Already revealed: "... because the sigil is +// already visible." and UseDone YouDoNotPassCraftingRequirements. +// +// One unbox at a time, each answered (the sigil line, the new name, or a +// refusal) before the next goes out. A refusal waits 10 s, then 30 s, 60 s, +// 120 s; a piece refused three times (not counting "too busy") is left alone +// for the session. It only starts at a safe moment (RynthAiPlugin.Aetheria.cs: +// the scroll reader's gate, no fight), and the bot holds still while the clap +// plays. Combat sets its own stance when the next fight starts. +// ============================================================================ + +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.Loot; + +internal sealed class AetheriaUnboxer +{ + internal const uint WcidBlue = 42635, WcidRed = 42636, WcidYellow = 42637, WcidManaStone = 42645; + internal const string CoalescedName = "Coalesced Aetheria"; + internal const string StoneName = "Aetheria Mana Stone"; + internal const string SigilLine = "A sigil rises to the surface as you bathe the aetheria in mana."; + /// ACE's YoureTooBusy, as a UseDone error. + internal const uint TooBusyErr = 0x1D; + + /// Peace (up to ~1 s) + clap + the reveal is ~2-3 s on ACE; no answer in this long is a failed try. + internal const long UnboxTimeoutMs = 10_000; + /// A UseDone with no error and the piece still coalesced: its name may lag the UseDone this long. + internal const long UseDoneGraceMs = 2_000; + /// + /// Pause between two unboxes, from the last one's end. ACE sends the UseDone before the + /// return-to-ready animation and stays busy until it ends: sooner is "too busy". + /// + internal const long GapMs = 1_500; + /// Waits after a refusal (or no answer): one step longer for each in a row. + internal static readonly long[] BackoffMs = { 10_000, 30_000, 60_000, 120_000 }; + /// Refusals (not "too busy") before a piece is left alone for the session. + internal const int MaxRefusalsPerItem = 3; + /// How often the pack is looked through while the last look found nothing to unbox. + internal const long SweepMs = 5_000; + /// How often while there is work (the next piece after an unbox). + internal const long StartCheckMs = 1_000; + + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private readonly WorldObjectCache? _cache; + + /// Clock (ms); tests replace it. + public Func NowMs = () => Environment.TickCount64; + /// The player's id (0 before login). + public Func PlayerId = () => 0; + /// A chat line for the player. + public Action? Chat; + + // The unbox in flight. + private int _targetId; + private int _stoneId; + private string _targetColor = ""; + private long _sentAt; + private bool _sigilSeen; + private bool _busyChat; + private bool _alreadyVisible; + private bool _targetDeleted; + private bool _useDoneWatch; + private int _useDoneSeqAtSend; + private long _useDoneAt; + private uint _useDoneErr; + + private long _lastEndAt = long.MinValue / 2; + private long _notBefore; + private int _backoffStep; + private long _lastWalkAt = long.MinValue / 2; + private bool _workSeen; + private bool _noStoneSaid; + private bool _manual; + private int _manualRevealed; + private readonly Dictionary _refusals = new(); + private readonly HashSet _givenUp = new(); + + public AetheriaUnboxer(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache? cache) + { + _host = host; + _settings = settings; + _cache = cache; + } + + public bool IsUnboxing => _targetId != 0; + /// A run asked for by hand (/ra aetheria unbox) is under way. + public bool ManualRun => _manual; + /// Pieces revealed this session. + public int Revealed { get; private set; } + public int GivenUpCount => _givenUp.Count; + public long BackoffLeftMs => Math.Max(0, _notBefore - NowMs()); + + // ── Facts ───────────────────────────────────────────────────────────────── + + private uint Wcid(int id) + { + try { return _host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)id), out uint w) ? w : 0; } + catch { return 0; } + } + + /// The client's name for it now (a reveal renames it), else the cache's. + private string LiveName(int id, string? cached = null) + { + try + { + if (_host.HasGetObjectName && _host.TryGetObjectName(unchecked((uint)id), out string n) && !string.IsNullOrWhiteSpace(n)) + return n; + } + catch { } + return cached ?? _cache?[id]?.Name ?? ""; + } + + private static bool IsAetheriaWcid(uint w) => w == WcidBlue || w == WcidRed || w == WcidYellow; + + /// + /// A piece the server will unbox: an aetheria wcid (or none readable) still named "Coalesced + /// Aetheria". A revealed one is named "Aetheria" and is left alone. + /// + internal bool IsCoalesced(WorldObject wo) + { + uint w = Wcid(wo.Id); + if (w != 0 && !IsAetheriaWcid(w)) return false; + return LiveName(wo.Id, wo.Name).Equals(CoalescedName, StringComparison.OrdinalIgnoreCase); + } + + /// An Aetheria Mana Stone: its wcid, or its name when no wcid is readable. + internal bool IsStone(WorldObject wo) + { + uint w = Wcid(wo.Id); + if (w != 0) return w == WcidManaStone; + return LiveName(wo.Id, wo.Name).Equals(StoneName, StringComparison.OrdinalIgnoreCase); + } + + private static string ColorOf(uint w) => w switch + { + WcidBlue => "blue", + WcidRed => "red", + WcidYellow => "yellow", + _ => "", + }; + + /// The pack, freshly walked: GetInventory can still hold items that are gone (2026-11-03). + private IReadOnlyList Inventory() + { + IReadOnlyList all; + try { all = _cache?.GetDirectInventory(forceRefresh: true) ?? Array.Empty(); } + catch { return Array.Empty(); } + + // Without the engine's container walk the cache falls back to every non-landscape + // object it knows, corpse contents included (ScrollLearner.Inventory). The server wants + // both items in the player's own packs: leave out what is known to sit elsewhere. + int player = unchecked((int)PlayerId()); + if (player == 0 || _host.HasGetContainerContents) return all; + var mine = new List(all.Count); + foreach (WorldObject wo in all) + { + int c = wo.Container; + if (c == 0 || c == player || _cache?[c]?.Container == player) mine.Add(wo); + } + return mine; + } + + /// What the pack holds: the coalesced pieces (left-alone ones too) and the first mana stone. + internal (List Coalesced, WorldObject? Stone, int Stones) Look() + { + var coalesced = new List(); + WorldObject? stone = null; + int stones = 0; + foreach (WorldObject wo in Inventory()) + { + if (IsStone(wo)) + { + stones++; + stone ??= wo; + } + else if (IsCoalesced(wo)) coalesced.Add(wo); + } + return (coalesced, stone, stones); + } + + // ── Ticking ─────────────────────────────────────────────────────────────── + + /// + /// One tick. : no fight, no corpse, not buffing, salvaging or in a portal + /// (RynthAiPlugin.IsSafeToUnboxAetheria). Returns true while an unbox is in flight with the macro + /// on and it is still safe: the caller then holds the bot still. + /// + public bool Tick(bool safe, int busyCount) + { + long now = NowMs(); + PollUseDone(now); + if (IsUnboxing) + { + if (Resolve(now)) return false; + return safe && _settings.IsMacroRunning; + } + + if (!_manual && !(_settings.UnboxAetheriaWhenIdle && _settings.IsMacroRunning)) return false; + if (!_host.HasUseObjectOn) + { + FinishManual("this engine can't use an item on another"); + return false; + } + if (!safe || busyCount > 0) return false; + if (now < _notBefore || now - _lastEndAt < GapMs) return false; + if (now - _lastWalkAt < (_workSeen ? StartCheckMs : SweepMs)) return false; + _lastWalkAt = now; + + var (coalesced, stone, _) = Look(); + WorldObject? pick = null; + foreach (WorldObject wo in coalesced) + if (!_givenUp.Contains(wo.Id)) { pick = wo; break; } + _workSeen = pick != null; + if (pick == null) + { + _noStoneSaid = false; + FinishManual(coalesced.Count > 0 ? $"{coalesced.Count} left alone after refusals" : ""); + return false; + } + if (stone == null) + { + // Said once, until a stone turns up again or nothing is left to unbox. + if (!_noStoneSaid) + { + LogLine($"[Aetheria] no mana stone in the pack, {coalesced.Count} coalesced aetheria left"); + if (!_manual) + Say($"[RynthAi] Aetheria: {coalesced.Count} coalesced aetheria in your pack, but no Aetheria Mana Stone to unbox them with."); + } + _noStoneSaid = true; + FinishManual($"no Aetheria Mana Stone left for the other {coalesced.Count}"); + return false; + } + _noStoneSaid = false; + return Send(pick, stone, now) && _settings.IsMacroRunning; + } + + private bool Send(WorldObject target, WorldObject stone, long now) + { + int seqBefore = 0; + bool haveSeq = false; + try { if (_host.HasUseDoneSeq) { seqBefore = _host.GetUseDoneSeq(); haveSeq = true; } } catch { } + bool sent = false; + try + { + sent = _host.UseOnFor(unchecked((uint)stone.Id), unchecked((uint)target.Id), "Aetheria", + _manual ? "unbox a coalesced aetheria (/ra aetheria unbox)" : "Unbox Aetheria When Idle", + _manual ? UseKind.Asked : UseKind.Auto); + } + catch { } + if (!sent) + { + // Nothing went out (the engine said no): the same wait as a refusal, so it isn't sent every second. + Refused(target.Id, "the use didn't go out", busy: true, now); + return false; + } + _targetId = target.Id; + _stoneId = stone.Id; + _targetColor = ColorOf(Wcid(target.Id)); + _sentAt = now; + _sigilSeen = _busyChat = _alreadyVisible = _targetDeleted = false; + _useDoneWatch = haveSeq; + _useDoneSeqAtSend = seqBefore; + _useDoneAt = 0; + _useDoneErr = 0; + LogLine($"[Aetheria] unboxing 0x{(uint)target.Id:X8} '{CoalescedName}'{ColorText} with 0x{(uint)stone.Id:X8} '{LiveName(stone.Id, stone.Name)}'"); + return true; + } + + private string ColorText => _targetColor.Length > 0 ? $" ({_targetColor})" : ""; + + /// Notes the first UseDone after the send, and its error. + private void PollUseDone(long now) + { + if (!_useDoneWatch) return; + try + { + int seq = _host.GetUseDoneSeq(); + if (unchecked(seq - _useDoneSeqAtSend) <= 0) return; + _useDoneWatch = false; + _useDoneAt = now; + _useDoneErr = _host.TryGetLastUseDone(out int lastSeq, out uint err) && lastSeq == seq ? err : 0; + } + catch { _useDoneWatch = false; } + } + + /// True when the unbox in flight is over (revealed, refused, gone, or timed out). + private bool Resolve(long now) + { + int id = _targetId; + string name = LiveName(id); + bool renamed = name.Length > 0 && !name.Equals(CoalescedName, StringComparison.OrdinalIgnoreCase); + + if (_sigilSeen || (renamed && !_alreadyVisible)) + { + Revealed++; + if (_manual) _manualRevealed++; + _backoffStep = 0; + _refusals.Remove(id); + string how = _sigilSeen ? "the sigil rose" : $"now named '{name}'"; + LogLine($"[Aetheria] revealed 0x{(uint)id:X8}{ColorText} ({how}; {Revealed} this session)"); + EndUnbox(now); + return true; + } + if (_alreadyVisible) + { + LogLine($"[Aetheria] 0x{(uint)id:X8} was already revealed - left alone"); + _givenUp.Add(id); + EndUnbox(now); + return true; + } + if (_targetDeleted) + { + LogLine($"[Aetheria] 0x{(uint)id:X8} left the pack during its unbox"); + EndUnbox(now); + return true; + } + + long age = now - _sentAt; + string? why = null; + bool busy = false; + if (_useDoneAt != 0 && _useDoneErr == TooBusyErr) { why = "too busy"; busy = true; } + else if (_useDoneAt != 0 && _useDoneErr != 0) why = $"refused, error 0x{_useDoneErr:X}"; + else if (_busyChat) { why = "too busy"; busy = true; } + else if (_useDoneAt != 0 && now - _useDoneAt >= UseDoneGraceMs) why = "answered, but no sigil rose"; + else if (age >= UnboxTimeoutMs) why = $"no answer in {UnboxTimeoutMs / 1000} s"; + if (why == null) return false; + + EndUnbox(now); + Refused(id, why, busy, now); + return true; + } + + private void Refused(int id, string why, bool busy, long now) + { + long wait = BackoffMs[Math.Min(_backoffStep, BackoffMs.Length - 1)]; + _backoffStep++; + _notBefore = now + wait; + if (!busy) + { + _refusals.TryGetValue(id, out int n); + _refusals[id] = ++n; + if (n >= MaxRefusalsPerItem) + { + _givenUp.Add(id); + LogLine($"[Aetheria] unbox of 0x{(uint)id:X8} failed ({why}) {n} times - left alone this session"); + return; + } + } + LogLine($"[Aetheria] unbox of 0x{(uint)id:X8} not done ({why}) - trying again in {wait / 1000} s"); + } + + private void EndUnbox(long now) + { + _targetId = 0; + _stoneId = 0; + _targetColor = ""; + _sigilSeen = _busyChat = _alreadyVisible = _targetDeleted = false; + _useDoneWatch = false; + _useDoneAt = 0; + _useDoneErr = 0; + _lastEndAt = now; + _lastWalkAt = long.MinValue / 2; // the next piece is looked for at once (past the gap) + } + + /// A run asked for by hand ends: one line saying how it went. + private void FinishManual(string why) + { + if (!_manual) return; + _manual = false; + string line = $"[RynthAi] Aetheria: revealed {_manualRevealed}."; + if (why.Length > 0) line = $"[RynthAi] Aetheria: revealed {_manualRevealed} ({why})."; + _manualRevealed = 0; + Say(line); + } + + // ── By hand ─────────────────────────────────────────────────────────────── + + /// + /// /ra aetheria unbox: unbox every coalesced piece in the pack, one at a time, whatever the + /// setting (with the macro on, still only at a safe moment). False with the reason when there + /// is nothing to do. A wait after a refusal is skipped; pieces left alone are tried again. + /// + public bool RequestManual(out string reply) + { + if (!_host.HasUseObjectOn) { reply = "[RynthAi] Aetheria: this engine can't use an item on another (UseObjectOn)."; return false; } + var (coalesced, stone, _) = Look(); + if (coalesced.Count == 0) { reply = "[RynthAi] Aetheria: no Coalesced Aetheria in your pack."; return false; } + if (stone == null) { reply = $"[RynthAi] Aetheria: {coalesced.Count} coalesced aetheria in your pack, but no Aetheria Mana Stone to unbox them with."; return false; } + _givenUp.Clear(); + _refusals.Clear(); + _notBefore = 0; + _backoffStep = 0; + _lastWalkAt = long.MinValue / 2; + _workSeen = true; + if (!_manual) _manualRevealed = 0; + _manual = true; + reply = $"[RynthAi] Aetheria: unboxing {coalesced.Count} coalesced aetheria, one at a time."; + return true; + } + + /// /ra aetheria status: the setting, the pack, and what it is doing. + public string Describe() + { + var (coalesced, _, stones) = Look(); + string state = IsUnboxing ? $"; unboxing 0x{(uint)_targetId:X8} now" + : BackoffLeftMs > 0 ? $"; waiting {(BackoffLeftMs + 999) / 1000} s after a refusal" + : ""; + string left = _givenUp.Count > 0 ? $"; {_givenUp.Count} left alone after refusals" : ""; + string manual = _manual ? "; an unbox by hand is under way" : ""; + return $"[RynthAi] Aetheria: Unbox When Idle {(_settings.UnboxAetheriaWhenIdle ? "on" : "off")}; in your pack {coalesced.Count} coalesced, " + + $"{stones} Aetheria Mana Stone{(stones == 1 ? "" : "s")}; revealed {Revealed} this session{state}{left}{manual}."; + } + + // ── Events ──────────────────────────────────────────────────────────────── + + /// ACE's answers to an unbox (Aetheria.ActivateSigil, VerifyUseRequirements, the busy refusal). + public void OnChat(string? text) + { + if (!IsUnboxing || string.IsNullOrEmpty(text)) return; + string t = text.Trim(); + if (t == SigilLine) _sigilSeen = true; + else if (t.EndsWith("because the sigil is already visible.", StringComparison.Ordinal)) _alreadyVisible = true; + else if (t.StartsWith("You're too busy", StringComparison.Ordinal)) _busyChat = true; + } + + public void OnObjectDeleted(uint objectId) + { + int id = unchecked((int)objectId); + if (IsUnboxing && (id == _targetId || id == _stoneId)) _targetDeleted = true; + _refusals.Remove(id); + _givenUp.Remove(id); + } + + /// Logout: the session memory goes with the character. + public void Reset() + { + _refusals.Clear(); + _givenUp.Clear(); + _notBefore = 0; + _backoffStep = 0; + _noStoneSaid = false; + _manual = false; + _manualRevealed = 0; + _workSeen = false; + Revealed = 0; + EndUnbox(NowMs()); + } + + private void Say(string line) + { + try { Chat?.Invoke(line); } catch { } + } + + private void LogLine(string line) + { + try { _host.Log(line); } catch { } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs index b080161..c0dd293 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs @@ -35,13 +35,17 @@ 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; public int TargetCount; public int SourceCount; } + private sealed class Pending { public DateTime EnqueuedAt; public int FromContainer; public int TargetCount; public int SourceCount; public string Group = ""; public string Name = ""; public bool Guessed; } 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 private readonly Dictionary _stackPending = new(); // "tgt_src" -> in-flight merge private readonly Dictionary _stackBackoff = new(); // "tgt_src" -> confirmed-fail backoff private DateTime _lastBackoffPrune = DateTime.MinValue; + // Groups whose stack size is only a name guess and whose merges the server never takes + // (2026-11-08: 17 Pyreal Motes, which don't stack, were "Pyreal" 25000 stacks; 136 pairs each + // failed and backed off on their own, two merges a second for hours). + private readonly StackGroupRefusals _guessRefusals = new(); // Grace window for confirm-via-snapshot. MUST be strictly larger than the // AcMainThreadQueue max gesture-defer (DrainDeferTickCap=250 ticks ≈ 4-8s at the @@ -269,7 +273,7 @@ public sealed class InventoryManager var groupList = playerItems .Where(x => GetMaxStackSize(x) > 1) .GroupBy(StackGroupKey) - .Where(g => g.Count() > 1) + .Where(g => g.Count() > 1 && !_guessRefusals.GivenUp(g.Key)) .ToList(); foreach (var g in groupList) @@ -302,7 +306,8 @@ public sealed class InventoryManager (WorldObject Item, int Count)? chosenTarget = null; (WorldObject Item, int Count)? chosenSource = null; string? pairKey = null; - for (int ti = 0; ti < parts.Count && chosenTarget == null; ti++) + bool guessed = g.First().Values(LongValueKey.MaxStackSize, 0) <= 1; + for (int ti = 0; ti < parts.Count && chosenTarget == null && !_guessRefusals.GivenUp(g.Key); ti++) { for (int si = parts.Count - 1; si > ti; si--) { @@ -320,12 +325,18 @@ public sealed class InventoryManager { _stackPending.Remove(key); _stackBackoff.Remove(key); + _guessRefusals.Merged(sp.Group); continue; // this pair resolved — try another } if ((RynthClock.Now - sp.EnqueuedAt).TotalMilliseconds < MoveConfirmGraceMs) continue; // still in flight — skip this pair this tick _stackPending.Remove(key); RegisterFailure(_stackBackoff, key); + if (sp.Guessed && _guessRefusals.Refused(sp.Group)) + { + _host.Log($"[RynthAi] AutoStack: '{sp.Name}' never merged in {StackGroupRefusals.GiveUpAfter} tries and its stack size was only guessed from its name: it doesn't stack, leaving those alone until the plugin reloads."); + break; + } _host.Log($"[RynthAi] AutoStack: CONFIRMED merge failure {key} (source survived after {MoveConfirmGraceMs:0}ms) — backing off"); continue; } @@ -351,6 +362,7 @@ public sealed class InventoryManager if (!ok) { RegisterFailure(_stackBackoff, pairKey); + if (guessed) _guessRefusals.Refused(g.Key); _host.Log($"[RynthAi] AutoStack: MergeStackInternal REJECTED src=0x{source.Item.Id:X8} tgt=0x{target.Item.Id:X8} — backing off"); return true; // one action per tick } @@ -358,7 +370,11 @@ 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 = RynthClock.Now, FromContainer = playerId, TargetCount = target.Count, SourceCount = source.Count }; + _stackPending[pairKey] = new Pending + { + EnqueuedAt = RynthClock.Now, FromContainer = playerId, TargetCount = target.Count, SourceCount = source.Count, + Group = g.Key, Name = source.Item.Name ?? "", Guessed = guessed, + }; return true; // one action per tick } @@ -431,26 +447,68 @@ public sealed class InventoryManager { int max = item.Values(LongValueKey.MaxStackSize, 0); if (max > 1) return max; + return NameFallbackMaxStack(item.Name); + } - // Name-based fallbacks for items whose quality property didn't resolve yet. - string n = item.Name; - if (string.IsNullOrEmpty(n)) return 1; - - if (n.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) return 25000; - if (n.Contains("Trade Note", StringComparison.OrdinalIgnoreCase)) return 100; - if (n.Contains("Taper", StringComparison.OrdinalIgnoreCase) - || n.Contains("Scarab", StringComparison.OrdinalIgnoreCase) - || n.Contains("Prismatic", StringComparison.OrdinalIgnoreCase)) return 100; - if (n.Contains("Arrow", StringComparison.OrdinalIgnoreCase) - || n.Contains("Bolt", StringComparison.OrdinalIgnoreCase) - || n.Contains("Quarrel", StringComparison.OrdinalIgnoreCase) - || n.Contains("Atlatl Dart", StringComparison.OrdinalIgnoreCase)) return 250; - if (n.Contains("Pea", StringComparison.OrdinalIgnoreCase) - || n.Contains("Grain", StringComparison.OrdinalIgnoreCase)) return 100; + /// + /// The stack size guessed from a name while the item's MaxStackSize isn't known. Pyreals by + /// their exact name only, the rest by whole words: "Pyreal Mote" (it doesn't stack) used to be + /// a 25000 pyreal stack and a "Spear" or "Pearl" a 100 "Pea" stack. + /// + internal static int NameFallbackMaxStack(string? n) + { + if (string.IsNullOrWhiteSpace(n)) return 1; + n = n.Trim(); + if (n.Equals("Pyreal", StringComparison.OrdinalIgnoreCase) || n.Equals("Pyreals", StringComparison.OrdinalIgnoreCase)) return 25000; + if (HasWord(n, "Trade Note")) return 100; + if (HasWord(n, "Taper") || HasWord(n, "Scarab") || HasWord(n, "Prismatic")) return 100; + if (HasWord(n, "Arrow") || HasWord(n, "Arrows") || HasWord(n, "Bolt") || HasWord(n, "Bolts") + || HasWord(n, "Quarrel") || HasWord(n, "Quarrels") || HasWord(n, "Atlatl Dart") || HasWord(n, "Atlatl Darts")) return 250; + if (HasWord(n, "Pea") || HasWord(n, "Peas") || HasWord(n, "Grain")) return 100; // Salvage bags are intentionally NOT here — each bag is a unique item // with quality props; they do not stack. return 1; } + + /// in as whole words (letters on neither side), any case. + private static bool HasWord(string name, string word) + { + for (int at = name.IndexOf(word, StringComparison.OrdinalIgnoreCase); at >= 0; + at = name.IndexOf(word, at + 1, StringComparison.OrdinalIgnoreCase)) + { + int end = at + word.Length; + if ((at == 0 || !char.IsLetter(name[at - 1])) && (end == name.Length || !char.IsLetter(name[end]))) + return true; + } + return false; + } +} + +/// +/// Stack groups whose merges the server keeps refusing, when their stack size was only guessed +/// from the name: after GiveUpAfter refusals with no merge between, the group is left alone for +/// the plugin's life. A merge that goes through clears the count. +/// +internal sealed class StackGroupRefusals +{ + internal const int GiveUpAfter = 3; + private readonly Dictionary _refused = new(); + private readonly HashSet _givenUp = new(); + + /// A refused merge in : true when this one gives the group up. + public bool Refused(string group) + { + if (string.IsNullOrEmpty(group) || _givenUp.Contains(group)) return false; + int n = _refused.TryGetValue(group, out int c) ? c + 1 : 1; + _refused[group] = n; + if (n < GiveUpAfter) return false; + _givenUp.Add(group); + return true; + } + + public void Merged(string group) { if (!string.IsNullOrEmpty(group)) _refused.Remove(group); } + + public bool GivenUp(string group) => _givenUp.Contains(group); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs index 8f84088..5970cd3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs @@ -26,7 +26,7 @@ internal sealed class LootEditorBridge private readonly LootEditSession _session = new(); private readonly Func _inUsePath; private readonly Action _onSaved; - private readonly string[] _vendorFolders; + private readonly Func> _vendorFolders; // Follow RynthAi's loot profile while the editor shows it and has no edits. private bool _followInUse = true; @@ -42,7 +42,8 @@ internal sealed class LootEditorBridge /// RynthAi's item lookups for "Add to loot profile". Set once by the plugin. public LootItemHooks Items { get; set; } = new(); - public LootEditorBridge(Func inUsePath, Action onSaved, params string[] vendorFolders) + /// AutoVendor's folders in its order (character, server, main). + public LootEditorBridge(Func inUsePath, Action onSaved, Func> vendorFolders) { _inUsePath = inUsePath; _onSaved = onSaved; @@ -339,14 +340,9 @@ internal sealed class LootEditorBridge names.Sort(StringComparer.OrdinalIgnoreCase); foreach (string f in names) files.Add(new LootEditFile { Path = f, Display = Path.GetFileName(f) }); } - foreach (string folder in _vendorFolders) - { - if (!Directory.Exists(folder)) continue; - var names = new List(Directory.GetFiles(folder, "*.utl", new EnumerationOptions { RecurseSubdirectories = true, MaxRecursionDepth = 2 })); - names.Sort(StringComparer.OrdinalIgnoreCase); - foreach (string f in names) - files.Add(new LootEditFile { Path = f, Display = "AutoVendor: " + Path.GetRelativePath(folder, f) }); - } + // In AutoVendor's order, each marked by its folder (character, server, main). + foreach ((string path, string display) in Vendor.AutoVendorManager.ListProfiles(_vendorFolders())) + files.Add(new LootEditFile { Path = path, Display = display }); } catch { } if (_session.IsOpen && !files.Exists(f => LootEditSession.SamePath(f.Path, _session.Path))) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs index 1f84f44..33f19c3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs @@ -53,8 +53,10 @@ internal sealed class UseRefusalWatch public const int RefusalsBeforeRetry = 3; /// The pause after the clean stop, before the one retry. public const long CleanStopPauseMs = 1500; - public const long FirstBackoffMs = 5 * 60_000; - public const long MaxBackoffMs = 20 * 60_000; + // A probe is one use and one jump, so it costs far less than loot left behind: 5 minutes, doubling + // to 20, was much too long to stop looting (the owner, 2026-11-06). + public const long FirstBackoffMs = 30_000; + public const long MaxBackoffMs = 2 * 60_000; public enum Phase { Normal, Retrying, Stuck } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LootByName.cs b/Plugins/RynthCore.Plugin.RynthAi/LootByName.cs new file mode 100644 index 0000000..3578e29 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LootByName.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +// Loot by name (2026-11-02). A short list of names the player types (/ra lootname add Unearthed Cache); +// while botting, anything lying in the world with one of those names inside the radius is used: a +// container opens (and the chest looter takes it), an item on the ground is picked up. The list, the +// matching, the settings string and the attempt bookkeeping live here, with no game types, so they can be tested alone; +// RynthAiPlugin.LootByName.cs is the host side. + +/// The names to loot and how far to look (the settings' Loot By Names and Loot By Name Radius). +internal sealed class LootByNameList +{ + public const double DefaultRadius = 30, MinRadius = 3, MaxRadius = 200; + public const int MaxNames = 50; + + private readonly List _names = new(); + + public double Radius { get; private set; } = DefaultRadius; + public IReadOnlyList Names => _names; + public bool IsEmpty => _names.Count == 0; + + /// True when added (false: empty, already there, or the list is full). + public bool Add(string? name) + { + string n = Clean(name); + if (n.Length == 0 || _names.Count >= MaxNames || IndexOf(n) >= 0) return false; + _names.Add(n); + return true; + } + + public bool Remove(string? name) + { + int i = IndexOf(Clean(name)); + if (i < 0) return false; + _names.RemoveAt(i); + return true; + } + + public void Clear() => _names.Clear(); + + public void SetRadius(double yards) => Radius = Math.Clamp(yards, MinRadius, MaxRadius); + + public bool MatchesAny(string? objectName) + { + if (string.IsNullOrEmpty(objectName)) return false; + foreach (string p in _names) + if (Matches(p, objectName)) return true; + return false; + } + + /// + /// Whole name, ignoring case. A * at the start and/or end makes it "ends with", "starts with" or "contains": + /// "*cache*" matches "Unearthed Cache". A name with no * never matches part of another ("Cache" does not + /// match "Unearthed Cache"), so a short word cannot loot half the world. + /// + public static bool Matches(string pattern, string name) + { + if (pattern.Length == 0 || name.Length == 0) return false; + bool head = pattern[0] == '*', tail = pattern.Length > 1 && pattern[^1] == '*'; + string core = pattern.Trim('*'); + if (core.Length == 0) return false; // "*" alone matches nothing + var cmp = StringComparison.OrdinalIgnoreCase; + if (head && tail) return name.Contains(core, cmp); + if (head) return name.EndsWith(core, cmp); + if (tail) return name.StartsWith(core, cmp); + return name.Equals(core, cmp); + } + + private int IndexOf(string n) + { + for (int i = 0; i < _names.Count; i++) + if (string.Equals(_names[i], n, StringComparison.OrdinalIgnoreCase)) return i; + return -1; + } + + private static string Clean(string? s) => (s ?? string.Empty).Trim().Trim('"').Trim(); + + // ── The settings string ──────────────────────────────────────────────── + + /// The names as saved in the settings: separated by |. + public const char Separator = '|'; + + /// A list from the settings' names string and radius (blank and repeated names dropped). + public static LootByNameList Parse(string? names, double radius) + { + var list = new LootByNameList(); + list.SetRadius(radius > 0 ? radius : DefaultRadius); + foreach (string n in (names ?? string.Empty).Split(Separator, StringSplitOptions.RemoveEmptyEntries)) + list.Add(n); + return list; + } + + /// The names string the settings keep: "Unearthed Cache | *Doubloon*". + public string ToSettingString() => string.Join(" | ", _names); + + /// A names string tidied the way a list would save it (the settings box can hold anything typed). + public static string Normalize(string? names) => Parse(names, DefaultRadius).ToSettingString(); +} + +/// +/// What was tried on each object: how often it was used and when, which ones are finished (opened, or given up +/// on). Entries for objects that left the world are dropped by , so a chest that comes back +/// (a new one with a new id, or a regenerating one) is looted again. +/// +internal sealed class LootNameTracker +{ + /// Uses on one object before giving up on it for a while. + public const int MaxUses = 4; + /// Between two uses: the client walks to the object in this time. + public const long UseGapMs = 5000; + /// After MaxUses with nothing to show, the object is left alone this long. + public const long GiveUpMs = 120_000; + + private sealed class Entry + { + public int Uses; + public long LastUseAt; + public long BlockedUntil; + public bool Done; + } + + private readonly Dictionary _entries = new(); + + /// The object is finished or being left alone: do not pick it. + public bool IsBlocked(int id, long now) + => _entries.TryGetValue(id, out var e) && (e.Done || now < e.BlockedUntil); + + /// A use may go out now: none yet, or the last one is old enough and the budget is not spent. + public bool CanUse(int id, long now) + { + if (!_entries.TryGetValue(id, out var e)) return true; + if (e.Done || now < e.BlockedUntil) return false; + return e.Uses < MaxUses && now - e.LastUseAt >= UseGapMs; + } + + /// True when this was the last use of the budget and the gap after it has passed: give up on it. + public bool Exhausted(int id, long now) + => _entries.TryGetValue(id, out var e) && e.Uses >= MaxUses && now - e.LastUseAt >= UseGapMs; + + public void NoteUse(int id, long now) + { + if (!_entries.TryGetValue(id, out var e)) _entries[id] = e = new Entry(); + e.Uses++; + e.LastUseAt = now; + } + + /// Opened or picked up: finished until the object is gone. + public void MarkDone(int id) + { + if (!_entries.TryGetValue(id, out var e)) _entries[id] = e = new Entry(); + e.Done = true; + } + + public void GiveUp(int id, long now) + { + if (!_entries.TryGetValue(id, out var e)) _entries[id] = e = new Entry(); + e.Uses = 0; + e.BlockedUntil = now + GiveUpMs; + } + + public int Uses(int id) => _entries.TryGetValue(id, out var e) ? e.Uses : 0; + + /// Forget objects that are no longer in the world. + public void Prune(Func stillThere) + { + List? gone = null; + foreach (int id in _entries.Keys) + if (!stillThere(id)) (gone ??= new()).Add(id); + if (gone != null) + foreach (int id in gone) _entries.Remove(id); + } + + public void Clear() => _entries.Clear(); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs index d82bc87..bebd182 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs @@ -250,6 +250,8 @@ public sealed partial class RynthAiPlugin ["approachdistance"] = "ApproachRange", ["navpriorityboost"] = "BoostNavPriority", ["lootpriorityboost"] = "BoostLootPriority", + ["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off + ["lootchestsmacrooff"] = "LootChestsMacroOff", ["dooropenrange"] = "OpenDoorRange", ["autofellowmanagement"] = "AutoFellowMgmt", ["switchwandstodebuff"] = "UseDispelItems", @@ -277,6 +279,7 @@ public sealed partial class RynthAiPlugin ["follownavmin"] = "FollowNavMin", ["outdoorhuntrange"] = "OutdoorHuntRange", ["outdoorhuntradius"] = "OutdoorHuntRadius", + ["outdoorhuntpick"] = "OutdoorHuntPick", // UtilityBelt AutoVendor options (/ub opt set AutoVendor.TestMode true) ["autovendor.enabled"] = "AutoVendorEnabled", ["autovendor.enablebuying"] = "AutoVendorEnableBuying", @@ -873,6 +876,7 @@ public sealed partial class RynthAiPlugin if (parts.Length >= 4) { string fellowName = string.Join(" ", parts, 3, parts.Length - 3); + NoteFellowshipCreate(); // Open fellowship on create (RynthAiPlugin.FellowOpen.cs) Host.InvokeChatParser($"/fellowship create {fellowName}"); Reply.Answered(); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index 9449a4a..d59acee 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -110,6 +110,7 @@ internal sealed class ManaStoneManager // With an Eternal Mana Charge (never used up) there's no reason to wait for 25%: top // gear up below 75% (Lucy carried one on her Items list and it was never used, 2026-09-30). private const double WornRefillPctOfMaxEternal = 0.75; + private const long EternalRetryMs = 20_000; private long _lastGearDiagAt; private readonly Dictionary _manaIdRequestedAt = new(); @@ -239,8 +240,12 @@ internal sealed class ManaStoneManager // re-select it every tick and never get to Priority 2 (drain looted). if (_state == TapState.UsingOnPlayer && _activeStoneId != 0) { - _stoneUseOnPlayerCooldownUntil[_activeStoneId] = now + StoneUseOnPlayerCooldownMs; - _host.Log($"[RynthAi] ManaStone: blacklisting stone 0x{(uint)_activeStoneId:X8} for use-on-player ({StoneUseOnPlayerCooldownMs / 1000}s cooldown)."); + // An Eternal charge can't be used up or be the problem: a use that got no answer is + // tried again soon (one sent mid stance change never left the client, 2026-11-06). + WorldObject? timedOut = _objectCache[_activeStoneId]; + long stoneCooldown = timedOut != null && IsEternal(timedOut) ? EternalRetryMs : StoneUseOnPlayerCooldownMs; + _stoneUseOnPlayerCooldownUntil[_activeStoneId] = now + stoneCooldown; + _host.Log($"[RynthAi] ManaStone: blacklisting stone 0x{(uint)_activeStoneId:X8} for use-on-player ({stoneCooldown / 1000}s cooldown)."); } // For the tap path, the STONE is the more likely culprit when an // action silently fails — AC won't drain into a charged stone, so @@ -550,7 +555,7 @@ internal sealed class ManaStoneManager // starves the drain path entirely. // Not in a fight (FightIsOn): the drain waits for it to end. bool drainWaits = DrainWaitsForFight(); - int stoneId = _settings.EnableManaTapping && !drainWaits ? FindEmptyStone() : 0; + int stoneId = TappingApplies && !drainWaits ? FindEmptyStone() : 0; int targetId = stoneId != 0 ? FindTapTarget(threshold) : 0; if (stoneId != 0 && targetId != 0) @@ -703,6 +708,7 @@ internal sealed class ManaStoneManager /// public int FreeEmptyStoneSlots() { + if (HasEternalChargeCached()) return 0; // tapping is ignored: nothing is looted to drain if (_lootedForTap.Count > 0) return 0; return CountEmptyStones() > 0 ? 1 : 0; } @@ -716,7 +722,7 @@ internal sealed class ManaStoneManager { if (_state == TapState.TappingItem) return true; if (_lootedForTap.Count == 0) return false; - if (!_settings.EnableManaTapping || !_settings.IsMacroRunning || !_host.HasUseObjectOn) return false; + if (!TappingApplies || !_settings.IsMacroRunning || !_host.HasUseObjectOn) return false; // The drain waits for the fight to end, so it holds nothing meanwhile. No second item is // looted to tap: FreeEmptyStoneSlots is 0 while this one waits. if (DrainWaitsForFight()) return false; @@ -838,6 +844,37 @@ internal sealed class ManaStoneManager return _chargedCached; } + // With an Eternal Mana Charge in the pack tapping is ignored (the owner, 2026-11-06): the charge + // does all the refilling and always wins, so a stone that drained something would just stay full. + // No draining, nothing looted to drain, no stones looted. The Mana Tap setting itself is untouched, + // so it applies again if the charge leaves the pack. + private bool TappingApplies => _settings.EnableManaTapping && !HasEternalChargeCached(); + + private long _eternalCheckAt = long.MinValue; + private bool _eternalCached; + private bool _eternalNoted; + + /// An Eternal Mana Charge is in the pack (looked up at most every 2 s: the looter asks per item). + internal bool HasEternalChargeCached() + { + long now = NowMs; + if (_eternalCheckAt != long.MinValue && now - _eternalCheckAt < 2000) return _eternalCached; + _eternalCheckAt = now; + _eternalCached = HasEternalCharge(); + if (_eternalCached != _eternalNoted) + { + _eternalNoted = _eternalCached; + if (_settings.EnableManaTapping) + _host.Log(_eternalCached + ? "[RynthAi] ManaStone: an Eternal Mana Charge is in the pack: mana tapping is ignored while it is." + : "[RynthAi] ManaStone: no Eternal Mana Charge in the pack any more: mana tapping applies again."); + } + return _eternalCached; + } + + /// True for an Eternal Mana Charge (internal so the looter can tell one from a stone). + internal static bool IsEternalCharge(WorldObject item) => IsEternal(item); + private bool HasEternalCharge() { int playerId = unchecked((int)_host.GetPlayerId()); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.Resume.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.Resume.cs new file mode 100644 index 0000000..cfb8d31 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.Resume.cs @@ -0,0 +1,46 @@ +// ExpressionEngine.Resume.cs - The meta's $variables, dictionaries and stopwatches out of and back into the +// engine, for Resume Meta After Reload (MetaResume.cs). @pvars and &gvars are on disk and need nothing. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.Meta; + +internal sealed partial class ExpressionEngine +{ + /// Copies every $variable, dictionary and stopwatch (and the next handles) into . + public void ExportVariables(MetaResumeState s) + { + s.Variables = new Dictionary(_variables, StringComparer.OrdinalIgnoreCase); + s.Dicts = new Dictionary>(StringComparer.Ordinal); + foreach (var d in _dicts) s.Dicts[d.Key] = new Dictionary(d.Value, StringComparer.Ordinal); + s.NextDictId = _nextDictId; + long now = TickMs(); + s.Stopwatches = new Dictionary(StringComparer.Ordinal); + foreach (var sw in _stopwatches) s.Stopwatches[sw.Key] = (sw.Value.ElapsedMs(now) / 1000.0, sw.Value.Running); + s.NextStopwatchId = _nextSwId; + } + + /// Replaces the $variables, dictionaries and stopwatches with the saved ones. A handle ("D:3", + /// "SW:4") held in a variable names the same dict or stopwatch again; new handles never reuse a saved one. + /// A running stopwatch runs on from its saved time (the reload's few seconds aren't counted, as with the + /// seconds-in-state clocks). + public void RestoreVariables(MetaResumeState s) + { + _variables.Clear(); + foreach (var kv in s.Variables) _variables[kv.Key] = kv.Value; + _dicts.Clear(); + foreach (var d in s.Dicts) _dicts[d.Key] = new Dictionary(d.Value, StringComparer.Ordinal); + _nextDictId = Math.Max(_nextDictId, s.NextDictId); + _dictSweepAt = Math.Max(DictSweepMin, _dicts.Count * 2); + long now = TickMs(); + _stopwatches.Clear(); + foreach (var sw in s.Stopwatches) + _stopwatches[sw.Key] = new MetaStopwatch + { + AccumulatedMs = (long)Math.Round(Math.Max(0, sw.Value.Seconds) * 1000.0), + Running = sw.Value.Running, + StartedAtMs = now, + }; + _nextSwId = Math.Max(_nextSwId, s.NextStopwatchId); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index a78718f..79af78b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -110,10 +110,20 @@ internal sealed partial class ExpressionEngine /// fake clock; the plugin never changes it. internal Func TickMs { get; set; } = static () => Environment.TickCount64; - // Stopwatch store: handle → Stopwatch. Persistent (not cleared per eval) — handles are stored in variables. - private readonly Dictionary _stopwatches = new(StringComparer.Ordinal); + // Stopwatch store: handle → stopwatch. Persistent (not cleared per eval) — handles are stored in variables. + // On TickMs, and its elapsed time can be set, so Resume Meta After Reload carries a stopwatch over with the + // variable that names it (a handle kept without its stopwatch read 0 s for ever, 2026-11-07). + private readonly Dictionary _stopwatches = new(StringComparer.Ordinal); private int _nextSwId; + private sealed class MetaStopwatch + { + public long AccumulatedMs; + public long StartedAtMs; // while Running + public bool Running; + public long ElapsedMs(long now) => AccumulatedMs + (Running ? Math.Max(0, now - StartedAtMs) : 0); + } + // Motion name → (AC motion uint, wanted state). Matches UB Motion enum values. private static readonly Dictionary MotionValues = new(StringComparer.OrdinalIgnoreCase) { @@ -211,6 +221,11 @@ internal sealed partial class ExpressionEngine // wobjectfindnearestmonster[] also finds attackable NPCs (a buff bot) combat rightly leaves alone. internal Func? CombatTargetCount { get; set; } + // ralastchestlooted[] (RynthAi only, 2026-11-07): the id of the last chest RynthAi looted to the end + // (every item judged; one that closed first doesn't count), 0 before any. A meta that opens a chest + // keeps opening it until this is its id: an open use can go unanswered, and a chest can close mid-loot. + internal Func? LastChestLooted { get; set; } + // ── Backward-compat shim ────────────────────────────────────────────────── /// Executes an expression for its side effects. Always returns true. @@ -393,6 +408,7 @@ internal sealed partial class ExpressionEngine // Whole seconds since our last kill; before the first, since the macro start (or login). "secondssincelastkill" => (_killClock?.SecondsSinceLastKill() ?? 0).ToString(CultureInfo.InvariantCulture), "ratargetcount" => (CombatTargetCount?.Invoke() ?? -1).ToString(CultureInfo.InvariantCulture), + "ralastchestlooted" => (LastChestLooted?.Invoke() ?? 0u).ToString(CultureInfo.InvariantCulture), // ── World object queries ────────────────────────────────────────── "wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)), @@ -789,26 +805,34 @@ internal sealed partial class ExpressionEngine private string EvalStopwatchCreate() { string handle = $"SW:{_nextSwId++}"; - _stopwatches[handle] = new System.Diagnostics.Stopwatch(); + _stopwatches[handle] = new MetaStopwatch(); return handle; } private string EvalStopwatchStart(string handle) { - if (_stopwatches.TryGetValue(handle, out var sw)) sw.Start(); + if (_stopwatches.TryGetValue(handle, out var sw) && !sw.Running) + { + sw.StartedAtMs = TickMs(); + sw.Running = true; + } return handle; } private string EvalStopwatchStop(string handle) { - if (_stopwatches.TryGetValue(handle, out var sw)) sw.Stop(); + if (_stopwatches.TryGetValue(handle, out var sw) && sw.Running) + { + sw.AccumulatedMs = sw.ElapsedMs(TickMs()); + sw.Running = false; + } return handle; } private string EvalStopwatchElapsedSeconds(string handle) { if (!_stopwatches.TryGetValue(handle, out var sw)) return "0"; - return sw.Elapsed.TotalSeconds.ToString("G", CultureInfo.InvariantCulture); + return (sw.ElapsedMs(TickMs()) / 1000.0).ToString("G", CultureInfo.InvariantCulture); } private static string EvalOrd(string s) @@ -3614,6 +3638,7 @@ internal sealed partial class ExpressionEngine ["EnableAutostack"] = (() => B(s.EnableAutostack), v => s.EnableAutostack = ToDouble(v) != 0), ["EnableAutocram"] = (() => B(s.EnableAutocram), v => s.EnableAutocram = ToDouble(v) != 0), ["ReadUnknownScrolls"] = (() => B(s.ReadUnknownScrolls), v => s.ReadUnknownScrolls = ToDouble(v) != 0), + ["UnboxAetheriaWhenIdle"] = (() => B(s.UnboxAetheriaWhenIdle), v => s.UnboxAetheriaWhenIdle = ToDouble(v) != 0), ["EnableCombineSalvage"]= (() => B(s.EnableCombineSalvage),v => s.EnableCombineSalvage= ToDouble(v) != 0), ["SalvageWithoutPanel"] = (() => B(s.SalvageWithoutPanel), v => s.SalvageWithoutPanel = ToDouble(v) != 0), ["PeaceModeWhenIdle"] = (() => B(s.PeaceModeWhenIdle), v => s.PeaceModeWhenIdle = ToDouble(v) != 0), @@ -3645,12 +3670,15 @@ internal sealed partial class ExpressionEngine ["ItemInfoLootSalvage"] = (() => B(s.ItemInfoSettings.LootChatSalvage), v => s.ItemInfoSettings.LootChatSalvage = ToDouble(v) != 0), // -1 = the Item Info chat type. ["ItemInfoLootChatType"] = (() => I(s.ItemInfoSettings.LootChatType), v => { if (int.TryParse(v, out int i)) s.ItemInfoSettings.LootChatType = Math.Clamp(i, -1, 31); }), + // Info text colour: "#RRGGBB" or a name ("allegiance"); "" / "default" = the chat type's own colour. + ["ItemInfoTextColor"] = (() => s.ItemInfoSettings.TextColor, v => { if (RynthCore.Plugin.RynthAi.ItemInfo.MagItemInfoCatalog.ParseTextColor(v ?? string.Empty) is { } c) s.ItemInfoSettings.TextColor = c; }), ["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0), ["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0), ["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0), ["UseDispelItems"] = (() => B(s.UseDispelItems), v => s.UseDispelItems = ToDouble(v) != 0), ["CastDispelSelf"] = (() => B(s.CastDispelSelf), v => s.CastDispelSelf = ToDouble(v) != 0), ["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0), + ["OpenFellowOnCreate"] = (() => B(s.OpenFellowOnCreate), v => s.OpenFellowOnCreate = 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); }), @@ -3744,6 +3772,8 @@ internal sealed partial class ExpressionEngine ["CurrentLootPath"] = (() => s.CurrentLootPath, v => s.CurrentLootPath = v), // Loot Mode: 0 = profile, 1 = rares and needed mana stones only (the words work too). ["LootMode"] = (() => I(Loot.LootModes.Clamp(s.LootMode)), v => { if (Loot.LootModes.TryParse(v, out int m)) s.LootMode = m; }), + // Item Tool > Chest re-lock wait (s): 5..600. + ["ChestRelockWaitSec"] = (() => I(s.ChestRelockWaitSec), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d) && double.IsFinite(d)) s.ChestRelockWaitSec = ItemTool.ChestKeyLooter.ClampRelockWaitSec((int)Math.Round(Math.Clamp(d, 0, 100_000))); }), ["CurrentMetaPath"] = (() => s.CurrentMetaPath, v => s.CurrentMetaPath = v), ["OpenDoors"] = (() => B(s.OpenDoors), v => s.OpenDoors = ToDouble(v) != 0), ["NavRecoveryEnabled"] = (() => B(s.NavRecoveryEnabled), v => s.NavRecoveryEnabled = ToDouble(v) != 0), @@ -3751,10 +3781,12 @@ internal sealed partial class ExpressionEngine ["NavOffTrackYards"] = (() => F(s.NavOffTrackYards), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavOffTrackYards = Math.Clamp(f, 160f, 1000f); }), ["OutdoorHuntRange"] = (() => F(s.OutdoorHuntRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.OutdoorHuntRange = (float)Math.Clamp(f, RynthAiPlugin.OutdoorHuntRangeMin, RynthAiPlugin.OutdoorHuntRangeMax); }), ["OutdoorHuntRadius"] = (() => F(s.OutdoorHuntRadius), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.OutdoorHuntRadius = (float)Math.Clamp(f, 0, RynthAiPlugin.OutdoorHuntRadiusMax); }), - ["NavMaxDetourAttempts"] = (() => I(s.NavMaxDetourAttempts), v => { if (int.TryParse(v, out int i)) s.NavMaxDetourAttempts = Math.Clamp(i, 1, 10); }), + ["OutdoorHuntPick"] = (() => I(s.OutdoorHuntPick), v => { if (int.TryParse(v, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture, out int i)) s.OutdoorHuntPick = Math.Clamp(i, 0, 2); }), + ["NavMaxDetourAttempts"] =(() => I(s.NavMaxDetourAttempts), v => { if (int.TryParse(v, out int i)) s.NavMaxDetourAttempts = Math.Clamp(i, 1, 10); }), ["OpenDoorRange"] = (() => F(s.OpenDoorRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.OpenDoorRange = f; }), ["BoostNavPriority"] = (() => B(s.BoostNavPriority), v => s.BoostNavPriority = ToDouble(v) != 0), ["BoostLootPriority"] = (() => B(s.BoostLootPriority), v => s.BoostLootPriority = ToDouble(v) != 0), + ["LootChestsMacroOff"] = (() => B(s.LootChestsMacroOff), v => s.LootChestsMacroOff = ToDouble(v) != 0), }; return _settingsMap; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt index ba39439..75c2a38 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt @@ -1711,9 +1711,9 @@ answer with the value ub-IT gives when there is nothing to report. Supported setting names: Booleans: EnableCombat, EnableBuffing, EnableNavigation, EnableLooting, EnableMeta, EnableRaycasting, EnableAutostack, EnableAutocram, - EnableCombineSalvage, PeaceModeWhenIdle, RebuffWhenIdle, + EnableCombineSalvage, PeaceModeWhenIdle, RebuffWhenIdle, UnboxAetheriaWhenIdle, SummonPets, MineOnly, UseDispelItems, CastDispelSelf, - AutoFellowMgmt, UseRecklessness, UseNativeAttack + AutoFellowMgmt, OpenFellowOnCreate, UseRecklessness, UseNativeAttack Integers: MonsterRange, RingRange, ApproachRange, MinRingTargets, HealAt, RestamAt, GetManaAt, TopOffHP, TopOffStam, TopOffMana, HealOthersAt, MeleeAttackPower, MissileAttackPower, diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs new file mode 100644 index 0000000..46f08f7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs @@ -0,0 +1,113 @@ +// MetaManager.Resume.cs - The meta's runtime out of and back into a MetaManager, for Resume Meta After +// Reload (MetaResume.cs says what goes over and why). Plugin-tick thread (Shutdown and OnLoginComplete +// run on the pump, as Think does). +using System; +using System.Collections.Generic; +using System.Numerics; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.Meta; + +internal sealed partial class MetaManager +{ + /// Copies the running meta into (everything but the identity fields). + public void ExportRuntime(MetaResumeState s) + { + DateTime now = Clock(); + s.MetaPath = _settings.CurrentMetaPath ?? ""; + s.MacroRunning = _settings.IsMacroRunning; + s.State = _settings.CurrentState ?? "Default"; + // A state entered (or a reset asked for) that the tick hasn't applied yet: the rules' fired marks + // belong to the old state, so the restore enters the state afresh, as the next tick would have. + s.EntryPending = _settings.ForceStateReset + || !string.Equals(_settings.CurrentState, _lastState, StringComparison.OrdinalIgnoreCase) + || _settings.MetaCallStackReset; + s.SecondsInState = Math.Max(0, (now - _stateStartTime).TotalSeconds); + s.SecondsInStateP = Math.Max(0, (now - _statePStartTime).TotalSeconds); + + // The stacks enumerate top first; saved bottom first so pushing them back keeps the order. + string[] states = _stateStack.ToArray(); + double?[] paused = _statePPaused.ToArray(); + s.CallStack.Clear(); + for (int i = states.Length - 1; i >= 0; i--) + s.CallStack.Add((states[i], i < paused.Length ? paused[i] : null)); + + s.FiredRules.Clear(); + lock (_settings.MetaRulesLock) + { + s.RulesSignature = MetaResumeStore.Signature(_settings.MetaRules); + if (!s.EntryPending && _settings.MetaRules != null) + for (int i = 0; i < _settings.MetaRules.Count; i++) + if (_settings.MetaRules[i].HasFired) s.FiredRules.Add(i); + } + + s.WatchdogActive = _watchdogActive; + s.WatchdogState = _watchdogState; + s.WatchdogMeters = _watchdogMetersRequired; + s.WatchdogSeconds = _watchdogSecondsConfig; + s.WatchdogSecondsLeft = _watchdogActive ? Math.Max(0, (_watchdogExpiration - now).TotalSeconds) : 0; + + _expressions?.ExportVariables(s); + + s.NavPath = _settings.CurrentNavPath ?? ""; + s.RouteLines = _settings.CurrentRoute != null && _settings.CurrentRoute.Points.Count > 0 + ? new List(_settings.CurrentRoute.ToLines()) + : new List(); + s.NavIndex = _settings.ActiveNavIndex; + s.NavEnabled = _settings.EnableNavigation; + } + + /// + /// Puts a saved runtime back (the caller checked it is this character's, this client's and this meta's): + /// the next Think carries on in the saved state without entering it again, so nothing that already ran + /// there (a recall, a route load, a setvar in Default) runs twice. + /// + public void RestoreRuntime(MetaResumeState s) + { + DateTime now = Clock(); + _settings.CurrentState = s.State; + _settings.IsMacroRunning = s.MacroRunning; + _lastState = s.State; + _lastMacroRunning = s.MacroRunning; // no "macro started": that would re-arm every rule + _settings.MetaCallStackReset = false; + _settings.ForceStateReset = s.EntryPending; + _stateStartTime = now.AddSeconds(-s.SecondsInState); + _statePStartTime = now.AddSeconds(-s.SecondsInStateP); + _statePResume = null; + + _stateStack.Clear(); + _statePPaused.Clear(); + foreach (var (state, p) in s.CallStack) + { + _stateStack.Push(state); + _statePPaused.Push(p); + } + + lock (_settings.MetaRulesLock) + { + _replayRules.Clear(); + if (_settings.MetaRules != null) + { + foreach (MetaRule r in _settings.MetaRules) r.HasFired = false; + foreach (int i in s.FiredRules) + if (i >= 0 && i < _settings.MetaRules.Count) _settings.MetaRules[i].HasFired = true; + } + } + + _watchdogActive = s.WatchdogActive && s.WatchdogState.Length > 0; + _watchdogState = s.WatchdogState; + _watchdogMetersRequired = s.WatchdogMeters; + _watchdogSecondsConfig = s.WatchdogSeconds; + _watchdogExpiration = now.AddSeconds(s.WatchdogSecondsLeft); + // Measured from where the character stands now (it didn't move during the reload). + if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _)) + _lastWatchdogPos = new Vector3(x, y, z); + + Expressions.RestoreVariables(s); + + _settings.CurrentNavPath = s.NavPath; + _settings.CurrentRoute = s.RouteLines.Count > 0 ? NavRouteParser.LoadFromLines(s.RouteLines) : new NavRouteParser(); + _settings.ActiveNavIndex = Math.Clamp(s.NavIndex, 0, Math.Max(0, _settings.CurrentRoute.Points.Count)); + _settings.EnableNavigation = s.NavEnabled; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs index 76fc432..ed776db 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs @@ -11,7 +11,7 @@ using RynthCore.Install; namespace RynthCore.Plugin.RynthAi.Meta; -internal sealed class MetaManager +internal sealed partial class MetaManager { private readonly LegacyUiSettings _settings; private readonly RynthCoreHost _host; @@ -222,6 +222,14 @@ internal sealed class MetaManager if (_expressions != null) _expressions.CombatTargetCount = count; } + // The last chest looted to the end, for ralastchestlooted[]. + private Func? _lastChestLooted; + public void SetLastChestLooted(Func? lastChest) + { + _lastChestLooted = lastChest; + if (_expressions != null) _expressions.LastChestLooted = lastChest; + } + public void SetPlayerId(uint id) { _playerId = id; @@ -343,6 +351,7 @@ internal sealed class MetaManager engine.SetKillClock(_killClock); engine.CorpseOpenedByMe = _corpseOpenedByMe; engine.CombatTargetCount = _combatTargetCount; + engine.LastChestLooted = _lastChestLooted; // vtsetsetting[] / vtgetsetting[] take VTank names and units, as '/vt opt set|get' does. engine.VtOptionSetter = TrySetVtOption; engine.VtOptionGetter = GetVtOption; @@ -1587,6 +1596,8 @@ internal sealed class MetaManager ["approachdistance"] = "ApproachRange", ["navpriorityboost"] = "BoostNavPriority", ["lootpriorityboost"] = "BoostLootPriority", + ["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off + ["lootchestsmacrooff"] = "LootChestsMacroOff", ["dooropenrange"] = "OpenDoorRange", ["autofellowmanagement"] = "AutoFellowMgmt", ["switchwandstodebuff"] = "UseDispelItems", diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaResume.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaResume.cs new file mode 100644 index 0000000..26da7fd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaResume.cs @@ -0,0 +1,316 @@ +// MetaResume.cs - The meta's runtime, carried over a hot reload (2026-11-07). +// +// Tom: "a hot reload setting where it remembers which meta state you're in and restarts in that state so +// Drakkon doesn't recall back every time" - and then: "there might be some variables set in default of +// other states". Until now a hot reload (RynthCore or RynthAi updated while playing) built a new +// MetaManager: LoadSettings put the state back to Default, every Default rule fired again (a meta that +// recalls in Default recalled), and every $variable, the call stack, the watchdog and an embedded route +// were gone. Restoring the state name alone would skip what Default set up, so the whole runtime goes over: +// +// the state and whether the macro ran; seconds in the state (both clocks); which rules had fired (so the +// state's one-shot rules don't fire again); the call stack; the watchdog; every $variable and dictionary; +// the loaded route, its waypoint and whether nav was on. +// +// Saved at the plugin's Shutdown (a hot reload unloads it), restored at the next OnLoginComplete in the SAME +// client process for the SAME character, within 10 minutes, with the SAME meta (path and rules) loaded, and +// only when it's a carried-over session (RynthAiPlugin.IsCarriedOverSession). A real logout deletes it, so a +// real login always starts in Default as before. Setting: Resume Meta After Reload (on by default). +// +// One file per client and character in %LOCALAPPDATA%\RynthCore\rynthai-meta (TrackerSessionStore's folder +// and file rules). Stopwatches go over too (their elapsed time and whether they run): a variable kept +// without its stopwatch read 0 s for ever, and a map rule waiting for "stopwatchelapsedseconds[$MapSW] >= 30" +// never fired again (2026-11-07). Not kept: delayexec queues, pending chat lines (VTank drops them on reload +// too), a Linear route's walking direction (it starts forward). @pvars and &gvars are on disk already. +// +// Tests: RynthCore.RynthAiHostTests MetaResumeTests (a reload modelled as export, a new settings object and +// MetaManager, restore), and the file format and checks. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.Meta; + +/// The meta's runtime at a hot reload. +internal sealed class MetaResumeState +{ + public int ProcessId; + public long ProcessStartUtcTicks; + public uint CharacterId; + public long SavedUtcTicks; + + /// The meta file and a signature of its rules: a different meta is never resumed. + public string MetaPath = ""; + public string RulesSignature = ""; + + public bool MacroRunning; + public string State = "Default"; + /// The state was entered (or a reset asked for) but not applied yet: the restore enters it afresh. + public bool EntryPending; + public double SecondsInState; + public double SecondsInStateP; + /// The call stack, bottom first: the state a Return goes to, and the P seconds it had (null: none). + public List<(string State, double? PSeconds)> CallStack = new(); + /// Indexes (in the meta's top-level rule list) of the rules that had fired since their state was entered. + public List FiredRules = new(); + + public bool WatchdogActive; + public string WatchdogState = ""; + public float WatchdogMeters; + public double WatchdogSeconds; + public double WatchdogSecondsLeft; + + public Dictionary Variables = new(StringComparer.OrdinalIgnoreCase); + public Dictionary> Dicts = new(StringComparer.Ordinal); + public int NextDictId; + /// Stopwatch handle ("SW:4") → its elapsed seconds and whether it runs. + public Dictionary Stopwatches = new(StringComparer.Ordinal); + public int NextStopwatchId; + + public string NavPath = ""; + public List RouteLines = new(); + public int NavIndex; + public bool NavEnabled; +} + +internal static class MetaResumeStore +{ + public const string Header = "RynthAi meta resume v1"; + + /// A save older than this is a different session. + public static readonly TimeSpan MaxAge = TimeSpan.FromMinutes(10); + + private static readonly CultureInfo Ic = CultureInfo.InvariantCulture; + + public static string DefaultDirectory() => RynthCore.Plugin.Shared.TrackerSessionStore.DirectoryFor("rynthai-meta"); + + public static string FileName(int processId, uint characterId) + => "meta-" + processId.ToString(Ic) + "-" + characterId.ToString("X8", Ic) + ".txt"; + + /// + /// A signature of the meta's rules (states, conditions, actions, their data and children, in order): + /// a meta edited or swapped between save and restore has another, and isn't resumed. FNV-1a, so it is + /// the same in every process. + /// + public static string Signature(IReadOnlyList? rules) + { + if (rules == null) return "none"; + ulong h = 14695981039346656037UL; + void Mix(string s) + { + foreach (char c in s) { h ^= c; h *= 1099511628211UL; } + h ^= 0x1F; h *= 1099511628211UL; + } + void Rule(MetaRule r) + { + Mix(r.State ?? ""); Mix(((int)r.Condition).ToString(Ic)); Mix(r.ConditionData ?? ""); + Mix(((int)r.Action).ToString(Ic)); Mix(r.ActionData ?? ""); Mix(r.CallReturnState ?? ""); + Mix(r.Enabled ? "1" : "0"); + Mix("C" + (r.Children?.Count ?? 0).ToString(Ic)); + if (r.Children != null) foreach (MetaRule c in r.Children) Rule(c); + Mix("A" + (r.ActionChildren?.Count ?? 0).ToString(Ic)); + if (r.ActionChildren != null) foreach (MetaRule c in r.ActionChildren) Rule(c); + } + foreach (MetaRule r in rules) Rule(r); + return rules.Count.ToString(Ic) + ":" + h.ToString("X16", Ic); + } + + // ── Format: "key=value" lines, values URL-escaped (variables may hold anything) ── + + public static string Serialize(MetaResumeState s) + { + var sb = new StringBuilder(1024); + sb.Append(Header).Append('\n'); + Line(sb, "pid", s.ProcessId.ToString(Ic)); + Line(sb, "pstart", s.ProcessStartUtcTicks.ToString(Ic)); + Line(sb, "char", s.CharacterId.ToString(Ic)); + Line(sb, "saved", s.SavedUtcTicks.ToString(Ic)); + Line(sb, "meta", Esc(s.MetaPath)); + Line(sb, "sig", Esc(s.RulesSignature)); + Line(sb, "running", s.MacroRunning ? "1" : "0"); + Line(sb, "state", Esc(s.State)); + Line(sb, "entry", s.EntryPending ? "1" : "0"); + Line(sb, "secs", s.SecondsInState.ToString("R", Ic)); + Line(sb, "psecs", s.SecondsInStateP.ToString("R", Ic)); + foreach (var (state, p) in s.CallStack) + Line(sb, "call", Esc(state) + "|" + (p is double d ? d.ToString("R", Ic) : "")); + Line(sb, "fired", string.Join(",", s.FiredRules.ConvertAll(i => i.ToString(Ic)))); + Line(sb, "wd", (s.WatchdogActive ? "1" : "0") + "|" + Esc(s.WatchdogState) + "|" + s.WatchdogMeters.ToString("R", Ic) + + "|" + s.WatchdogSeconds.ToString("R", Ic) + "|" + s.WatchdogSecondsLeft.ToString("R", Ic)); + foreach (var kv in s.Variables) Line(sb, "var", Esc(kv.Key) + "|" + Esc(kv.Value)); + foreach (var d in s.Dicts) + { + var parts = new List(d.Value.Count); + foreach (var kv in d.Value) parts.Add(Esc(kv.Key) + ":" + Esc(kv.Value)); + Line(sb, "dict", Esc(d.Key) + "|" + string.Join(",", parts)); + } + Line(sb, "nextdict", s.NextDictId.ToString(Ic)); + foreach (var sw in s.Stopwatches) + Line(sb, "sw", Esc(sw.Key) + "|" + sw.Value.Seconds.ToString("R", Ic) + "|" + (sw.Value.Running ? "1" : "0")); + Line(sb, "nextsw", s.NextStopwatchId.ToString(Ic)); + Line(sb, "navpath", Esc(s.NavPath)); + foreach (string l in s.RouteLines) Line(sb, "route", Esc(l)); + Line(sb, "navindex", s.NavIndex.ToString(Ic)); + Line(sb, "navon", s.NavEnabled ? "1" : "0"); + Line(sb, "end", "1"); // a torn write never parses + return sb.ToString(); + } + + /// Strict: a wrong header, a malformed line or no end marker = nothing (start in Default). + public static bool TryParse(string? text, out MetaResumeState state) + { + state = new MetaResumeState(); + if (string.IsNullOrEmpty(text)) return false; + string[] lines = text.Replace("\r", "").Split('\n'); + if (lines.Length == 0 || lines[0] != Header) return false; + var s = state; + bool end = false; + try + { + for (int i = 1; i < lines.Length; i++) + { + string line = lines[i]; + if (line.Length == 0) continue; + int eq = line.IndexOf('='); + if (eq <= 0) return false; + string key = line[..eq], v = line[(eq + 1)..]; + switch (key) + { + case "pid": s.ProcessId = int.Parse(v, Ic); break; + case "pstart": s.ProcessStartUtcTicks = long.Parse(v, Ic); break; + case "char": s.CharacterId = uint.Parse(v, Ic); break; + case "saved": s.SavedUtcTicks = long.Parse(v, Ic); break; + case "meta": s.MetaPath = Un(v); break; + case "sig": s.RulesSignature = Un(v); break; + case "running": s.MacroRunning = v == "1"; break; + case "state": s.State = Un(v); break; + case "entry": s.EntryPending = v == "1"; break; + case "secs": s.SecondsInState = double.Parse(v, Ic); break; + case "psecs": s.SecondsInStateP = double.Parse(v, Ic); break; + case "call": + { + string[] p = v.Split('|'); + if (p.Length != 2) return false; + s.CallStack.Add((Un(p[0]), p[1].Length == 0 ? null : double.Parse(p[1], Ic))); + break; + } + case "fired": + foreach (string n in v.Split(',', StringSplitOptions.RemoveEmptyEntries)) s.FiredRules.Add(int.Parse(n, Ic)); + break; + case "wd": + { + string[] p = v.Split('|'); + if (p.Length != 5) return false; + s.WatchdogActive = p[0] == "1"; + s.WatchdogState = Un(p[1]); + s.WatchdogMeters = float.Parse(p[2], Ic); + s.WatchdogSeconds = double.Parse(p[3], Ic); + s.WatchdogSecondsLeft = double.Parse(p[4], Ic); + break; + } + case "var": + { + int bar = v.IndexOf('|'); + if (bar < 0) return false; + s.Variables[Un(v[..bar])] = Un(v[(bar + 1)..]); + break; + } + case "dict": + { + int bar = v.IndexOf('|'); + if (bar < 0) return false; + var d = new Dictionary(StringComparer.Ordinal); + foreach (string kv in v[(bar + 1)..].Split(',', StringSplitOptions.RemoveEmptyEntries)) + { + int c = kv.IndexOf(':'); + if (c < 0) return false; + d[Un(kv[..c])] = Un(kv[(c + 1)..]); + } + s.Dicts[Un(v[..bar])] = d; + break; + } + case "nextdict": s.NextDictId = int.Parse(v, Ic); break; + case "sw": + { + string[] p = v.Split('|'); + if (p.Length != 3) return false; + double secs = double.Parse(p[1], Ic); + if (!double.IsFinite(secs) || secs < 0) return false; + s.Stopwatches[Un(p[0])] = (secs, p[2] == "1"); + break; + } + case "nextsw": s.NextStopwatchId = int.Parse(v, Ic); break; + case "navpath": s.NavPath = Un(v); break; + case "route": s.RouteLines.Add(Un(v)); break; + case "navindex": s.NavIndex = int.Parse(v, Ic); break; + case "navon": s.NavEnabled = v == "1"; break; + case "end": end = v == "1"; break; + default: break; // a later version's key + } + } + } + catch (FormatException) { return false; } + catch (OverflowException) { return false; } + if (!end || s.SavedUtcTicks < DateTime.MinValue.Ticks || s.SavedUtcTicks > DateTime.MaxValue.Ticks) return false; + if (!double.IsFinite(s.SecondsInState) || !double.IsFinite(s.SecondsInStateP) || !double.IsFinite(s.WatchdogSecondsLeft)) return false; + return true; + } + + /// Why a save can't be resumed, or null when it can: the same client process and character, + /// recent, and the same meta (path and rules) loaded now. + public static string? WhyNot(MetaResumeState s, int processId, long processStartUtcTicks, uint characterId, + string metaPath, string rulesSignature, DateTime nowUtc) + { + if (characterId == 0 || s.CharacterId != characterId) return "another character"; + if (s.ProcessId != processId || s.ProcessStartUtcTicks != processStartUtcTicks) return "another client"; + TimeSpan age = nowUtc - new DateTime(s.SavedUtcTicks, DateTimeKind.Utc); + if (age > MaxAge || age < TimeSpan.FromMinutes(-1)) return $"saved {age.TotalMinutes:0} min ago"; + if (!string.Equals(s.MetaPath ?? "", metaPath ?? "", StringComparison.OrdinalIgnoreCase)) return "another meta is loaded"; + if (s.RulesSignature != rulesSignature) return "the meta's rules changed"; + return null; + } + + // ── Files (TrackerSessionStore's rules: temp file swapped in) ── + + public static void Save(string directory, MetaResumeState s) + { + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, FileName(s.ProcessId, s.CharacterId)); + string tmp = path + ".tmp"; + File.WriteAllText(tmp, Serialize(s)); + File.Move(tmp, path, overwrite: true); + } + + public static bool TryLoad(string directory, int processId, uint characterId, out MetaResumeState state) + { + state = new MetaResumeState(); + string path = Path.Combine(directory, FileName(processId, characterId)); + return File.Exists(path) && TryParse(File.ReadAllText(path), out state); + } + + public static void Delete(string directory, int processId, uint characterId) + { + string path = Path.Combine(directory, FileName(processId, characterId)); + if (File.Exists(path)) File.Delete(path); + } + + /// Files from clients closed more than a day ago. + public static void Cleanup(string directory, DateTime nowUtc) + { + if (!Directory.Exists(directory)) return; + foreach (string path in Directory.GetFiles(directory, "meta-*")) + { + try { if (nowUtc - File.GetLastWriteTimeUtc(path) > TimeSpan.FromDays(1)) File.Delete(path); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } + + private static void Line(StringBuilder sb, string key, string value) => sb.Append(key).Append('=').Append(value).Append('\n'); + + private static string Esc(string? s) => Uri.EscapeDataString(s ?? ""); + + private static string Un(string s) => Uri.UnescapeDataString(s); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/VTankUsdImporter.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/VTankUsdImporter.cs index 2fd8e2a..9e3f13f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/VTankUsdImporter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/VTankUsdImporter.cs @@ -11,7 +11,9 @@ // // per cell: then // Tables we read: MyMonsters (monster rules), weapons/wands/shields/combatitems (weapon -// rules), pets (pet essences), items/itemlist/buffeditems/AssistItems (consumables). +// rules), pets (pet essences), items/itemlist/buffeditems/AssistItems (consumables). Of the +// options after the tables, the two ring ones (MinimumRingTargets, RingDistance: VtRingSettings) +// become Min Ring Targets and Ring Range when the profile has them (2026-11-06). // Object ids are resolved against the current inventory (id first, then name). The // import is previewed first and only applied after a confirm; existing rules with the // same name / id are replaced, everything else is kept. @@ -23,6 +25,7 @@ using System.Linq; using ImGuiNET; using RynthCore.Loot; using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.ProfileImport; using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.MiniRemote; @@ -62,6 +65,7 @@ internal sealed class VTankUsdImporter public List Weapons = new(); public List Consumables = new(); public List Notes = new(); + public VtRingSettings Ring = new(); } private readonly MiniRemoteContext _ctx; @@ -69,6 +73,9 @@ internal sealed class VTankUsdImporter private volatile string _status = string.Empty; private string _pathInput = string.Empty; + /// The last preview / import line (tests read it). + internal string Status => _status; + public VTankUsdImporter(MiniRemoteContext ctx) { _ctx = ctx; @@ -211,7 +218,7 @@ internal sealed class VTankUsdImporter try { lines = File.ReadAllLines(path); } catch (Exception ex) { _status = "Read failed: " + ex.Message; _plan = null; return; } - var plan = new ImportPlan { Path = path }; + var plan = new ImportPlan { Path = path, Ring = VtRingSettings.Read(lines) }; foreach (var t in Parse(lines)) { if (t.Name.Equals("MyMonsters", StringComparison.OrdinalIgnoreCase)) PlanMonsters(t, plan); @@ -221,7 +228,11 @@ internal sealed class VTankUsdImporter } _ctx.State.LastUsdPath = path; _plan = plan; - _status = $"Preview: {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables."; + foreach (string c in plan.Ring.Clamped) plan.Notes.Add($"{c} (the settings' range)"); + var cur = _ctx.Settings; + string ring = cur != null ? plan.Ring.DescribeAgainst(cur) : plan.Ring.Describe(); + _status = $"Preview: {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables" + + (ring.Length > 0 ? $"; ring settings: {ring}." : "; no ring settings in the profile (Min Ring Targets and Ring Range are left alone)."); } private void PlanMonsters(UsdTable t, ImportPlan plan) @@ -294,6 +305,19 @@ internal sealed class VTankUsdImporter } } + /// + /// An imported weapon or shield replaces the saved entries with its id. A shield the player + /// marked "No buff" stays marked: VTank's .usd has no such setting, so a re-import must not + /// quietly turn buffing back on for it (ItemRule.KeepBuffed). + /// + internal static void ReplaceItemRule(List rules, ItemRule imported) + { + if (rules.Exists(r => r.Id == imported.Id && WeaponList.IsShieldRule(r) && r.ExcludedFromBuffing())) + imported.KeepBuffed = false; + rules.RemoveAll(r => r.Id == imported.Id); + rules.Add(imported); + } + /// Writes the previewed rules into the live settings and saves them. public void Apply() { @@ -307,17 +331,18 @@ internal sealed class VTankUsdImporter s.MonsterRules.Add(m); } foreach (var w in plan.Weapons) - { - s.ItemRules.RemoveAll(r => r.Id == w.Id); - s.ItemRules.Add(w); - } + ReplaceItemRule(s.ItemRules, w); foreach (var c in plan.Consumables) { s.ConsumableRules.RemoveAll(r => r.Id == c.Id); s.ConsumableRules.Add(c); } + // The player's own import: the profile's ring options replace these two settings. + plan.Ring.ApplyTo(s); _ctx.SaveCombatSettings?.Invoke(); - _status = $"Imported {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables."; + string ring = plan.Ring.Describe(); + _status = $"Imported {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables" + + (ring.Length > 0 ? $"; set {ring}." : "; ring settings left alone (none in the profile)."); _ctx.Chat("[Mini Remote] " + _status); _plan = null; } @@ -337,6 +362,8 @@ internal sealed class VTankUsdImporter if (plan != null) { ImGui.TextUnformatted($"{plan.Monsters.Count} monster rules, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables"); + string ringLine = plan.Ring.Describe(); + SafeImGui.Text(ringLine.Length > 0 ? "Ring settings: " + ringLine : "Ring settings: none in the profile (left alone)"); if (ImGui.TreeNode("Preview details")) { foreach (var m in plan.Monsters.Take(50)) SafeImGui.BulletText($"Monster {m.Name} [{m.DamageType}] pri {m.Priority}"); @@ -347,7 +374,8 @@ internal sealed class VTankUsdImporter } if (ImGui.Button("Apply import...")) _ctx.Confirm("Import VTank settings", - $"Write these rules into the current RynthAi profile?\nRules with the same monster name / item id are replaced.", + $"Write these rules into the current RynthAi profile?\nRules with the same monster name / item id are replaced." + + (plan.Ring.Any ? $"\nAlso sets {plan.Ring.Describe()}." : ""), Apply, "Import"); } if (_status.Length > 0) SafeImGui.TextWrapped(_status); diff --git a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/CorpseTimer.cs b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/CorpseTimer.cs new file mode 100644 index 0000000..85e3d90 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/CorpseTimer.cs @@ -0,0 +1,75 @@ +// ============================================================================ +// RynthAi - MonsterStats/CorpseTimer.cs +// How long each kind of monster takes to die (2026-11-08, Tom: "the bot is +// running away from a monster it's killed and then turning around and running +// back because there is a second or two for the corpse to show up due to a +// death animation"). ACE creates the corpse once the death animation has +// played, so the time from our kill notice to its "Corpse of " object +// is the death animation's length. +// +// Each credited kill is queued with its time; a corpse object named "Corpse +// of " created within WindowMs is paired with the oldest kill of that +// name still waiting. Pure: every call takes the time (ms), so the tests drive +// it. One thread (the plugin pump). +// ============================================================================ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.MonsterStats; + +internal sealed class CorpseTimer +{ + public const string CorpsePrefix = "Corpse of "; + /// A kill waits this long for its corpse; later, it's no death animation we can time. + public long WindowMs { get; set; } = 8000; + /// Kills kept waiting at most; past it the oldest goes. + public const int MaxWaiting = 32; + + private readonly List<(string Name, long At)> _kills = new(); + + internal int Waiting => _kills.Count; + + /// The monster a corpse's name says ("Corpse of Drudge Skulker" -> "Drudge Skulker"), or null for any other name. + public static string? KilledName(string? corpseName) + { + if (string.IsNullOrEmpty(corpseName) || !corpseName.StartsWith(CorpsePrefix, StringComparison.Ordinal)) return null; + string n = corpseName.Substring(CorpsePrefix.Length).Trim(); + return n.Length > 0 ? n : null; + } + + /// A kill notice credited at . + public void OnKill(string? name, long nowMs) + { + if (string.IsNullOrWhiteSpace(name)) return; + Expire(nowMs); + if (_kills.Count >= MaxWaiting) _kills.RemoveAt(0); + _kills.Add((name.Trim(), nowMs)); + } + + /// + /// An object named was created: when it is the corpse of a kill + /// still waiting, that kill's name and the milliseconds from the kill to the corpse; else null. + /// + public (string Name, long Ms)? OnCorpse(string? corpseName, long nowMs) + { + Expire(nowMs); + string? name = KilledName(corpseName); + if (name == null) return null; + for (int i = 0; i < _kills.Count; i++) + { + if (!_kills[i].Name.Equals(name, StringComparison.OrdinalIgnoreCase)) continue; + long ms = Math.Max(0, nowMs - _kills[i].At); + string killed = _kills[i].Name; + _kills.RemoveAt(i); + return (killed, ms); + } + return null; + } + + public void Reset() => _kills.Clear(); + + private void Expire(long nowMs) + { + while (_kills.Count > 0 && nowMs - _kills[0].At > WindowMs) _kills.RemoveAt(0); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/KillXpMatcher.cs b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/KillXpMatcher.cs new file mode 100644 index 0000000..1fab80c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/KillXpMatcher.cs @@ -0,0 +1,101 @@ +// ============================================================================ +// RynthAi - MonsterStats/KillXpMatcher.cs +// Which kill an experience rise belongs to (2026-11-08, Tom: "The monster tab +// should record how much experience you get for killing x mob"). +// +// The server says nothing that ties XP to a kill: the kill notice names the +// monster, and the player's TotalExperience (quad property 1) goes up a moment +// before or after it. So: each kill notice that credits a monster is queued +// with its time; the plugin hands in TotalExperience every tick; a rise is +// paired with the oldest kill still waiting, one rise per kill. A kill waits +// up to KillWaitSec for its rise; a rise that comes first waits up to +// RiseWaitSec for its kill notice. A rise with no kill (a quest, a fellow's +// kill shared with us, a turn-in) finds none and is dropped. +// +// Pure: every call takes the time, so the tests drive it. One thread (the +// plugin pump). +// ============================================================================ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.MonsterStats; + +/// One kill with the experience it gave. +internal readonly record struct KillXp(string Name, long Xp, DateTime At); + +internal sealed class KillXpMatcher +{ + /// A kill notice waits this long for its experience rise. + public double KillWaitSec { get; set; } = 3.0; + /// A rise that came before its kill notice waits this long for it. + public double RiseWaitSec { get; set; } = 1.0; + /// Kills (and rises) kept waiting at most; past it the oldest goes (a ring spell's ten kills fit). + public const int MaxWaiting = 32; + + private readonly List<(string Name, DateTime At)> _kills = new(); + private readonly List<(long Xp, DateTime At)> _rises = new(); + private long? _lastTotal; + + /// Kills waiting for their rise (tests). + internal int WaitingKills => _kills.Count; + /// Rises waiting for their kill (tests). + internal int WaitingRises => _rises.Count; + + /// A kill notice credited . Returns the kills paired now (a rise that came first). + public IReadOnlyList OnKill(string? name, DateTime now) + { + if (string.IsNullOrWhiteSpace(name)) return Array.Empty(); + if (_kills.Count >= MaxWaiting) _kills.RemoveAt(0); + _kills.Add((name.Trim(), now)); + return Match(now); + } + + /// + /// The player's TotalExperience now. The first value read is the starting point (a login, a + /// reload); a value lower than the last (another character) starts over from it. Returns the + /// kills paired now. + /// + public IReadOnlyList OnTotal(long total, DateTime now) + { + if (_lastTotal is not long last || total < last) + { + _lastTotal = total; + return Match(now); + } + if (total > last) + { + if (_rises.Count >= MaxWaiting) _rises.RemoveAt(0); + _rises.Add((total - last, now)); + _lastTotal = total; + } + return Match(now); + } + + /// A logout: nothing waits on, and the next value read is a new starting point. + public void Reset() + { + _kills.Clear(); + _rises.Clear(); + _lastTotal = null; + } + + private IReadOnlyList Match(DateTime now) + { + List? done = null; + while (_kills.Count > 0 && _rises.Count > 0) + { + var k = _kills[0]; + var r = _rises[0]; + double riseAfterKill = (r.At - k.At).TotalSeconds; + if (riseAfterKill > KillWaitSec) { _kills.RemoveAt(0); continue; } // the kill gave nothing we saw + if (-riseAfterKill > RiseWaitSec) { _rises.RemoveAt(0); continue; } // the rise was no kill's + _kills.RemoveAt(0); + _rises.RemoveAt(0); + (done ??= new List()).Add(new KillXp(k.Name, r.Xp, k.At > r.At ? k.At : r.At)); + } + // What waited too long goes: a kill with no rise (a kill worth nothing), a rise with no kill (a quest). + while (_kills.Count > 0 && (now - _kills[0].At).TotalSeconds > KillWaitSec) _kills.RemoveAt(0); + while (_rises.Count > 0 && (now - _rises[0].At).TotalSeconds > RiseWaitSec) _rises.RemoveAt(0); + return done ?? (IReadOnlyList)Array.Empty(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterCombatStats.cs b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterCombatStats.cs index 62ab7f2..827486e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterCombatStats.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterCombatStats.cs @@ -10,6 +10,10 @@ // = landed + resisted + no effect; damage taken. // Rates it evades (its evades / your swings), it resists (its // resists / your spells), you evade, you resist. +// Experience (2026-11-08) the XP of the kills whose rise was seen +// (KillXpMatcher) and how many: XP per kill. +// Death (2026-11-08) the time from each kill to its corpse (the +// death animation; CorpseTimer), summed, and how many. // // Fed by CombatEvents (typed melee/missile events), CombatLines (spell lines) // and the kill notice; shown under each monster in the Damage panel (the row's @@ -40,8 +44,15 @@ internal sealed record MonsterStatsRow( string Name, int Hits, int Evaded, int SpellsLanded, int Resisted, int NoEffect, int Kills, long DamageDealt, int HitsTaken, int YouEvaded, int SpellsTaken, int YouResisted, int NoEffectOnYou, long DamageTaken, - long FirstUtcTicks, long LastUtcTicks) + long FirstUtcTicks, long LastUtcTicks, + long Xp = 0, int XpKills = 0, + long CorpseMs = 0, int CorpseKills = 0) { + /// The experience per kill, over the kills whose XP was seen (KillXpMatcher), or null. + public double? XpPerKill => XpKills > 0 ? (double)Xp / XpKills : null; + /// The time from the kill to its corpse (the death animation), on average in ms, or null (CorpseTimer). + public double? CorpseAvgMs => CorpseKills > 0 ? (double)CorpseMs / CorpseKills : null; + /// Your melee and missile attacks at it: hits and the ones it evaded. public int Swings => Hits + Evaded; /// Your spells that reached it. @@ -73,9 +84,14 @@ internal sealed class MonsterCombatStats public int HitsTaken, YouEvaded, SpellsTaken, YouResisted, NoEffectOnYou; public long DamageTaken; public long FirstUtcTicks, LastUtcTicks; + public long Xp; // experience from the kills whose rise was seen (2026-11-08) + public int XpKills; // those kills + public long CorpseMs; // kill notice to corpse, summed (the death animation, 2026-11-08) + public int CorpseKills; // the kills whose corpse was timed public MonsterStatsRow ToRow() => new(Name, Hits, Evaded, SpellsLanded, Resisted, NoEffect, Kills, DamageDealt, - HitsTaken, YouEvaded, SpellsTaken, YouResisted, NoEffectOnYou, DamageTaken, FirstUtcTicks, LastUtcTicks); + HitsTaken, YouEvaded, SpellsTaken, YouResisted, NoEffectOnYou, DamageTaken, FirstUtcTicks, LastUtcTicks, Xp, XpKills, + CorpseMs, CorpseKills); } private readonly Dictionary _byName = new(StringComparer.OrdinalIgnoreCase); @@ -173,6 +189,32 @@ internal sealed class MonsterCombatStats return e.Name; } + /// + /// A kill of gave (KillXpMatcher paired the rise with + /// its kill notice): added to its XP and its kills with XP counted. Kills whose rise wasn't seen + /// stay out of both, so XP/kill is never diluted by them. + /// + public void OnKillXp(string? name, long xp, DateTime nowUtc) + { + if (xp <= 0) return; + Entry? e = Touch(name, nowUtc); + if (e == null) return; + e.Xp += xp; + e.XpKills++; + Version++; + } + + /// A kill of left its corpse after the kill notice (CorpseTimer). + public void OnCorpseTime(string? name, long ms, DateTime nowUtc) + { + if (ms < 0) return; + Entry? e = Touch(name, nowUtc); + if (e == null) return; + e.CorpseMs += ms; + e.CorpseKills++; + Version++; + } + private string? LongestNameIn(string notice) { string? best = null; @@ -252,6 +294,8 @@ internal sealed class MonsterCombatStats SpellsTaken = Math.Max(0, r.SpellsTaken), YouResisted = Math.Max(0, r.YouResisted), NoEffectOnYou = Math.Max(0, r.NoEffectOnYou), DamageTaken = Math.Max(0, r.DamageTaken), FirstUtcTicks = r.FirstUtcTicks, LastUtcTicks = r.LastUtcTicks, + Xp = Math.Max(0, r.Xp), XpKills = Math.Max(0, r.XpKills), + CorpseMs = Math.Max(0, r.CorpseMs), CorpseKills = Math.Max(0, r.CorpseKills), }; if (_byName.Count >= MaxMonsters) break; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterStatsStore.cs b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterStatsStore.cs index c1bef44..5971bb9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterStatsStore.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterStatsStore.cs @@ -45,6 +45,11 @@ internal static class MonsterStatsStore private const string FilePrefix = "monsters-"; private const string FileSuffix = ".txt"; private const int Fields = 16; // the name and 15 numbers + // 2026-11-08: two more at the end, XP and kills with XP counted. The header stays v2: an older + // copy reads the first 16 and leaves the rest, and a row from an older save has XP 0. + private const int FieldsWithXp = 18; + // Then two more (same day): the kill-to-corpse ms summed and how many (the death animation). + private const int FieldsWithCorpse = 20; private static readonly CultureInfo Ic = CultureInfo.InvariantCulture; @@ -73,7 +78,7 @@ internal static class MonsterStatsStore { r.Hits, r.Evaded, r.SpellsLanded, r.Resisted, r.NoEffect, r.Kills, r.DamageDealt, r.HitsTaken, r.YouEvaded, r.SpellsTaken, r.YouResisted, r.NoEffectOnYou, r.DamageTaken, - r.FirstUtcTicks, r.LastUtcTicks, + r.FirstUtcTicks, r.LastUtcTicks, r.Xp, r.XpKills, r.CorpseMs, r.CorpseKills, }) sb.Append('\t').Append(v.ToString(Ic)); sb.Append('\n'); @@ -134,10 +139,22 @@ internal static class MonsterStatsStore for (int i = 0; i < 13; i++) if (i != 6 && i != 12 && n[i] > int.MaxValue) return false; // counts are ints; damage is long if (!ValidTicks(n[13]) || !ValidTicks(n[14])) return false; + long xp = 0, xpKills = 0; + if (f.Length >= FieldsWithXp) + { + if (!long.TryParse(f[16], NumberStyles.None, Ic, out xp) || !long.TryParse(f[17], NumberStyles.None, Ic, out xpKills) + || xpKills > int.MaxValue) return false; + } + long corpseMs = 0, corpseKills = 0; + if (f.Length >= FieldsWithCorpse) + { + if (!long.TryParse(f[18], NumberStyles.None, Ic, out corpseMs) || !long.TryParse(f[19], NumberStyles.None, Ic, out corpseKills) + || corpseKills > int.MaxValue) return false; + } row = new MonsterStatsRow(f[0].Trim(), (int)n[0], (int)n[1], (int)n[2], (int)n[3], (int)n[4], (int)n[5], n[6], (int)n[7], (int)n[8], (int)n[9], (int)n[10], (int)n[11], n[12], - n[13], n[14]); + n[13], n[14], xp, (int)xpKills, corpseMs, (int)corpseKills); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterStatsWindow.cs b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterStatsWindow.cs index 5523a43..f18a30a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterStatsWindow.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterStatsWindow.cs @@ -54,7 +54,9 @@ internal sealed class MonsterStatsWindow "It evades: of your melee and missile attacks, the share it evaded.\n" + "It resists: of your spells that reached it, the share it resisted.\n" + "You evade: of its melee and missile attacks, the share you evaded.\n" + - "You resist: of its spells that reached you, the share you resisted.\n\n" + + "You resist: of its spells that reached you, the share you resisted.\n" + + "XP/kill: the experience a kill gave you, on average (a kill counts when your XP rose within a few seconds of it).\n" + + "Click a monster for its death too: how long after the kill its corpse came (the death animation; looting waits that long).\n\n" + "Click a monster for its numbers both ways: attacks and hits, spells and how many landed, " + "spells that could do nothing to it (immune), damage and kills. The killing blow counts as a hit " + "(melee or missile) or a landed spell (magic).\n\n" + @@ -72,7 +74,7 @@ internal sealed class MonsterStatsWindow _k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f); Vector2 origin = ImGui.GetCursorScreenPos(); Vector2 size = ImGui.GetContentRegionAvail(); - var want = new Vector2(Px(560), Px(360)); + var want = new Vector2(Px(620), Px(360)); // 620 since the XP/kill column (2026-11-08) if (size.X < 60 || size.Y < 40) return want; ImDrawListPtr frame = ImGui.GetWindowDrawList(); frame.AddRectFilled(origin, origin + size, Background, 4); @@ -168,6 +170,7 @@ internal sealed class MonsterStatsWindow ("It resists", "Of your spells that reached it, the share it resisted."), ("You evade", "Of its melee and missile attacks, the share you evaded."), ("You resist", "Of its spells that reached you, the share you resisted."), + ("XP/kill", "The experience a kill gave, on average (the kills whose XP was seen since login)."), }; private float ColW => Px(66); @@ -256,6 +259,7 @@ internal sealed class MonsterStatsWindow MonsterCombatStats.Percent(r.ItResistsRate), MonsterCombatStats.Percent(r.YouEvadeRate), MonsterCombatStats.Percent(r.YouResistRate), + MonsterStatsText.XpCell(r), }; for (int c = 0; c < cells.Length; c++) { @@ -281,6 +285,7 @@ internal sealed class MonsterStatsWindow 2 => $"It resisted {r.Resisted:N0} of your {r.SpellsAtIt:N0} spells that reached it.", 3 => $"You evaded {r.YouEvaded:N0} of its {r.Attacks:N0} melee and missile attacks.", 4 => $"You resisted {r.YouResisted:N0} of its {r.SpellsAtYou:N0} spells that reached you.", + 5 => r.XpKills > 0 ? $"{r.Xp:N0} XP from {r.XpKills:N0} {(r.XpKills == 1 ? "kill" : "kills")} whose XP was seen." : "No kill's XP seen yet.", _ => null, }; @@ -347,13 +352,32 @@ internal static class MonsterStatsText rows.Add(("No effect", $"{N(r.NoEffect)} (it is immune)", $"{N(r.NoEffectOnYou)} (you are immune)")); rows.Add(("Damage", $"{N(r.DamageDealt)} dealt", $"{N(r.DamageTaken)} taken")); rows.Add(("Kills", N(r.Kills), string.Empty)); + if (r.XpKills > 0) rows.Add(("XP", $"XP/kill {N(XpPerKill(r))} ({N(r.Xp)} from {N(r.XpKills)} {(r.XpKills == 1 ? "kill" : "kills")})", string.Empty)); + if (r.CorpseKills > 0) rows.Add(("Death", $"corpse after {Seconds(r)} ({N(r.CorpseKills)} timed)", string.Empty)); return rows; } + /// "2.1 s": the average kill-to-corpse time. + private static string Seconds(MonsterStatsRow r) + => ((r.CorpseAvgMs ?? 0) / 1000.0).ToString("0.0", CultureInfo.InvariantCulture) + " s"; + + /// ", corpse after 2.1 s" for the chat lines, or "" before any corpse was timed. + private static string CorpseText(MonsterStatsRow r) => r.CorpseKills > 0 ? $", corpse after {Seconds(r)}" : string.Empty; + + /// The average XP per kill, whole. + private static long XpPerKill(MonsterStatsRow r) => r.XpPerKill is double x ? (long)Math.Round(x, MidpointRounding.AwayFromZero) : 0; + + /// The window's XP/kill cell: "1,234,567", or "-" before any kill's XP was seen. + public static string XpCell(MonsterStatsRow r) => r.XpKills > 0 ? N(XpPerKill(r)) : "-"; + + /// ", XP/kill 1,234,567" for the chat lines, or "" before any kill's XP was seen. + private static string XpText(MonsterStatsRow r) => r.XpKills > 0 ? $", XP/kill {N(XpPerKill(r))}" : string.Empty; + /// /ra mstats's answer: a title line, then your side and its side (three chat lines). public static string[] ChatLines(MonsterStatsRow r) => new[] { - $"[RynthAi] {r.Name} since login: {N(r.Kills)} {(r.Kills == 1 ? "kill" : "kills")}.", + $"[RynthAi] {r.Name} since login: {N(r.Kills)} {(r.Kills == 1 ? "kill" : "kills")}" + + (r.XpKills > 0 ? $"{XpText(r)} ({N(r.Xp)} XP from {N(r.XpKills)})" : string.Empty) + CorpseText(r) + ".", $"[RynthAi] You at it: {N(r.Swings)} swings, {N(r.Hits)} hit, it evaded {N(r.Evaded)} ({MonsterCombatStats.Percent(r.ItEvadesRate)}); " + $"{N(r.SpellsAtIt)} spells reached it, it resisted {N(r.Resisted)} ({MonsterCombatStats.Percent(r.ItResistsRate)})" + (r.NoEffect > 0 ? $", {N(r.NoEffect)} no effect" : string.Empty) @@ -368,5 +392,5 @@ internal static class MonsterStatsText public static string ListLine(MonsterStatsRow r) => $"[RynthAi] {r.Name}: {N(r.Kills)} {(r.Kills == 1 ? "kill" : "kills")}, it evades {MonsterCombatStats.Percent(r.ItEvadesRate)}, " + $"resists {MonsterCombatStats.Percent(r.ItResistsRate)}; you evade {MonsterCombatStats.Percent(r.YouEvadeRate)}, " - + $"resist {MonsterCombatStats.Percent(r.YouResistRate)}"; + + $"resist {MonsterCombatStats.Percent(r.YouResistRate)}{XpText(r)}{CorpseText(r)}"; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterXpTable.cs b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterXpTable.cs new file mode 100644 index 0000000..44498ad --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MonsterStats/MonsterXpTable.cs @@ -0,0 +1,233 @@ +// ============================================================================ +// RynthAi - MonsterStats/MonsterXpTable.cs +// What a kill of each kind of monster gives and takes, learned and kept across +// logins (2026-11-08): the experience per kill (the Outdoor Hunt's "Most XP" +// choice reads it) and the time from the kill to its corpse, the death +// animation (looting waits that long before moving on). The session's monster +// stats start over at every login; this doesn't. +// +// Per character, next to the character's settings and monster_damage.txt: +// ...\SettingsProfiles\\\monster_xp.txt +// one line per monster and number: +// X|name|xpPerKill|kills D|name|deathMs|kills +// Each average is over the last AverageOver kills (a running average: the +// first kills count fully, then each new one moves it by 1/AverageOver), so a +// level's XP change or a server's bonus weekend shows within a few dozen kills. +// Plain text, no System.Text.Json (plugin types and STJ leak across reloads). +// +// Pump thread writes; the hunt and the looter read on the pump thread too; a +// lock anyway. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; + +namespace RynthCore.Plugin.RynthAi.MonsterStats; + +internal sealed class MonsterXpTable +{ + public const string FileName = "monster_xp.txt"; + /// The averages follow about this many of the latest kills. + public const int AverageOver = 20; + /// Kinds of monster kept; past it the one with the fewest kills goes. + public const int MaxMonsters = 2000; + + private sealed class Entry + { + public string Name = ""; + public double Avg; // XP per kill + public int Kills; // kills with XP counted + public double DeathAvg; // ms from the kill to its corpse + public int DeathKills; // kills whose corpse was timed + } + + private static readonly CultureInfo Ic = CultureInfo.InvariantCulture; + private readonly object _lock = new(); + private readonly Dictionary _byName = new(StringComparer.OrdinalIgnoreCase); + private string _path = string.Empty; + private bool _dirty; + + /// The file it reads and writes ("" while no character is set). + public string FilePath { get { lock (_lock) return _path; } } + + /// Kinds of monster known. + public int Count { get { lock (_lock) return _byName.Count; } } + + /// Points the table at a character's folder and loads its file ("" detaches it, empty). + public void SetCharacter(string? charFolder) + { + lock (_lock) + { + _byName.Clear(); + _dirty = false; + _path = string.IsNullOrWhiteSpace(charFolder) ? string.Empty : Path.Combine(charFolder, FileName); + if (_path.Length == 0 || !File.Exists(_path)) return; + try { Parse(File.ReadAllText(_path)); } + catch { _byName.Clear(); } // unreadable: start fresh, the next save rewrites it + } + } + + /// One kill of gave . + public void Record(string? name, long xp) + { + if (xp <= 0) return; + lock (_lock) + { + if (EntryFor(name) is not Entry e) return; + e.Kills++; + e.Avg += (xp - e.Avg) / Math.Min(e.Kills, AverageOver); + _dirty = true; + } + } + + /// One kill of left its corpse after the kill notice. + public void RecordDeath(string? name, long ms) + { + if (ms < 0) return; + lock (_lock) + { + if (EntryFor(name) is not Entry e) return; + e.DeathKills++; + e.DeathAvg += (ms - e.DeathAvg) / Math.Min(e.DeathKills, AverageOver); + _dirty = true; + } + } + + /// The learned experience per kill of , or null when none is known. + public double? XpPerKill(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return null; + lock (_lock) + return _byName.TryGetValue(name.Trim(), out Entry? e) && e.Kills > 0 ? e.Avg : null; + } + + /// Kills behind (0 when unknown). + public int KillsCounted(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return 0; + lock (_lock) + return _byName.TryGetValue(name.Trim(), out Entry? e) ? e.Kills : 0; + } + + /// The learned time from a kill of to its corpse (ms), or null when none is known. + public double? DeathMs(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return null; + lock (_lock) + return _byName.TryGetValue(name.Trim(), out Entry? e) && e.DeathKills > 0 ? e.DeathAvg : null; + } + + /// Kills behind (0 when unknown). + public int DeathsTimed(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return 0; + lock (_lock) + return _byName.TryGetValue(name.Trim(), out Entry? e) ? e.DeathKills : 0; + } + + /// Writes the file when something changed. Cheap to call from a tick. + public void SaveIfDirty() + { + string text, path; + lock (_lock) + { + if (!_dirty || _path.Length == 0) return; + _dirty = false; + text = Serialize(); + path = _path; + } + try + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + string tmp = path + ".tmp"; + File.WriteAllText(tmp, text); + File.Move(tmp, path, overwrite: true); + } + catch + { + lock (_lock) _dirty = true; // tried again at the next save + } + } + + // ── Format ─────────────────────────────────────────────────────────── + + internal string Serialize() + { + var sb = new StringBuilder(128 + _byName.Count * 60); + sb.Append("# RynthAi per monster, learned from your kills (auto-generated); averages over the last ") + .Append(AverageOver.ToString(Ic)).Append(" kills.\n"); + sb.Append("# X|name|xpPerKill|kills counted\n"); + sb.Append("# D|name|ms from the kill to its corpse (the death animation)|kills timed\n"); + var names = new List(_byName.Keys); + names.Sort(StringComparer.OrdinalIgnoreCase); + foreach (string k in names) + { + Entry e = _byName[k]; + if (e.Kills > 0) + sb.Append("X|").Append(e.Name).Append('|').Append(e.Avg.ToString("0.##", Ic)).Append('|').Append(e.Kills.ToString(Ic)).Append('\n'); + if (e.DeathKills > 0) + sb.Append("D|").Append(e.Name).Append('|').Append(e.DeathAvg.ToString("0", Ic)).Append('|').Append(e.DeathKills.ToString(Ic)).Append('\n'); + } + return sb.ToString(); + } + + /// Reads the lines it knows; anything else (a comment, a later version's line, a bad number) is skipped. + private void Parse(string text) + { + foreach (string raw in text.Replace("\r", "").Split('\n')) + { + string line = raw.Trim(); + if (line.Length == 0 || line[0] == '#') continue; + string[] f = line.Split('|'); + if (f.Length < 4 || (f[0] != "X" && f[0] != "D")) continue; + string n = Clean(f[1]); + if (n.Length == 0) continue; + if (!double.TryParse(f[2], NumberStyles.Float, Ic, out double avg) || !double.IsFinite(avg) || avg < 0) continue; + if (!int.TryParse(f[3], NumberStyles.None, Ic, out int kills) || kills <= 0) continue; + if (!_byName.TryGetValue(n, out Entry? e)) + { + if (_byName.Count >= MaxMonsters) continue; + e = new Entry { Name = n }; + _byName[n] = e; + } + if (f[0] == "X" && e.Kills == 0 && avg > 0) { e.Avg = avg; e.Kills = kills; } + else if (f[0] == "D" && e.DeathKills == 0) { e.DeathAvg = avg; e.DeathKills = kills; } + } + // A name whose every line was bad leaves nothing. + var empty = new List(); + foreach (var kv in _byName) if (kv.Value.Kills == 0 && kv.Value.DeathKills == 0) empty.Add(kv.Key); + foreach (string k in empty) _byName.Remove(k); + } + + /// The monster's entry (made on first sight); null for no name. Caller holds _lock. + private Entry? EntryFor(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return null; + string n = Clean(name); + if (n.Length == 0) return null; + if (!_byName.TryGetValue(n, out Entry? e)) + { + if (_byName.Count >= MaxMonsters) DropFewest(); + e = new Entry { Name = n }; + _byName[n] = e; + } + return e; + } + + private void DropFewest() + { + string? fewest = null; + int k = int.MaxValue; + foreach (Entry e in _byName.Values) + if (e.Kills + e.DeathKills < k) { k = e.Kills + e.DeathKills; fewest = e.Name; } + if (fewest != null) _byName.Remove(fewest); + } + + private static string Clean(string name) + { + string n = name.Replace('|', '/').Replace('\r', ' ').Replace('\n', ' ').Trim(); + return n.Length > 64 ? n.Substring(0, 64) : n; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs b/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs index ed3268b..a0f1d0a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs @@ -74,7 +74,7 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner // Area check: dungeon cells can sit outside their landblock's 192-unit square, so a // waypoint that maps to a neighbouring landblock still counts as "in this dungeon" // when it is this close to one of its cells. - private const double AreaCellReachYd = 60.0; + internal const double AreaCellReachYd = 60.0; private const int MaxNavmeshCorners = 128; private readonly RynthCoreHost _host; @@ -333,7 +333,7 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner return result; } - private static bool ComputeIsDungeon(uint lb, DatDatabase cellDat) + internal static bool ComputeIsDungeon(uint lb, DatDatabase cellDat) { try { diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index 2c1b872..7069216 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -416,13 +416,18 @@ internal sealed class NavigationEngine } if (!_hasStopped) { - ClearTurnMotions(); + // The macro switched off with nav idle (no route, between routes): the character may be + // the player's, running by hand, and is left running (the owner, 2026-11-07). Nav's own + // movement is still stopped. + bool navMoving = _isMovingForward || _isTurning || _tier1TurnDir != 0; + bool sendStops = _settings.IsMacroRunning || navMoving; + if (sendStops) ClearTurnMotions(); if (_stopRequestedAt == long.MaxValue) _stopRequestedAt = Now; if (Now - _stopRequestedAt >= (long)StopDebounceMs) { - _host.SetAutoRunBy("Nav", false); + if (sendStops) _host.SetAutoRunBy("Nav", false); _isMovingForward = false; _isTurning = false; _hasStopped = true; @@ -466,20 +471,27 @@ internal sealed class NavigationEngine // so a new route doesn't inherit the old route's pause/portal/stuck progress. if (!ReferenceEquals(route, _lastRoute)) { + // Outdoor Hunt plans its walk again every 8 s: that is the same walk, not a new route. + // Resetting here kept a character pinned at a wall on the first rung of the stuck ladder + // (a jump) for good: no count ever built up, so no detour was ever tried (2026-11-06). + bool sameWalk = route.OutdoorHuntWalk && _lastRoute?.OutdoorHuntWalk == true; _lastRoute = route; _inPause = false; _closestDist = double.MaxValue; _linearDir = 1; - _watchdogNs = double.NaN; - _watchdogEw = double.NaN; - _stuckCount = 0; - _inRecovery = false; + if (!sameWalk) + { + _watchdogNs = double.NaN; + _watchdogEw = double.NaN; + _stuckCount = 0; + _inRecovery = false; + } _hasGoodHeading = false; // The loader chose the new route's start index; a pause on the old route says nothing. ClearPausePosition(); ResetPortalState(); - ResetRecovery("the route changed"); - _host.Log($"Nav: route swap detected, {route.Points.Count} pts, startIdx={_settings.ActiveNavIndex}"); + if (!sameWalk) ResetRecovery("the route changed"); + _host.Log($"Nav: route swap detected, {route.Points.Count} pts, startIdx={_settings.ActiveNavIndex}{(sameWalk ? " (the same hunt walk: the stuck count carries on)" : "")}"); } // STEP 5: the self-promote from "Default" to "Navigating" is gone. Tick() diff --git a/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs index 757468a..edbbfa5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs @@ -16,7 +16,8 @@ namespace RynthCore.Plugin.RynthAi; /// in a straight line. A monster with no walkable way to it (on a cliff, in water, inside a closed /// building) is left out for . Monsters are looked for out to /// (Hunt Range); (Hunt Radius) keeps the picks within that far of where it started -/// (0 = anywhere). With nothing in range it waits where it is. +/// (0 = anywhere). With nothing in range it waits where it is. That is ; +/// since 2026-11-08 the setting can go for the biggest pack or the most experience instead (PickPack). /// /// Buildings (2026-10-25, Tom: "the entire radar range, also going inside houses"): RynthNav's map ends /// at a building's walls, so a walk into one is RynthNav's way to the outside of one of its doors, then @@ -128,6 +129,35 @@ internal sealed class OutdoorHunt /// public double NoFightSec { get; set; } = 2; + /// + /// What the next monster is chosen by (2026-11-08, Tom: "it should be a setting to go for nearest + /// spawn or most dense or highest experience", and "right now it does circles when only 1 mob has + /// respawned"): the setting OutdoorHuntPick, 0 / 1 / 2. + /// + internal enum PickMode + { + /// The shortest walk among the nearest few (the hunt as it was before the setting). + Nearest = 0, + /// The biggest pack: the monsters within of each other, counted. + Pack = 1, + /// The pack worth the most experience (the learned XP per kill, ). + Xp = 2, + } + + public PickMode Pick { get; set; } = PickMode.Nearest; + /// Monsters this close to a monster are in its pack. + public double PackYd { get; set; } = 20; + /// + /// A pack's worth is divided by (1 + its walk / this): a pack this far away counts half, twice as far + /// a third, so a near pack wins unless a farther one is clearly bigger (a 5-pack 80 yd off beats a + /// lone monster 10 yd off; a 3-pack 180 yd off doesn't). + /// + public double PackFarYd { get; set; } = 60; + /// Most monsters looked at for packs (nearest first): the pack count is every pair. + public const int MaxPackCandidates = 300; + /// The learned XP per kill of a monster by name (null: not known), for . + public Func? XpLookup { get; set; } + public bool Active { get; private set; } public Vec Anchor { get; private set; } public int TargetId { get; private set; } @@ -254,6 +284,7 @@ internal sealed class OutdoorHunt if ((now - _lastPick).TotalSeconds < PickEverySec) return new Decision(Act.Idle); _lastPick = now; + if (Pick != PickMode.Nearest) return PickPack(now, me, meCell, candidates); _viable.Clear(); int asked = 0; foreach (var c in candidates) @@ -280,25 +311,156 @@ internal sealed class OutdoorHunt var v = _viable[i]; if (v.C.Priority > best.C.Priority || (v.C.Priority == best.C.Priority && v.W.P.Length < best.W.P.Length)) best = v; } - TargetId = best.C.Id; - _plannedTo = best.C.Pos; - _lastPlan = now; - Note = NextNote(best.C, best.W); - if (best.W.P.Length > ArrivedYd) - { - _arrivedSince = DateTime.MinValue; - return new Decision(Act.Walk, best.W.P.Corners, best.C.Id, Note); - } - _arrivedSince = now; // it's right here and combat hasn't taken it: NoFightSec, then left out - return new Decision(Act.Idle, TargetId: best.C.Id, Why: Note); + return Go(now, best.C, best.W); } + return Waiting(); + } - // Nothing to hunt: wait where it is (no walk back to the start: Tom 10-23, "it shouldn't bother"). + /// The chosen monster becomes the target: walked to, or stood by when the walk's end is already here. + private Decision Go(DateTime now, Candidate c, HuntWalk w, string pack = "") + { + TargetId = c.Id; + _plannedTo = c.Pos; + _lastPlan = now; + Note = NextNote(c, w, pack); + if (w.P.Length > ArrivedYd) + { + _arrivedSince = DateTime.MinValue; + return new Decision(Act.Walk, w.P.Corners, c.Id, Note); + } + _arrivedSince = now; // it's right here and combat hasn't taken it: NoFightSec, then left out + return new Decision(Act.Idle, TargetId: c.Id, Why: Note); + } + + /// Nothing to hunt: wait where it is (no walk back to the start: Tom 10-23, "it shouldn't bother"). + private Decision Waiting() + { string wait = $"nothing within Hunt Range ({RangeYd:0} yd){(RadiusYd > 0 ? $" inside Hunt Radius ({RadiusYd:0} yd)" : "")}: waiting here"; if (_note != wait) Note = wait; return new Decision(Act.Idle); } + // ── Biggest pack / Most XP (2026-11-08) ──────────────────────────────────────────────────────── + // Every monster that could be chosen has a pack: itself and the others within PackYd of it. Its + // worth is the pack's count (Biggest pack) or the sum of the pack's XP per kill (Most XP: a name + // with no XP learned counts as the average of the known ones here, or 1 when none is known, so + // it falls back to Biggest pack). Score = worth / (1 + walk / PackFarYd). A higher Priority in the + // pack still comes first. The packs are ranked by the straight line first, paths are asked only + // for the top PickCandidates, and those are scored again by the real walk; the target is the + // pack's member with the shortest walk. + + private readonly List _eligible = new(); + + private Decision PickPack(DateTime now, Vec me, uint meCell, IReadOnlyList candidates) + { + _eligible.Clear(); + foreach (var c in candidates) + { + if (c.Distance > RangeYd) break; // nearest first + if (!InArea(c.Pos) || IsSkipped(c.Id, now) || !Plannable(c)) continue; + _eligible.Add(c); + if (_eligible.Count >= MaxPackCandidates) break; + } + int n = _eligible.Count; + if (n == 0) return Waiting(); + + // Each monster's worth: 1, or its XP per kill. + var worth = new double[n]; + bool xpKnown = false; + if (Pick == PickMode.Xp && XpLookup != null) + { + double sum = 0; + int known = 0; + for (int i = 0; i < n; i++) + { + double? x = XpLookup(_eligible[i].Name); + if (x is double v && double.IsFinite(v) && v > 0) { worth[i] = v; sum += v; known++; } + else worth[i] = -1; + } + xpKnown = known > 0; + double unknown = known > 0 ? sum / known : 1; + for (int i = 0; i < n; i++) if (worth[i] < 0) worth[i] = unknown; + } + else + for (int i = 0; i < n; i++) worth[i] = 1; + + // Each monster's pack: its worth, its size, its highest Priority. + var packWorth = new double[n]; + var packCount = new int[n]; + var packPri = new int[n]; + for (int i = 0; i < n; i++) + { + int pri = int.MinValue; + for (int j = 0; j < n; j++) + { + if (i != j && _eligible[i].Pos.DistanceTo(_eligible[j].Pos) > PackYd) continue; + packWorth[i] += worth[j]; + packCount[i]++; + if (_eligible[j].Priority > pri) pri = _eligible[j].Priority; + } + packPri[i] = pri; + } + + // Ranked by the straight line; paths for the top few only. + var order = new List(n); + for (int i = 0; i < n; i++) order.Add(i); + var straight = new double[n]; + for (int i = 0; i < n; i++) straight[i] = packWorth[i] / (1 + _eligible[i].Distance / PackFarYd); + order.Sort((a, b) => + { + if (packPri[a] != packPri[b]) return packPri[b].CompareTo(packPri[a]); + int s = straight[b].CompareTo(straight[a]); + return s != 0 ? s : _eligible[a].Distance.CompareTo(_eligible[b].Distance); + }); + + var walks = new Dictionary(); // eligible index -> its walk (the ones that reach it) + int asked = 0; + foreach (int i in order) + { + if (asked >= PickCandidates) break; + asked++; + var c = _eligible[i]; + var w = PlanWalk(me, meCell, c.Pos, c.Cell); + if (w.P.Status == PathStatus.Unavailable) return new Decision(Act.Idle, Why: "no pathfinder"); + if (Reaches(w.P)) walks[i] = w; + else + { + Skip(c.Id, now); + Note = $"'{c.Name}' left out for {SkipSec:0} s: {Describe(w.P, w.Why)}"; + } + } + if (walks.Count == 0) return Waiting(); + + // Scored again by the real walk. + int best = -1; + double bestScore = 0; + foreach (var (i, w) in walks) + { + double score = packWorth[i] / (1 + w.P.Length / PackFarYd); + if (best < 0 || packPri[i] > packPri[best] + || (packPri[i] == packPri[best] && (score > bestScore || (score == bestScore && w.P.Length < walks[best].P.Length)))) + { + best = i; + bestScore = score; + } + } + + // The target: the pack's member with the highest Priority, then the shortest walk (best itself if no other was planned). + int target = best; + foreach (var (i, w) in walks) + { + if (i != best && _eligible[i].Pos.DistanceTo(_eligible[best].Pos) > PackYd) continue; + var t = _eligible[target]; + var c = _eligible[i]; + if (c.Priority > t.Priority || (c.Priority == t.Priority && w.P.Length < walks[target].P.Length)) target = i; + } + + int count = packCount[best]; + string pack = count == 1 ? ", on its own" : $", pack of {count}"; + if (Pick == PickMode.Xp) pack += xpKnown ? $" ({packWorth[best]:N0} XP)" : " (no XP learned yet: by size)"; + return Go(now, _eligible[target], walks[target], pack); + } + // ── Indoors ────────────────────────────────────────────────────────────────────────────────── // A building's rooms are off RynthNav's landscape map: it plans no walk from in there, and every // monster came back "not on the map" (a test hunt 10-23, after combat chased one inside: the hunt left @@ -425,19 +587,21 @@ internal sealed class OutdoorHunt return b != 0 && (b == _meBuilding || _buildings!.Doors(b).Count > 0); } - private string NextNote(Candidate c, HuntWalk w) + /// The log line for the choice; (Biggest pack, Most XP): ", pack of 5 (4,200,000 XP)" after the name. + private string NextNote(Candidate c, HuntWalk w, string pack = "") { var b = _buildings; string len = $"a {w.P.Length:0} yd walk"; string away = $"({c.Distance:0} yd away)"; + string next = $"next: '{c.Name}'{pack}"; static string At(Door d) => $"{d.At.X:0},{d.At.Y:0}"; - if (b == null || (w.From == 0 && w.To == 0)) return $"next: '{c.Name}', {len} {away}"; + if (b == null || (w.From == 0 && w.To == 0)) return $"{next}, {len} {away}"; if (w.Out is Door o && w.In is Door i) - return $"next: '{c.Name}', inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} out of {b.Name(w.From)} through the door at {At(o)}, " + return $"{next}, inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} out of {b.Name(w.From)} through the door at {At(o)}, " + $"then in through the door at {At(i)} {away}"; - if (w.In is Door din) return $"next: '{c.Name}', inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} through the door at {At(din)} {away}"; - if (w.Out is Door dout) return $"next: '{c.Name}', {len} out of {b.Name(w.From)} through the door at {At(dout)} {away}"; - return $"next: '{c.Name}', inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} through its rooms {away}"; + if (w.In is Door din) return $"{next}, inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} through the door at {At(din)} {away}"; + if (w.Out is Door dout) return $"{next}, {len} out of {b.Name(w.From)} through the door at {At(dout)} {away}"; + return $"{next}, inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} through its rooms {away}"; } // ── Walks into, out of and between buildings ─────────────────────────────────────────────────── diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 71fdcdf..d4be3f8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -20,7 +20,9 @@ public static unsafe class PluginExports // "RynthAi.Hub" v1 for RynthILT (the Mini Remote hosting its ILT tabs, /myquests, spell names, loot // matching, the .usd importer, session stats; Shared/RynthAiHubApi.cs, HubInterface.cs), // "RynthAi.Yield" v1 for RynthDefective (the player's key press goes before RynthAi's next action; - // Shared/RynthAiYieldApi.cs, YieldInterface.cs). + // Shared/RynthAiYieldApi.cs, YieldInterface.cs), + // "RynthAi.Routes" v1 for a plugin that has RynthAi make dungeon routes (/ra dunroute, dunpatrol-save; + // JSON in and out, Shared/RynthAiRoutesApi.cs, RoutesInterface.cs). // Fixed signature: void* (const char* iface, uint version). [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) @@ -33,6 +35,7 @@ public static unsafe class PluginExports if (table == IntPtr.Zero) table = ActivityInterface.Query(iface, version); if (table == IntPtr.Zero) table = HubInterface.Query(iface, version); if (table == IntPtr.Zero) table = YieldInterface.Query(iface, version); + if (table == IntPtr.Zero) table = RoutesInterface.Query(iface, version); return table != IntPtr.Zero ? table : CombatHookInterface.Query(iface, version); } catch @@ -58,6 +61,8 @@ public static unsafe class PluginExports catch (Exception ex) { LogShutdownError(plugin, "ActivityInterface.Release", ex); } try { YieldInterface.Release(); } catch (Exception ex) { LogShutdownError(plugin, "YieldInterface.Release", ex); } + try { RoutesInterface.Release(); } + catch (Exception ex) { LogShutdownError(plugin, "RoutesInterface.Release", ex); } try { HubInterface.Release(); } // Version 0; the table stays (RynthILT's render thread may hold it) catch (Exception ex) { LogShutdownError(plugin, "HubInterface.Release", ex); } try { CombatHookInterface.Shutdown(); } // the hook goes native at once (RynthLua re-claims after a reload) diff --git a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs index 92f5d5d..1d8951e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs @@ -50,6 +50,10 @@ public static class VirindiTankProfileImporter /// Full paths of .utl files copied into the Rynth loot folder this run (for activating loot). public List CopiedLootDestPaths { get; } = new(); public List LogLines { get; } = new(); + /// The ring options of each text .usd read (file name, values); see . + internal List<(string File, VtRingSettings Ring)> RingSettingsFound { get; } = new(); + /// "Min Ring Targets 2, Ring Range 5 (from the profile)" when they were set; else "". + public string RingSettingsSet { get; internal set; } = string.Empty; } /// RynthAi LootProfiles folder. @@ -108,6 +112,9 @@ public static class VirindiTankProfileImporter } } + if (mergeMonsterRules) + ApplyRingSettings(settings, result); + if (result.LootFilesCopied == 0 && result.MonsterRulesAdded == 0) result.LogLines.Add("No .utl loot files, Rynth monsters.json, or text MyMonsters .usd found under VirindiTank paths."); @@ -140,7 +147,7 @@ public static class VirindiTankProfileImporter } /// Text SCF .usd with MyMonsters — same subset as Monster Editor import for the current character merge. - private static void TryMergeUsdMyMonstersScf(string usdPath, LegacyUiSettings settings, Result result) + internal static void TryMergeUsdMyMonstersScf(string usdPath, LegacyUiSettings settings, Result result) { if (string.IsNullOrWhiteSpace(usdPath) || !File.Exists(usdPath)) return; @@ -161,6 +168,9 @@ public static class VirindiTankProfileImporter return; } + var ring = VtRingSettings.Read(allText.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)); + if (ring.Any) result.RingSettingsFound.Add((Path.GetFileName(usdPath), ring)); + var tmp = new List(); if (!VirindiTankUsdMyMonstersScfParser.TryParseMyMonsters(allText, tmp, out string? note) || tmp.Count == 0) return; @@ -172,6 +182,32 @@ public static class VirindiTankProfileImporter $"Monsters: VT MyMonsters from {Path.GetFileName(usdPath)} — parsed {tmp.Count} row(s), +{newNamed} new rule(s).{(string.IsNullOrEmpty(note) ? "" : " " + note)}"); } + /// + /// The ring options of the .usd profiles read (VtRingSettings) into Min Ring Targets and Ring + /// Range: the import is the player's, so these two settings may change here and only here. This + /// import reads every profile under the VirindiTank folders, so it sets them only when every + /// profile that has ring options agrees; profiles that differ leave both alone and say so. + /// None found: the settings are left as they are. + /// + internal static void ApplyRingSettings(LegacyUiSettings settings, Result result) + { + var found = result.RingSettingsFound; + if (found.Count == 0) return; + var first = found[0].Ring; + foreach (var (file, ring) in found) + { + if (ring.SameAs(first)) continue; + result.LogLines.Add($"Ring settings: the profiles differ ({found[0].File}: {first.Describe()}; {file}: {ring.Describe()}): " + + "Min Ring Targets and Ring Range left alone. Import one profile from the Hub's VTank import to take its values."); + return; + } + foreach (string c in first.Clamped) result.LogLines.Add($"Ring settings: {c} (the settings' range)"); + first.ApplyTo(settings); + result.RingSettingsSet = first.Describe(); + result.LogLines.Add($"Ring settings: set {result.RingSettingsSet}" + + (found.Count > 1 ? $", the same in {found.Count} profiles." : $", {found[0].File}.")); + } + /// Merges VT-style rows into like Monster Editor external import. private static void MergeVtMonsterRows(IReadOnlyList src, LegacyUiSettings settings, Result result) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VtRingSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VtRingSettings.cs new file mode 100644 index 0000000..59252c6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VtRingSettings.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.ProfileImport; + +/// +/// VTank's two ring options in a text .usd profile, MinimumRingTargets and RingDistance, as +/// RynthAi's Min Ring Targets and Ring Range (2026-11-06: an imported profile brought the +/// monsters' Ring ticks but not the ring options that go with them, so a player who rang at 2 +/// targets in VTank waited for RynthAi's default 4). Applied only by an import the player starts, +/// never on a load. A value the .usd doesn't have leaves the setting alone (VTank writes only the +/// options changed from its defaults). +/// +/// The options are rows of four lines after the tables: "s", the option name, its type tag +/// ("i", "d", "b"), the value. RingDistance is in VTank's distance unit, a fraction of a landblock +/// (0.0208333 is 5 / 240), converted as every VTank distance in RynthAi is (MetaManager's +/// VtDistanceToYards: x240, whole yards, the same value a meta's RingDistance option gives), then +/// held to the settings window's range. +/// +internal sealed class VtRingSettings +{ + // The settings window's and the /ra set ranges (RynthAiPlugin's setting limits, the engine's Int rows). + internal const int MinTargetsLow = 1, MinTargetsHigh = 20; + internal const int RangeLow = 1, RangeHigh = 50; + + /// Min Ring Targets from the profile, or null when it has none. + public int? MinRingTargets { get; private set; } + /// Ring Range (yards) from the profile, or null when it has none. + public int? RingRange { get; private set; } + /// The profile's raw RingDistance (landblock units), for the notes. + public double? RawRingDistance { get; private set; } + /// A value was held to the allowed range ("Ring Range 60 -> 50"). + public List Clamped { get; } = new(); + + public bool Any => MinRingTargets != null || RingRange != null; + + /// Reads the two options from a .usd's lines (the first of each). + public static VtRingSettings Read(IReadOnlyList lines) + { + var r = new VtRingSettings(); + for (int i = 1; i + 2 < lines.Count; i++) + { + if (!string.Equals(lines[i - 1].Trim(), "s", StringComparison.Ordinal)) continue; + string name = lines[i].Trim(); + string value = lines[i + 2].Trim(); + if (r.MinRingTargets == null && name.Equals("MinimumRingTargets", StringComparison.OrdinalIgnoreCase) + && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double n)) + { + int v = (int)Math.Round(n); + int c = Math.Clamp(v, MinTargetsLow, MinTargetsHigh); + if (c != v) r.Clamped.Add($"Min Ring Targets {v} -> {c}"); + r.MinRingTargets = c; + } + else if (r.RingRange == null && name.Equals("RingDistance", StringComparison.OrdinalIgnoreCase) + && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double d)) + { + string yards = Meta.MetaManager.VtDistanceToYards(value, wholeYards: true); + if (!int.TryParse(yards, NumberStyles.Integer, CultureInfo.InvariantCulture, out int y)) continue; + int c = Math.Clamp(y, RangeLow, RangeHigh); + if (c != y) r.Clamped.Add($"Ring Range {y} -> {c}"); + r.RingRange = c; + r.RawRingDistance = d; + } + } + return r; + } + + /// "Min Ring Targets 2, Ring Range 5 (from the profile)"; "" when the profile has neither. + public string Describe() + { + if (!Any) return string.Empty; + var parts = new List(2); + if (MinRingTargets is int t) parts.Add($"Min Ring Targets {t}"); + if (RingRange is int y) parts.Add($"Ring Range {y}"); + return string.Join(", ", parts) + " (from the profile)"; + } + + /// What applying would change, against : "Min Ring Targets 2 (now 4), Ring Range 5 (unchanged)". + public string DescribeAgainst(LegacyUiSettings s) + { + if (!Any) return string.Empty; + var parts = new List(2); + if (MinRingTargets is int t) parts.Add($"Min Ring Targets {t} ({(t == s.MinRingTargets ? "unchanged" : $"now {s.MinRingTargets}")})"); + if (RingRange is int y) parts.Add($"Ring Range {y} ({(y == s.RingRange ? "unchanged" : $"now {s.RingRange}")})"); + return string.Join(", ", parts); + } + + /// Writes the values the profile has into ; the others are left alone. + public void ApplyTo(LegacyUiSettings s) + { + if (MinRingTargets is int t) s.MinRingTargets = t; + if (RingRange is int y) s.RingRange = y; + } + + public bool SameAs(VtRingSettings o) => MinRingTargets == o.MinRingTargets && RingRange == o.RingRange; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/BlacklistManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/BlacklistManager.cs index 73fa49d..986c65f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/BlacklistManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/BlacklistManager.cs @@ -58,6 +58,13 @@ namespace RynthCore.Plugin.RynthAi.Raycasting } } + /// Blacklists a target for its own duration rather than the configured one. + public void BlacklistFor(int targetId, int seconds) + { + _blacklistExpirations[targetId] = RynthClock.Now.AddSeconds(seconds); + Log?.Invoke($"0x{(uint)targetId:X8} blacklisted {seconds}s (out of reach)"); + } + /// /// Immediately blacklists a target for the configured timeout duration. /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/RoutesInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/RoutesInterface.cs new file mode 100644 index 0000000..9752c13 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RoutesInterface.cs @@ -0,0 +1,95 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// RynthAi's side of the "RynthAi.Routes" interface (Shared/RynthAiRoutesApi.cs, 2026-10-30): another +/// plugin has RynthAi make dungeon routes (the work of /ra dunroute and /ra dunpatrol-save) and reads +/// JSON answers. Request checks and queues; RynthAi's tick does the work (RynthAiPlugin.DunRoutes.cs); +/// Poll reads a job. Runs on the plugin pump thread (the caller's OnTick), on the current plugin instance. +/// +internal static unsafe class RoutesInterface +{ + private static RynthAiRoutesApiV1* _table; + private static IntPtr _out; // the last string handed back (valid until the next call) + + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthAiRoutesApiV1.InterfaceName || version == 0 || version > RynthAiRoutesApiV1.InterfaceVersion) return IntPtr.Zero; + if (_table == null) + { + var t = (RynthAiRoutesApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiRoutesApiV1)); + t->Version = RynthAiRoutesApiV1.InterfaceVersion; + t->StructSize = (uint)sizeof(RynthAiRoutesApiV1); + t->Request = &Request; + t->Poll = &Poll; + _table = t; + } + return (IntPtr)_table; + } + + /// Frees the table and the last string (plugin shutdown). Callers resolve it every tick. + public static void Release() + { + var t = _table; + _table = null; + if (t != null) NativeMemory.Free(t); + IntPtr o = _out; + _out = IntPtr.Zero; + if (o != IntPtr.Zero) Marshal.FreeCoTaskMem(o); + } + + private static void Out(byte** dst, string value) + { + if (dst == null) return; + IntPtr fresh = Marshal.StringToCoTaskMemUTF8(value ?? ""); + IntPtr old = _out; + _out = fresh; + if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old); + *dst = (byte*)fresh; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint Request(byte* json, byte** answer) + { + try + { + string text = json == null ? "" : Marshal.PtrToStringUTF8((IntPtr)json) ?? ""; + var p = PluginExports.Runtime.Plugin; + if (p == null) { Out(answer, DunRouteJobs.ErrorJson("RynthAi isn't ready")); return 0; } + uint id = p.RouteRequest(text, out string error); + Out(answer, id != 0 ? DunRouteJobs.QueuedJson(id) : DunRouteJobs.ErrorJson(error)); + return id; + } + catch (Exception ex) + { + try { Out(answer, DunRouteJobs.ErrorJson("RynthAi failed to take the request: " + ex.Message)); } catch { } + return 0; + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Poll(uint id, byte** json) + { + try + { + var p = PluginExports.Runtime.Plugin; + if (p == null) + { + Out(json, "{\"id\":" + id.ToString(System.Globalization.CultureInfo.InvariantCulture) + + ",\"state\":\"unknown\",\"detail\":\"RynthAi isn't ready\"}"); + return 0; + } + bool known = p.RouteJobs.TryPoll(id, out string answer); + Out(json, answer); + return known ? 1 : 0; + } + catch + { + return 0; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 03fb851..b6e73dc 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -110,9 +110,13 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra meta list — list the metas in MetaFiles"); ChatLine("[RynthAi] /ra lua run — run a RynthLua script (same as /lua run; also stop, list, exec )"); ChatLine("[RynthAi] /ra items fill — add weapons, healing kits, lockpicks and pet essences from your pack"); + ChatLine("[RynthAi] /ra aetheria [status|unbox|on|off] — unbox Coalesced Aetheria with an Aetheria Mana Stone (Unbox Aetheria When Idle)"); ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off"); ChatLine("[RynthAi] /ra dunnav — navigate to NS/EW coords through dungeon (no nav file needed)"); ChatLine("[RynthAi] /ra dunnav-patrol — circular hunt patrol through the whole dungeon (no nav file needed)"); + ChatLine("[RynthAi] /ra dunroute to exit|far|portal | |room [overwrite] — save a Once nav from here to there in this dungeon"); + ChatLine("[RynthAi] /ra dunpatrol-save [overwrite] — save the patrol dunnav-patrol would walk from here as a circular nav"); + ChatLine("[RynthAi] /ra dunroute info | where — describe a saved nav (points, length, cells, this dungeon's?) | where you are, the portals known"); ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it"); ChatLine("[RynthAi] /ra jump[swzxc] [heading] [holdtime] — jump with optional face/direction (s=run w=fwd x=back z=strafeL c=strafeR)"); ChatLine("[RynthAi] /ra corpseinfo — show corpse range/open diagnostics"); @@ -124,6 +128,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra lootparse — inspect the selected loot profile"); ChatLine("[RynthAi] /ra lootcheckinv — test the loot profile against inventory"); ChatLine("[RynthAi] /ra lootcheck — classify selected item (on|off = auto on click)"); + ChatLine("[RynthAi] /ra lootname add|remove|list|radius|clear — loot anything in the world with that name while botting (a chest is opened, an item picked up; *part* matches part of a name)"); ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't"); ChatLine("[RynthAi] /ra loot mode [profile|rares] — loot by the loot profile, or rares and needed mana stones only"); ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item"); @@ -1177,20 +1182,56 @@ public sealed partial class RynthAiPlugin double rad = deg * Math.PI / 180.0; double unit = yards / 240.0; // nav coordinates are 240-yard units + double goalNs = ns + Math.Cos(rad) * unit, goalEw = ew + Math.Sin(rad) * unit; var route = new NavRouteParser { RouteType = NavRouteType.Once }; - route.Points.Add(new NavPoint + + // The way there round what's in the way (owner, 2026-11-06: "nav route is not navving around + // obstacles"; a treasure map meta walks 50 yd steps on a heading and stuck on rocks and walls): RynthNav's + // path, planned like the Outdoor Hunt's walks. A straight line when RynthNav has no mesh or no way here. + string how = "straight"; + if (TryHuntPosition(out _, out OutdoorHunt.Vec at)) { - Type = NavPointType.Point, - NS = ns + Math.Cos(rad) * unit, - EW = ew + Math.Sin(rad) * unit, - Z = z / 240.0, - }); + var goal = new OutdoorHunt.Vec(at.X + Math.Sin(rad) * yards, at.Y + Math.Cos(rad) * yards, at.Z); + OutdoorHunt.PathResult path = HuntPath(at, goal); + if ((path.Status == OutdoorHunt.PathStatus.Ok || path.Status == OutdoorHunt.PathStatus.Partial) && path.Corners.Count > 0) + { + route = HeadingRoute(path.Corners); + how = path.Status == OutdoorHunt.PathStatus.Ok + ? $"round obstacles, {route.Points.Count} point(s)" + : $"round obstacles as far as it goes, {route.Points.Count} point(s)"; + } + else how = path.Status switch + { + OutdoorHunt.PathStatus.NoMesh => "straight (no RynthNav map here)", + OutdoorHunt.PathStatus.Unavailable => "straight (RynthNav isn't loaded)", + _ => "straight (RynthNav found no way)", + }; + } + if (route.Points.Count == 0) + route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = goalNs, EW = goalEw, Z = z / 240.0 }); + settings.CurrentNavPath = ""; settings.CurrentRoute = route; settings.ActiveNavIndex = 0; settings.EnableNavigation = true; - Host.Log($"[RynthAi] navheading: {yards:0} yd on {deg:0}° -> NS {route.Points[0].NS:0.0000} EW {route.Points[0].EW:0.0000}"); - ReplyOk($"[RynthAi] Navigating {yards:0} yd on heading {deg:0}° (to NS {route.Points[0].NS:0.000} EW {route.Points[0].EW:0.000})."); + Host.Log($"[RynthAi] navheading: {yards:0} yd on {deg:0}° -> NS {goalNs:0.0000} EW {goalEw:0.0000}, {how}"); + ReplyOk($"[RynthAi] Navigating {yards:0} yd on heading {deg:0}° (to NS {goalNs:0.000} EW {goalEw:0.000}), {how}."); + } + + /// A Once route through RynthNav's corners (world x east, y north, as the Outdoor Hunt installs them). + internal static NavRouteParser HeadingRoute(IReadOnlyList corners) + { + var route = new NavRouteParser { RouteType = NavRouteType.Once }; + foreach (var c in corners) + route.Points.Add(new NavPoint + { + Type = NavPointType.Point, + EW = (c.X / 24.0 - 1019.5) / 10.0, + NS = (c.Y / 24.0 - 1019.5) / 10.0, + Z = c.Z / 240.0, + Doorway = c.Door, + }); + return route; } private void HandleAddNavPointCommand() @@ -1600,7 +1641,8 @@ public sealed partial class RynthAiPlugin internal LootEditorBridge LootEditor => _lootEditor ??= new LootEditorBridge( () => _dashboard?.Settings?.CurrentLootPath ?? string.Empty, OnLootProfileEdited, - Vendor.AutoVendorManager.MainProfileDir) + // AutoVendor's own folders, so the picker lists what a vendor reads (before login: the main folder). + () => (IReadOnlyList?)_autoVendor?.ProfileDirs() ?? new[] { Vendor.AutoVendorManager.MainProfileDir }) { Items = new LootItemHooks { @@ -3210,49 +3252,94 @@ public sealed partial class RynthAiPlugin } } - private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false, bool followedIn = false) + /// Why or built nothing. + private enum DunBuildRefusal { - // The one way into the dungeon patrol (the command, the dashboard button, a meta's "Patrol", the hazard - // reroute): where a server's owners asked for it to be off (a Thread on DreamWeave) nothing is built (ServerPolicy). - if (ServerPolicy.PatrolOff(Host)) - { - if (_dunPatrolActive) StopPatrolForServer(); - if (!isRebuild) ChatLine(ServerPolicy.PatrolOffMessage); - return; - } + /// Built. + None, + /// Anything else: settings not ready, an empty graph, no start cell. + Other, + /// A server's owners asked for the patrol to be off here (ServerPolicy). + Policy, + /// The client isn't ready: no position or nav coordinates, the cell dat not loaded (a job waits). + NotReady, + /// Not in a dungeon (a running patrol stands down). + NotInDungeon, + /// No walkable patrol from here (a running patrol stands down). + EmptyRoute, + } + + /// + /// A dungeon patrol laid from where the character stands: what /ra dunnav-patrol installs (Route, + /// started at StartIdx, the lead-in points included) and what /ra dunpatrol-save writes (Loop: the + /// lap alone, BuildPatrolRoute's points, without the walk out of a hazard or a portal's reach). + /// + private sealed class DunPatrolBuild + { + public DunRouteWorld World = null!; + public DungeonPatrolOptions Options = null!; + public NavRouteParser Route = null!; + public List Loop = null!; + public int StartIdx; + public uint StartCell; + public bool Evacuated; + public NavPoint? WalkOut; + public List? PortalReport; + } + + /// Tests: a landblock's cell graph and map geometry without the dats (null: the dats, as live). + internal Func Graph, DungeonGeometry? Geo)?>? DungeonMapOverride; + + /// + /// Where the character is, for the patrol and for a dungeon route: the dungeon's cell graph and map, + /// the start cell, the hazard cells (the stored ones and the lava/acid floors seeded first) and the + /// portals the client knows here. names the command in the "inside a dungeon" + /// line, starts the others ("DunNav-Patrol"). Null with the line to show. + /// + private DunRouteWorld? TryGetDunWorld(string who, string label, out DungeonPatrolOptions patrolOptions, out string error, out DunBuildRefusal refusal) + { + patrolOptions = DungeonPatrolOptions.Default; + error = ""; + refusal = DunBuildRefusal.Other; var settings = _dashboard?.Settings; - if (settings == null) { if (!isRebuild) ReplyFail("[RynthAi] Settings not ready."); return; } - var patrolOptions = PatrolOptionsFrom(settings); + if (settings == null) { error = "[RynthAi] Settings not ready."; return null; } + patrolOptions = PatrolOptionsFrom(settings); if (!Host.TryGetPlayerPose(out uint playerCell, out float playerLocalX, out float playerLocalY, out float patrolWZ, out _, out _, out _, out _)) { - if (!isRebuild) ReplyFail("[RynthAi] Cannot get player position."); return; + refusal = DunBuildRefusal.NotReady; + error = "[RynthAi] Cannot get player position."; + return null; } uint landblockKey = playerCell >> 16; bool isDungeon = (playerCell & 0xFFFF) >= 0x0100; if (!isDungeon) { - // Left the dungeon (e.g. portalled out) — stop tracking; nothing to rebuild. - _dunPatrolActive = false; - if (!isRebuild) ReplyFail("[RynthAi] dunnav-patrol requires you to be inside a dungeon (cell >= 0x0100)."); - return; + refusal = DunBuildRefusal.NotInDungeon; + error = $"[RynthAi] {who} requires you to be inside a dungeon (cell >= 0x0100)."; + return null; } - var cellDat = _raycast?.GeometryLoader.CellDat; - if (cellDat == null || !cellDat.IsLoaded) + var map = DungeonMapOverride?.Invoke(landblockKey); + var cellDat = DungeonMapOverride == null ? _raycast?.GeometryLoader.CellDat : null; + if (DungeonMapOverride == null && (cellDat == null || !cellDat.IsLoaded)) { - if (!isRebuild) ReplyFail("[RynthAi] Cell dat not loaded — raycast system must be initialized first."); return; + refusal = DunBuildRefusal.NotReady; + error = "[RynthAi] Cell dat not loaded — raycast system must be initialized first."; + return null; } if (!NavCoordinateHelper.TryGetNavCoords(Host, out double playerNS, out double playerEW)) { - if (!isRebuild) ReplyFail("[RynthAi] Cannot get player nav coordinates."); return; + refusal = DunBuildRefusal.NotReady; + error = "[RynthAi] Cannot get player nav coordinates."; + return null; } - var graph = DungeonPathfinder.GetGraph(landblockKey, cellDat); - if (graph.Count == 0) { if (!isRebuild) ReplyFail("[RynthAi] DunNav-Patrol: dungeon graph is empty."); return; } + var graph = map?.Graph ?? (cellDat != null ? DungeonPathfinder.GetGraph(landblockKey, cellDat) : new Dictionary()); + if (graph.Count == 0) { error = $"[RynthAi] {label}: dungeon graph is empty."; return null; } // Prefer the actual cell the player is standing in. NearestCell-by-distance can // pick a same-floor cell across an interior wall when the player is hugging a @@ -3265,7 +3352,7 @@ public sealed partial class RynthAiPlugin else { startCell = DungeonPathfinder.NearestCell(graph, playerNS, playerEW, patrolWZ); - if (startCell == 0) { if (!isRebuild) ReplyFail("[RynthAi] DunNav-Patrol: cannot find starting cell."); return; } + if (startCell == 0) { error = $"[RynthAi] {label}: cannot find starting cell."; return null; } } // Pull in hazards discovered on previous visits to this dungeon so the route avoids @@ -3290,6 +3377,55 @@ public sealed partial class RynthAiPlugin var hazards = DungeonPathfinder.PatrolHazards(_objectCache?.GetHazardCells(), surfaceHazards, patrolOptions.AvoidHazardFloors ? null : DungeonHazardStore.Load(landblockKey), patrolOptions); + // The dungeon map geometry (doorways, floors, walls): doorways taken straight on and + // big rooms crossed directly. Null (old cell walk) until DungeonLOS is up. + var geometry = map != null ? map.Value.Geo : DungeonPathfinder.GetGeometry(landblockKey, cellDat!, _raycast?.GeometryLoader?.DungeonLOS); + + refusal = DunBuildRefusal.None; + return new DunRouteWorld + { + Landblock = landblockKey, + PlayerCell = playerCell, + StartCell = startCell, + X = ((playerCell >> 24) & 0xFF) * 192.0 + playerLocalX, + Y = ((playerCell >> 16) & 0xFF) * 192.0 + playerLocalY, + Z = patrolWZ, + Graph = graph, + Geo = geometry, + Hazards = hazards, + // Portals (DungeonPathfinder.Portals.cs, 2026-10-23): every portal the client knows in this dungeon. + Portals = PatrolPortalsIn(landblockKey), + Wall = patrolOptions.WallClearance, + }; + } + + /// + /// Lays the circular dungeon patrol from the character's current cell, excluding all + /// currently-known hazard cells and keeping out of the portals known: the one place a + /// patrol is built (/ra dunnav-patrol installs it, /ra dunpatrol-save writes it). + /// names the command in the "inside a dungeon" line. Null with the + /// line to show ( says why). + /// + private DunPatrolBuild? TryBuildDunPatrol(string who, out string error, out DunBuildRefusal refusal) + { + // The one way into the dungeon patrol (the command, the dashboard button, a meta's "Patrol", the hazard + // reroute, /ra dunpatrol-save): where a server's owners asked for it to be off (a Thread on DreamWeave) + // nothing is built (ServerPolicy). + if (ServerPolicy.PatrolOff(Host)) + { + refusal = DunBuildRefusal.Policy; + error = ServerPolicy.PatrolOffMessage; + return null; + } + var w = TryGetDunWorld(who, "DunNav-Patrol", out var patrolOptions, out error, out refusal); + if (w == null) return null; + var graph = w.Graph; + var hazards = w.Hazards; + var geometry = w.Geo; + var portals = w.Portals; + uint playerCell = w.PlayerCell, startCell = w.StartCell; + float playerLocalX = (float)(w.X - w.OriginX), playerLocalY = (float)(w.Y - w.OriginY), patrolWZ = (float)w.Z; + // Start-in-hazard evacuation: if the player is standing on an excluded (acid/lava) cell, build // the patrol from the nearest SAFE cell and prepend a lead-in waypoint so the first move walks // out of the hazard onto safe ground — instead of producing an empty, hazard-locked route. @@ -3306,15 +3442,11 @@ public sealed partial class RynthAiPlugin } } - // The dungeon map geometry (doorways, floors, walls): doorways taken straight on and - // big rooms crossed directly. Null (old cell walk) until DungeonLOS is up. - var geometry = DungeonPathfinder.GetGeometry(landblockKey, cellDat, _raycast?.GeometryLoader?.DungeonLOS); // Portals (DungeonPathfinder.Portals.cs, 2026-10-23): the patrol keeps out of every portal the // client knows in this dungeon (Tiny Hive: it walked onto the Surface Portal). A character // standing in a portal's circle walks out first, and the patrol is built from where it gets // to (that cell, that side of the portal). - var portals = PatrolPortalsIn(landblockKey); - double playerWX = ((playerCell >> 24) & 0xFF) * 192.0 + playerLocalX, playerWY = ((playerCell >> 16) & 0xFF) * 192.0 + playerLocalY; + double playerWX = w.X, playerWY = w.Y; (double X, double Y, double Z) startAt = (playerWX, playerWY, patrolWZ); NavPoint? walkOut = null; uint losCell = playerCell; @@ -3324,7 +3456,9 @@ public sealed partial class RynthAiPlugin // Diagnostics: record which rule laid each waypoint (logged below, one line each). var pointLog = new Dictionary(ReferenceEqualityComparer.Instance); DungeonPathfinder.PointLog = pointLog; + DungeonPathfinder.MainRouteNote = null; NavRouteParser route; + List loop; try { if (portals.Count > 0) @@ -3344,6 +3478,7 @@ public sealed partial class RynthAiPlugin } route = DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards, geometry, patrolOptions, portals, startAt); portalReport = DungeonPathfinder.LastPortalAvoidance; + loop = new List(route.Points); // the lap, before any lead-in goes in front of it } finally { DungeonPathfinder.PointLog = null; } @@ -3377,11 +3512,53 @@ public sealed partial class RynthAiPlugin // patrol started or enable nav — the bot would just stand in place (in the hazard) taking damage. if (route.Points.Count == 0) { - _dunPatrolActive = false; - if (!isRebuild) - ReplyFail("[RynthAi] DunNav-Patrol: no walkable route from here — you're standing in or surrounded by a hazard. Move to safe ground and retry."); + refusal = DunBuildRefusal.EmptyRoute; + error = "[RynthAi] DunNav-Patrol: no walkable route from here — you're standing in or surrounded by a hazard. Move to safe ground and retry."; + return null; + } + + // The lap from the waypoint the patrol starts at (the first of the lap at or after StartIdx). + var inLoop = new HashSet(loop, ReferenceEqualityComparer.Instance); + int loopStart = 0; + for (int k = 0; k < route.Points.Count; k++) + { + var p = route.Points[(startIdx + k) % route.Points.Count]; + if (!inLoop.Contains(p)) continue; + loopStart = loop.IndexOf(p); + break; + } + if (loopStart > 0) loop = loop.GetRange(loopStart, loop.Count - loopStart).Concat(loop.GetRange(0, loopStart)).ToList(); + + refusal = DunBuildRefusal.None; + return new DunPatrolBuild + { + World = w, Options = patrolOptions, Route = route, Loop = loop, StartIdx = startIdx, StartCell = startCell, + Evacuated = evacuate, WalkOut = walkOut, PortalReport = portalReport, + }; + } + + private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false, bool followedIn = false) + { + var b = TryBuildDunPatrol("dunnav-patrol", out string error, out var refusal); + if (b == null) + { + if (refusal == DunBuildRefusal.Policy) + { + if (_dunPatrolActive) StopPatrolForServer(); + if (!isRebuild) ChatLine(error); + return; + } + // Left the dungeon (e.g. portalled out), or no walkable route from here: stop tracking; nothing to rebuild. + if (refusal is DunBuildRefusal.NotInDungeon or DunBuildRefusal.EmptyRoute) _dunPatrolActive = false; + if (!isRebuild) ReplyFail(error); return; } + var settings = _dashboard!.Settings; + var patrolOptions = b.Options; + var route = b.Route; + int startIdx = b.StartIdx; + var portals = b.World.Portals; + var hazards = b.World.Hazards; if (!isRebuild) { @@ -3407,7 +3584,7 @@ public sealed partial class RynthAiPlugin // hazard is sighted in this same landblock. _dunPatrolActive = true; _dunPatrolRoute = route; - _dunPatrolLandblock = landblockKey; + _dunPatrolLandblock = b.World.Landblock; _dunPatrolFollowTriedLb = uint.MaxValue; _dunPatrolHazardVersion = _objectCache?.HazardVersion ?? 0; _dunPatrolSettings.MarkBuilt(patrolOptions); @@ -3418,7 +3595,7 @@ public sealed partial class RynthAiPlugin string portalNote = portals.Count > 0 ? $", kept out of {portals.Count} portal(s)" : ""; if (isRebuild && followedIn) { - ChatLine($"[RynthAi] DunNav-Patrol: followed you into dungeon 0x{landblockKey:X4} → {route.Points.Count} waypoints, patrolling here{hazardNote}{portalNote}. Stop the macro or load a route to end it."); + ChatLine($"[RynthAi] DunNav-Patrol: followed you into dungeon 0x{b.World.Landblock:X4} → {route.Points.Count} waypoints, patrolling here{hazardNote}{portalNote}. Stop the macro or load a route to end it."); } else if (isRebuild && settingsChanged) { @@ -3437,10 +3614,10 @@ public sealed partial class RynthAiPlugin string skipNote = startIdx > 0 ? $", skipped {startIdx} blocked waypoint(s)" : ""; int doorwayPts = 0; foreach (var p in route.Points) if (p.Doorway) doorwayPts++; - string layout = geometry != null && doorwayPts > 0 + string layout = b.World.Geo != null && doorwayPts > 0 ? $", {doorwayPts} of them lined up on doorways" - : geometry == null ? " (dungeon map not loaded yet: cell-centre route)" : ""; - ReplyOk($"[RynthAi] DunNav-Patrol: {graph.Count} cells, {route.Points.Count} waypoints{layout} → circular patrol started{skipNote}{hazardNote}{portalNote}"); + : b.World.Geo == null ? " (dungeon map not loaded yet: cell-centre route)" : ""; + ReplyOk($"[RynthAi] DunNav-Patrol: {b.World.Graph.Count} cells, {route.Points.Count} waypoints{layout} → circular patrol started{skipNote}{hazardNote}{portalNote}"); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs index 1453b29..41ce13a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs @@ -28,6 +28,7 @@ namespace RynthCore.Plugin.RynthAi; /// /ra iteminfo layout pet|line pet-roster style lines or the Mag one-liner /// /ra iteminfo loot on|off describe what the looter takes in its "Looted" line /// /ra iteminfo loot salvage on|off salvage too (material and workmanship only) +/// /ra iteminfo color <name>|#RRGGBB the lines' colour in RynthCore's chat, whatever their chat type ("default": the type's) /// /ra iteminfo reset restore defaults /// Every option is also editable in the "RynthAi Item Info" window (LegacyItemInfoUi). /// @@ -165,6 +166,23 @@ public sealed partial class RynthAiPlugin ReplyOk($"[RynthAi] Item info on loot: {OnOff(s.LootChat)} (salvage {OnOff(s.LootChatSalvage)})"); return; + case "color": + case "colour": + if (arg3.Length > 0) + { + string? color = MagItemInfoCatalog.ParseTextColor(arg3); + if (color == null) + { + ReplyFail("[RynthAi] Usage: /ra iteminfo color " + TextColorWords()); + return; + } + s.TextColor = color; + } + ReplyOk(s.TextColor.Length == 0 + ? "[RynthAi] Item info text colour: the chat type's own colour. Others: /ra iteminfo color " + TextColorWords() + : $"[RynthAi] Item info text colour: {MagItemInfoCatalog.TextColorLabel(s.TextColor)} in RynthCore's chat (same tab; AC's chat window shows the chat type's colour)"); + return; + case "reset": s.ResetToDefaults(); ReplyOk("[RynthAi] Item info settings reset to defaults."); @@ -185,7 +203,15 @@ public sealed partial class RynthAiPlugin if (found != 0) { QueueItemInfo(unchecked((int)found), requestId: true); return; } ReplyFail($"[RynthAi] Item info: no \"{name}\" in your inventory."); } - ReplyFail("[RynthAi] Usage: /ra iteminfo [|me|on|off|settings|fields|field on|off|rating on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|loot on|off|reset]"); + ReplyFail("[RynthAi] Usage: /ra iteminfo [|me|on|off|settings|fields|field on|off|rating on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|loot on|off|color |#RRGGBB|reset]"); + } + + /// "default|allegiance|...|#RRGGBB": what /ra iteminfo color takes. + private static string TextColorWords() + { + var sb = new StringBuilder(); + foreach (var c in MagItemInfoCatalog.TextColors) sb.Append(c.Word).Append('|'); + return sb.Append("#RRGGBB").ToString(); } /// @@ -460,9 +486,34 @@ public sealed partial class RynthAiPlugin int headerType = s?.ChatType ?? 1; int detailType = s == null || s.DetailChatType == MagItemInfoSettings.SameAsHeader ? headerType : s.DetailChatType; - Host.WriteToChat(prefix + lines[0], headerType); + WriteItemInfoLine(prefix + lines[0], headerType); for (int i = 1; i < lines.Count; i++) - Host.WriteToChat(prefix + " " + lines[i], detailType); + WriteItemInfoLine(prefix + " " + lines[i], detailType); + } + + /// The engine's name for a line's own colour in RynthCore's chat (engine UI/Data/ChatOwnColors.cs). + internal const string ChatColorTarget = "RynthCore.Chat"; + + // An engine from before 2026-11-05 answered "no such plugin" once: item info lines then go + // out exactly as before, without asking again. + private bool _infoColorUnsupported; + + /// + /// One item info line, in (which picks its chat tab and AC's chat + /// window). With Info text colour set () the engine + /// is asked to draw the next line in that colour just before it is written: RynthCore's chat + /// shows it so, in the same tab. Unset, or an older engine: the plain WriteToChat, as before. + /// + internal void WriteItemInfoLine(string text, int chatType) + { + string color = ItemInfoSettings?.TextColor ?? string.Empty; + if (color.Length > 0 && text.Length > 0 && !_infoColorUnsupported && Host.HasWriteToChat && Host.HasSendPluginCommand + && !Host.SendPluginCommand(ChatColorTarget, "nextcolor", color)) + { + _infoColorUnsupported = true; + ItemInfoLog("the engine has no line colours (before 2026-11-05): item info keeps its chat type's colour"); + } + Host.WriteToChat(text, chatType); } /// Item Info window preview: the selected item's lines, or null when nothing is selected. @@ -514,10 +565,11 @@ public sealed partial class RynthAiPlugin } } - /// Item Info window "Test" button: sample line in the chosen chat type. + /// Item Info window "Test" button: sample line in the chosen chat type (and the Info text colour). private void TestItemInfoChatType(int chatType) { string prefix = ItemInfoSettings?.Prefix ?? "[RynthAi Item] "; - Host.WriteToChat($"{prefix}Item info chat test (type {chatType})", chatType); + string color = ItemInfoSettings?.TextColor ?? string.Empty; + WriteItemInfoLine($"{prefix}Item info chat test (type {chatType}{(color.Length > 0 ? ", colour " + color : "")})", chatType); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Aetheria.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Aetheria.cs new file mode 100644 index 0000000..748cb06 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Aetheria.cs @@ -0,0 +1,103 @@ +using System; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; + +namespace RynthCore.Plugin.RynthAi; + +// Unbox Aetheria When Idle (a player's request, 2026-11-01). The unboxing lives in +// Loot/AetheriaUnboxer.cs; this is the plugin side: when it is safe to unbox, and +// /ra aetheria [unbox|status|on|off]. +public sealed partial class RynthAiPlugin +{ + private AetheriaUnboxer CreateAetheriaUnboxer(LegacyUiSettings settings) => + new(Host, settings, _objectCache) + { + PlayerId = () => _playerId, + Chat = s => Host.WriteToChat(s, 1), + }; + + /// + /// A safe moment to unbox: the server puts the character in peace mode for the clap, so with the + /// macro on it is the scroll reader's moment (no monster within Monster Range nor on top of us, + /// not buffing, looting, salvaging or in a portal), and no fight even with Enable Combat off. + /// With the macro off (an unbox asked for by hand) only no corpse, cast, salvage or portal. + /// Never while a scroll is read or missiles are crafted (both hold the bot themselves). + /// + internal bool IsSafeToUnboxAetheria(LegacyUiSettings s) + { + if (s.IsMacroRunning) + { + if (!IsSafeToReadScroll(s)) return false; + var combat = _combatManager; + if (combat != null && (combat.HasEngageableTarget || combat.IsUnderCloseAttack)) return false; + } + else + { + if (_openedContainerId != 0 || _targetCorpseId != 0) return false; + if (_buffManager != null && _buffManager.PendingSpellId != 0) return false; + if (_salvageManager?.IsBusy == true) return false; + if (_navigationEngine?.IsInPortalAction == true) return false; + } + try { if (Host.HasIsPortaling && Host.IsPortaling()) return false; } catch { } + if (_scrollLearner?.IsReading == true) return false; + if (_missileCraftingManager?.IsCrafting == true) return false; + return true; + } + + /// One unboxer tick; true while an unbox is in flight and the bot should hold still. + private bool TickAetheriaUnbox(LegacyUiSettings settings) + { + var unboxer = _aetheriaUnboxer; + if (unboxer == null) return false; + try + { + return unboxer.Tick(IsSafeToUnboxAetheria(settings), PacedBusy); + } + catch (Exception ex) + { + if (Environment.TickCount64 - _lastAetheriaErrorLogAt > 10_000) + { + _lastAetheriaErrorLogAt = Environment.TickCount64; + Host.Log($"[Aetheria] tick threw: {ex.GetType().Name}: {ex.Message}"); + } + return false; + } + } + + private long _lastAetheriaErrorLogAt = -100_000; + + internal const string AetheriaUsage = "Usage: /ra aetheria [status | unbox | on | off]"; + + /// /ra aetheria: status (the default), unbox (every coalesced piece now), on|off (the setting). + private void HandleAetheriaCommand(string[] parts) + { + var settings = _dashboard?.Settings; + var unboxer = _aetheriaUnboxer; + if (settings == null || unboxer == null) { ReplyFail("[RynthAi] Aetheria: not ready yet (log in first)."); return; } + + string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "status"; + switch (verb) + { + case "status": + ChatLine(unboxer.Describe()); // the status asked for + break; + case "unbox": + case "now": + if (!unboxer.RequestManual(out string reply)) { ReplyFail(reply); break; } + if (settings.IsMacroRunning && !IsSafeToUnboxAetheria(settings)) + reply += " It starts once nothing else needs the moment (a fight, a corpse, a buff)."; + ReplyOk(reply); + break; + case "on": + case "off": + settings.UnboxAetheriaWhenIdle = verb == "on"; + _dashboard?.SaveSettings(); + ReplyOk($"[RynthAi] Unbox Aetheria When Idle: {verb}" + + (verb == "on" && !settings.IsMacroRunning ? " (it works while the macro runs; /ra aetheria unbox does it now)." : ".")); + break; + default: + ReplyFail($"[RynthAi] Aetheria: unknown option '{parts[2]}'. {AetheriaUsage}"); + break; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs index 37a529c..b30bc89 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs @@ -38,6 +38,9 @@ public sealed partial class RynthAiPlugin private bool IsChestLoot(int id) => id != 0 && id == _lootChestId; + /// The last chest looted to the end (every item judged), for the meta's ralastchestlooted[] (0 = none). + private uint _lastChestLootedId; + internal enum ChestVerdict { Loot, Wait, Skip } /// Names AC/ACE give house storage and hooks ("Storage", "Wall Hook", ...). @@ -145,6 +148,37 @@ public sealed partial class RynthAiPlugin LootDiag($"[RynthAi] Chest loot: chest 0x{(uint)id:X8} waits for combat (targets in range); it is looted when the fight ends if it is still open."); } + // ── An open chest goes before a fight further off (2026-11-07) ────────────────────────────── + // Unlike a corpse, a chest closes as soon as you walk away from it. A meta opened a treasure + // cache with a golem 32 m off: combat had the tick, walked to the golem, the cache closed and + // nothing was taken. So an open chest RynthAi is to loot gets the tick ahead of combat (the + // loot-starvation turn, without its 8 s wait), unless a monster is within + // LootStarveCloseYards: that one is fought first, next to the chest. + private int _chestFirstLoggedFor; + + /// An open chest RynthAi is to loot: the loot container, or one opened and not taken yet. + private bool OpenChestWaiting() + { + if (IsChestLoot(_openedContainerId)) return true; + return _chestCandidateId != 0 && _openedContainerId == 0 && _targetCorpseId == 0 + && JudgeChest(_chestCandidateId, out _) == ChestVerdict.Loot; + } + + /// The arbiter's loot-first input for an open chest (see above). Logs once per chest. + private bool IsOpenChestTurn(bool wantLoot, bool wantCombat) + { + if (!wantLoot || !wantCombat || !OpenChestWaiting()) return false; + if (_combatManager?.HasCloseThreat(LootStarveCloseYards) == true) return false; + int id = IsChestLoot(_openedContainerId) ? _openedContainerId : _chestCandidateId; + if (_chestFirstLoggedFor != id) + { + _chestFirstLoggedFor = id; + LootDiag($"[RynthAi] Chest loot: chest 0x{(uint)id:X8} is open, so it is looted before the fight " + + $"(no monster within {LootStarveCloseYards:0} yd; a chest closes when you walk away)."); + } + return true; + } + /// /// TickCorpseOpening, nothing claimed or open: takes an open eligible chest as the loot /// container (no walk, no open: it is open and in reach). True when this tick is spent on it. @@ -220,6 +254,8 @@ public sealed partial class RynthAiPlugin /// private void FinishChestLoot(int chestId, string why, bool close, bool sayNothingMatched) { + if (why == "completed") + _lastChestLootedId = unchecked((uint)chestId); // ralastchestlooted[] // Pickup with macro off > Leave the chest open: a chest the player opened stays open, and chat says so. bool leaveOpen = close && chestId == _manualChestLootId && (_dashboard?.Settings?.LootChestsMacroOffLeaveOpen ?? false); if (chestId == _manualChestLootId) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs new file mode 100644 index 0000000..4613d6d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs @@ -0,0 +1,190 @@ +// RynthAiPlugin.DeathWait.cs - the death animation, learned per monster and waited out (2026-11-08). +// +// Tom: "the bot is running away from a monster it's killed and then turning around and running back +// because there is a second or two for the corpse to show up due to a death animation", and "with +// looting on I'd like it to wait that duration before running away, and maybe an extra second to let +// the corpse spawn and be looted. As soon as the corpse is looted the bot can run away, if no corpse +// spawns it needs to continue." +// +// Learning: ACE creates the corpse once the death animation has played, so the time from our kill +// notice to its "Corpse of " object (CorpseTimer) is that monster's death. It goes to the +// session's monster stats ("cd", "cn") and to the learned table (MonsterXpTable, kept across logins). +// +// The wait: with the macro and Looting on, our kill starts a wait of the monster's learned death (or +// DeathWaitDefaultMs while it isn't learned) plus DeathWaitExtraMs. While it runs, looting counts as +// work, the arbiter gives Looting the tick over combat (ArbiterInputs.DeathWait, as Boost Loot does) +// and combat locks no new target (CombatManager.HoldNewTarget), so neither a fight's walk, nor nav, +// nor the Outdoor Hunt takes the character away. A monster within CloseAttackYards is still fought +// (HoldNewTarget and CombatEngaged both let it through). It ends when the corpse is looted, when no +// corpse came in the time, or DeathWaitDecideMs after a corpse came that the looter hasn't claimed +// (the loot rules don't take it, or the looter leaves it for the fight: then the fight goes on and the +// looter comes back for it; holding combat there stood the character still, both waiting on the other). +// Pump thread throughout. +using System; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.Plugin.RynthAi.MonsterStats; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// A monster's death while it isn't learned yet (most AC deaths take 1.5-3 s). + internal const long DeathWaitDefaultMs = 2500; + /// Waited past the death, for the corpse to come and be seen. + internal const long DeathWaitExtraMs = 1000; + /// After the corpse came: this long for the loot rules to say whether it is looted (its ID). + internal const long DeathWaitDecideMs = 1000; + /// A corpse being looted holds the wait at most this long past it (never a wedge). + internal const long DeathWaitLootMaxMs = 20000; + /// A learned death longer than this is no death animation (the corpse came late for some other reason). + internal const long DeathWaitMaxDeathMs = 8000; + /// A corpse farther than this from the character isn't its kill's. + private const double DeathCorpseNearYd = 80; + + private readonly CorpseTimer _corpseTimer = new(); + private long _deathWaitAt; // CorpseNowMs of the kill being waited for; 0 = none + private long _deathWaitMs; // how long the wait is + private string _deathWaitName = ""; + private int _deathCorpseId; // its corpse, once it came + private long _deathCorpseAt; + private bool _deathWaitHeld; // HasLootWork's answer this tick (the arbiter's DeathWait input) + + /// The death wait can run: the macro and Looting on, and the looter able to loot now. + private bool DeathWaitCanRun(LegacyUiSettings settings) + => settings.IsMacroRunning && settings.EnableLooting + && !BoostNavHoldsLoot(settings) + && !settings.LootOnlyRareCorpses // rare-only: most corpses have nothing to wait for + && !LootModes.IsRares(settings.LootMode) + && !IsLootingBlockedByPack(settings) + && !_useRefusals.HoldsOpens(CorpseNowMs) + && GetCorpseApproachRangeMaxMeters(settings) > 0.25; + + /// Our kill of (the kill notice's monster, null when none was named): its corpse is on its way. + private void StartDeathWait(string? name) + { + var s = _dashboard?.Settings; + if (s == null || !DeathWaitCanRun(s)) return; + double? learned = string.IsNullOrWhiteSpace(name) ? null : _xpTable.DeathMs(name); + long death = learned is double d ? (long)Math.Round(Math.Clamp(d, 0, DeathWaitMaxDeathMs)) : DeathWaitDefaultMs; + _deathWaitMs = death + DeathWaitExtraMs; + _deathWaitAt = CorpseNowMs; + _deathWaitName = name?.Trim() ?? ""; + _deathCorpseId = 0; + _deathCorpseAt = 0; + string who = _deathWaitName.Length > 0 ? $"'{_deathWaitName}'" : "the kill"; + string why = learned != null + ? $"its death takes {death / 1000.0:0.0} s, learned over {_xpTable.DeathsTimed(name)} {(_xpTable.DeathsTimed(name) == 1 ? "kill" : "kills")}" + : $"its death isn't learned yet: {DeathWaitDefaultMs / 1000.0:0.0} s"; + Host.Log($"[RynthAi] Kill: waiting up to {_deathWaitMs / 1000.0:0.0} s for the corpse of {who} ({why}, and {DeathWaitExtraMs / 1000.0:0.0} s more) before moving on."); + } + + /// The wait is over: says why, once. + private void EndDeathWait(string why) + { + if (_deathWaitAt == 0) return; + long took = CorpseNowMs - _deathWaitAt; + string who = _deathWaitName.Length > 0 ? $"'{_deathWaitName}'" : "the kill"; + Host.Log($"[RynthAi] Kill: done waiting for the corpse of {who} after {took / 1000.0:0.0} s: {why}."); + _deathWaitAt = 0; + _deathCorpseId = 0; + _deathCorpseAt = 0; + _deathWaitName = ""; + _deathWaitHeld = false; + } + + /// + /// The wait holds the character now (and ends it, with its line, when it is over). Before the + /// corpse: until the wait's time is up. With the corpse: while it is claimed, open or lootable in + /// range (up to DeathWaitLootMaxMs), else DeathWaitDecideMs for the loot rules' look. + /// + private bool DeathWaitHolds(LegacyUiSettings settings) + { + if (_deathWaitAt == 0) return false; + if (!DeathWaitCanRun(settings)) { EndDeathWait("looting stopped or can't loot now"); return false; } + long now = CorpseNowMs, since = now - _deathWaitAt; + if (_deathCorpseId == 0) + { + if (since < _deathWaitMs) return true; + EndDeathWait($"no corpse came in {_deathWaitMs / 1000.0:0.0} s, carrying on"); + return false; + } + if (_completedCorpses.ContainsKey(_deathCorpseId)) { EndDeathWait("its corpse is looted"); return false; } + // Only a corpse the looter has claimed or opened holds the character. One that is merely + // lootable in range while the looter defers to the fight ("waits for combat") must not: the + // wait would hold combat's next target while looting waits for combat, and the character + // stood still until the looter's own 8 s rule (2026-11-08: 16 s for a 1.2 s death). + bool looting = _targetCorpseId == _deathCorpseId || _openedContainerId == _deathCorpseId; + if (looting) + { + if (since < _deathWaitMs + DeathWaitLootMaxMs) return true; + EndDeathWait("looting its corpse is taking too long, carrying on"); + return false; + } + if (now - _deathCorpseAt < DeathWaitDecideMs) return true; + EndDeathWait(_lootableInRange.Contains(_deathCorpseId) + ? "its corpse came but the looter leaves it for the fight (it comes back for it), carrying on" + : "its corpse came but the loot rules don't take it, carrying on"); + return false; + } + + /// A corpse was looted (MarkCorpseCompleted): when it is the kill's (or the first seen since the kill), the wait is over. + private void EndDeathWaitFor(int corpseId) + { + if (_deathWaitAt == 0) return; + bool kills = _deathCorpseId != 0 + ? corpseId == _deathCorpseId + : !_corpseWaitingSince.TryGetValue(corpseId, out long seen) || seen >= _deathWaitAt; + if (kills) EndDeathWait("its corpse is looted"); + } + + /// + /// OnCreateObject: a "Corpse of X" near the character. Times X's death (CorpseTimer: the session's + /// stats and the learned table), and is the waited-for kill's corpse when the names match. + /// + private void NoteCorpseCreated(uint objectId) + { + if (_corpseTimer.Waiting == 0 && _deathWaitAt == 0) return; + if (!Host.HasGetObjectName || !Host.TryGetObjectName(objectId, out string name)) return; + string? killed = CorpseTimer.KilledName(name); + if (killed == null || !CorpseNearMe(objectId)) return; + if (_corpseTimer.OnCorpse(name, CorpseNowMs) is var (who, ms) && ms <= DeathWaitMaxDeathMs) + { + _monsterStats.OnCorpseTime(who, ms, DateTime.UtcNow); + _xpTable.RecordDeath(who, ms); + } + if (_deathWaitAt != 0 && _deathCorpseId == 0 + && (_deathWaitName.Length == 0 || killed.Equals(_deathWaitName, StringComparison.OrdinalIgnoreCase))) + { + _deathCorpseId = unchecked((int)objectId); + _deathCorpseAt = CorpseNowMs; + } + } + + /// Within DeathCorpseNearYd of the character (true when either position can't be read). + private bool CorpseNearMe(uint objectId) + { + if (!Host.HasGetObjectPosition || !Host.HasGetPlayerPose) return true; + if (!Host.TryGetObjectPosition(objectId, out uint cell, out float x, out float y, out _) || cell == 0) return true; + if (!Host.TryGetPlayerPose(out uint me, out float mx, out float my, out _, out _, out _, out _, out _) || me == 0) return true; + double ax = ((cell >> 24) & 0xFF) * 192.0 + x, ay = ((cell >> 16) & 0xFF) * 192.0 + y; + double bx = ((me >> 24) & 0xFF) * 192.0 + mx, by = ((me >> 16) & 0xFF) * 192.0 + my; + // A dungeon's cells share one landblock origin: the local positions compare directly there too. + double dx = ax - bx, dy = ay - by; + return Math.Sqrt(dx * dx + dy * dy) <= DeathCorpseNearYd; + } + + /// CombatManager.HoldNewTarget: Boost Loot Priority's hold, or the death wait's. + private bool LootHoldsNewTarget() + { + if (BoostLootHoldsNewTarget()) return true; + var s = _dashboard?.Settings; + return s != null && DeathWaitHolds(s); + } + + /// CombatManager.HoldNewTargetWhy: the words for its one log line. + private string LootHoldWhy() + => _deathWaitAt != 0 && !BoostLootHoldsNewTarget() + ? "the kill's corpse comes first (its death animation, then the loot)" + : "Boost Loot Priority loots the kill first"; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunRoutes.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunRoutes.cs new file mode 100644 index 0000000..2d6a13f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunRoutes.cs @@ -0,0 +1,516 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Dungeon routes on demand (2026-10-30). Players and plugins (an AI layer driving characters) save +/// RynthAi nav routes inside a dungeon, from where the character stands: +/// /ra dunroute <name> to exit|far|portal <name>|<x> <y> <z>|room <n> [overwrite] +/// /ra dunpatrol-save <name> [overwrite] the patrol /ra dunnav-patrol would walk now, as a circular nav +/// /ra dunroute info <name> a saved nav described (points, length, cells, landblock, this dungeon's?) +/// /ra dunroute where where the character is, and the portals known here +/// and the "RynthAi.Routes" interface (Shared/RynthAiRoutesApi.cs) does the same with JSON. One +/// implementation: (the route itself is DungeonRouteMaker's, the patrol +/// TryBuildDunPatrol's, the one dunnav-patrol installs). The chat command runs it at once, on the thread +/// commands run on (as dunnav-patrol always has); an interface job runs it from OnTick, one a tick +/// (TickDunRoutes), and waits while the client isn't ready (portal space, the dats loading). +/// Nothing is loaded or started: the route is a file in NavProfiles, run with /ra nav load. +/// +public sealed partial class RynthAiPlugin +{ + private const string DunRouteUsage = + "[RynthAi] Usage: /ra dunroute to exit|far|portal | |room [overwrite] — /ra dunroute info — /ra dunroute where"; + private const string DunPatrolSaveUsage = + "[RynthAi] Usage: /ra dunpatrol-save [overwrite] (the patrol /ra dunnav-patrol would walk from here, saved as a circular nav)"; + + private DunRouteJobs? _routeJobs; + + /// The interface's jobs (RoutesInterface; the host tests read them too). + internal DunRouteJobs RouteJobs => _routeJobs ??= new DunRouteJobs(); + + // Where the character came into the dungeon it is in: the exit portal is usually by it. + private uint _dunLastLandblock; + private (uint Landblock, uint Cell, double X, double Y, double Z)? _dunArrival; + + /// What a request came to: done (Json is the result), failed, or waiting on the client (Wait). + /// Detail is the one line chat shows (without the "[RynthAi] " tag); Lines go under it. + internal sealed record DunRouteOutcome(bool Ok, bool Wait, string Detail, string? Json, IReadOnlyList Lines) + { + public static DunRouteOutcome Fail(string why) => new(false, false, Bare(why), null, Array.Empty()); + public static DunRouteOutcome Waiting(string why) => new(false, true, Bare(why), null, Array.Empty()); + + /// A line without the chat tags the shared build lines start with. + internal static string Bare(string s) + { + s = (s ?? "").Trim(); + foreach (string tag in new[] { "[RynthAi] ", "DunNav-Patrol: ", "DunRoute: " }) + if (s.StartsWith(tag, StringComparison.Ordinal)) s = s[tag.Length..]; + return s; + } + } + + // ── The interface's side ───────────────────────────────────────────────── + + /// RynthAi.Routes Request: the job id, or 0 with the reason (bad JSON, not logged in, too many jobs). + internal uint RouteRequest(string json, out string error) + { + if (!DunRouteRequest.TryParseJson(json, out var request, out error)) return 0; + if (!_loginComplete) { error = "RynthAi isn't logged in: there is no character in the world"; return 0; } + uint id = RouteJobs.Add(request, out error); + if (id != 0) Host.Log($"[RynthAi] Routes: job {id} queued ({DunRouteRequest.OpName(request.Op)}{(request.Name.Length > 0 ? " '" + request.Name + "'" : "")})"); + return id; + } + + // The route the doorway check last looked at (and its point list: an edit replaces it), and the + // sidecar entry waiting for the character to be in its dungeon. + private NavRouteParser? _doorwayRoute; + private List? _doorwayPoints; + private DunRouteSidecar.Entry? _doorwayPending; + + /// + /// A nav just loaded that the route maker wrote (DunRouteSidecar: the same name and hash): its + /// doorway points get their flag back once the character is in that dungeon, so it walks the + /// doorways as dunnav-patrol does. However it was loaded (the Nav picker, /ra nav load, /vt nav load, + /// a meta): checked when the current route changes. An edited file, another dungeon, any other + /// nav: nothing. Before navigation in the same tick. + /// + private void TickDunDoorways() + { + var s = _dashboard?.Settings; + if (s == null) return; + var route = s.CurrentRoute; + if (!ReferenceEquals(route, _doorwayRoute)) + { + _doorwayRoute = route; + _doorwayPoints = route?.Points; + string? log = null; + _doorwayPending = route == null ? null : DunRouteSidecar.Match(DungeonRouteMaker.Folder, s.CurrentNavPath, route, out log); + if (log != null) Host.Log(log); + } + var e = _doorwayPending; + if (e == null || route == null) return; + if (!ReferenceEquals(route.Points, _doorwayPoints)) + { + Host.Log($"[RynthAi] DunRoute: '{e.File}' was edited before you were in its dungeon: its doorway points aren't restored"); + _doorwayPending = null; + return; + } + if (!_loginComplete || !Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _)) return; + if ((cell >> 16) != e.Landblock || (cell & 0xFFFF) < 0x0100) return; // not in that dungeon (yet) + int n = DunRouteSidecar.Apply(route, e); + _doorwayPending = null; + Host.Log($"[RynthAi] DunRoute: '{e.File}': {n} doorway point(s) restored (saved by the route maker in dungeon {e.Landblock:X4})"); + } + + /// OnTick (every tick): the doorway flags of a route just loaded, where the character came into a + /// dungeon, and the oldest job. + private void TickDunRoutes() + { + TickDunDoorways(); + if (_loginComplete) TickDunArrival(); + var jobs = _routeJobs; + var job = jobs?.Next(); + if (jobs == null || job == null) return; + if (!_loginComplete) + { + jobs.Finish(job, false, "the character left the world before the job ran", null); + return; + } + jobs.Working(job, "working"); + DunRouteOutcome o; + try { o = RunDunRouteRequest(job.Request); } + catch (Exception ex) + { + Host.Log($"[RynthAi] Routes: job {job.Id} threw: {ex}"); + o = DunRouteOutcome.Fail($"failed ({ex.GetType().Name}: {ex.Message})"); + } + if (o.Wait) + { + if (jobs.WaitedTooLong(job)) jobs.Finish(job, false, $"gave up after {DunRouteJobs.WaitLimitMs / 1000} s: {o.Detail}", null); + else jobs.Working(job, "waiting: " + o.Detail); + return; + } + jobs.Finish(job, o.Ok, o.Detail, o.Json); + Host.Log($"[RynthAi] Routes: job {job.Id} {(o.Ok ? "done" : "failed")}: {o.Detail}"); + } + + /// Where the character lands in a new landblock (after portal space) is where it came in. + /// Not where RynthAi first sees it (a login, a reload): that isn't an arrival. + private void TickDunArrival() + { + if (Host.HasIsPortaling && Host.IsPortaling()) return; + if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _)) return; + uint lb = cell >> 16; + if (lb == 0 || lb == _dunLastLandblock) return; + bool first = _dunLastLandblock == 0; + _dunLastLandblock = lb; + _dunArrival = null; + if (first || (cell & 0xFFFF) < 0x0100) return; + _dunArrival = (lb, cell, ((cell >> 24) & 0xFF) * 192.0 + x, ((cell >> 16) & 0xFF) * 192.0 + y, z); + Host.Log($"[RynthAi] DunRoute: came into dungeon {lb:X4} at cell {cell:X8} ({x:F1}, {y:F1}, {z:F1})"); + } + + private void ForgetDunArrival() + { + _dunLastLandblock = 0; + _dunArrival = null; + } + + /// What a route needs beyond the map: where the character came in, the explored share, portal destinations. + private void FillDunWorldExtras(DunRouteWorld w) + { + if (_dunArrival is { } a && a.Landblock == w.Landblock) w.Arrival = (a.Cell, a.X, a.Y, a.Z); + try { w.Explored = _dashboard?.ExploredShare(w.Landblock); } catch { w.Explored = null; } + const uint STypePortalDest = 38u; // the appraised destination ("Destination: ..."), when the client has it + w.PortalDestination = id => Host.HasGetObjectStringProperty && Host.TryGetObjectStringProperty(id, STypePortalDest, out string d) ? d : null; + } + + // ── One implementation ─────────────────────────────────────────────────── + + /// Runs one request (the chat command's or a job's). Pump thread (DungeonPathfinder's caches). + internal DunRouteOutcome RunDunRouteRequest(DunRouteRequest r) + { + if (r.Op != DunRouteOp.Info && Host.HasIsPortaling && Host.IsPortaling()) + return DunRouteOutcome.Waiting("you're in portal space"); + return r.Op switch + { + DunRouteOp.Where => RunDunWhere(), + DunRouteOp.Info => RunDunInfo(r), + DunRouteOp.DunPatrol => RunDunPatrolSave(r), + _ => RunDunRoute(r), + }; + } + + private DunRouteOutcome RunDunRoute(DunRouteRequest r) + { + if (r.To == null) return DunRouteOutcome.Fail("no target: to exit|far|portal | |room "); + if (!r.Overwrite && File.Exists(DungeonRouteMaker.PathFor(r.Name))) return DunRouteOutcome.Fail(DungeonRouteMaker.AlreadyThere(r.Name)); + var w = TryGetDunWorld("dunroute", "DunRoute", out _, out string error, out var refusal); + if (w == null) return refusal == DunBuildRefusal.NotReady ? DunRouteOutcome.Waiting(error) : DunRouteOutcome.Fail(error); + FillDunWorldExtras(w); + var b = DungeonRouteMaker.TryBuildRoute(w, r.To, out error); + if (b == null) return DunRouteOutcome.Fail(error); + if (!DungeonRouteMaker.TrySave(r.Name, b.Route, r.Overwrite, w.Landblock, out string path, out bool overwrote, out error, b.Notes)) + return DunRouteOutcome.Fail(error); + Host.Log($"[RynthAi] DunRoute: {path}: {b.Route.Points.Count} points, {b.Yards:F0} yd, cells {b.StartCell:X8} -> {b.GoalCell:X8} ({b.PathCells} on the path), {r.To.Words()} = {b.TargetText}"); + string detail = $"{(overwrote ? "replaced" : "saved")} {r.Name}.nav: {b.Route.Points.Count} points, {b.Yards:0} yd from cell {w.PlayerCell:X8} to {b.TargetText}. Run it: /ra nav load {r.Name}"; + return new DunRouteOutcome(true, false, detail, DungeonRouteMaker.RouteJson(w, b, r.Name, path, overwrote), Under(b.LeftOut, b.Notes)); + } + + private DunRouteOutcome RunDunPatrolSave(DunRouteRequest r) + { + if (!r.Overwrite && File.Exists(DungeonRouteMaker.PathFor(r.Name))) return DunRouteOutcome.Fail(DungeonRouteMaker.AlreadyThere(r.Name)); + var b = TryBuildDunPatrol("dunpatrol-save", out string error, out var refusal); + if (b == null) return refusal == DunBuildRefusal.NotReady ? DunRouteOutcome.Waiting(error) : DunRouteOutcome.Fail(error); + var w = b.World; + FillDunWorldExtras(w); + var route = new NavRouteParser { RouteType = NavRouteType.Circular, Points = b.Loop }; + if (route.Points.Count == 0) return DunRouteOutcome.Fail("no walkable patrol from here"); + var leftOut = new List(); + var notes = new List(); + if (!DungeonRouteMaker.TrySave(r.Name, route, r.Overwrite, w.Landblock, out string path, out bool overwrote, out error, notes)) + return DunRouteOutcome.Fail(error); + + // What the lap doesn't walk, and why. + int cells = w.Graph.Count; + int reachable = DungeonRouteMaker.ReachableCount(w.Graph, b.StartCell, w.Hazards); + var rooms = w.Geo != null && w.Geo.DoorwayCount > 0 ? DungeonPathfinder.BuildRooms(w.Graph, w.Geo, w.Hazards) : null; + int covered = DungeonPathfinder.GetMainRouteNodes(w.Graph, b.StartCell, w.Hazards, b.Options, rooms).Count; + if (reachable < cells) leftOut.Add($"{cells - reachable} of {cells} cells can't be walked to from here (behind drops or lava/acid, or not joined)"); + if (covered < reachable) + leftOut.Add($"{reachable - covered} reachable cells left out by the coverage ({DungeonPatrolOptions.CoverageName(b.Options.Coverage)}" + + (b.Options.Coverage == PatrolCoverage.Everything ? "" : $", dead ends of up to {b.Options.MaxDeadEndCells} cells") + "; Settings > Dungeon Patrol)"); + int hz = w.HazardsHere; + if (hz > 0) leftOut.Add($"{hz} lava/acid cell{(hz == 1 ? "" : "s")} kept out of"); + foreach (var a in b.PortalReport ?? new List()) + if (a.Closed.Count + a.CutCells.Count > 0) + leftOut.Add($"beyond portal '{a.Portal.Name}': {a.Closed.Count} opening(s) closed" + (a.CutCells.Count > 0 ? $", {a.CutCells.Count} cell(s) cut off" : "") + " (a portal fires at a touch)"); + var inLoop = new HashSet(b.Loop, ReferenceEqualityComparer.Instance); + int lead = b.Route.Points.Count(p => !inLoop.Contains(p)); + if (lead > 0 || b.Evacuated || b.WalkOut != null) + leftOut.Add($"the walk from where you stand onto the lap ({Math.Max(lead, 1)} point(s): {(b.Evacuated ? "out of lava/acid" : b.WalkOut != null ? "out of a portal's reach" : "round a portal")}) isn't saved: only needed from here"); + if (w.Geo == null) notes.Add("the dungeon map isn't loaded yet: a cell-centre patrol (save it again in a moment for one lined up on doorways)"); + DungeonRouteMaker.AddKnownNotes(w, notes); + + double yards = DungeonRouteMaker.RouteYards(route); + Host.Log($"[RynthAi] DunPatrol-Save: {path}: {route.Points.Count} points, {yards:F0} yd a lap, from {b.StartCell:X8}; {b.Options.Describe()}"); + string detail = $"{(overwrote ? "replaced" : "saved")} {r.Name}.nav: the circular patrol dunnav-patrol walks from here, {route.Points.Count} points, {yards:0} yd a lap ({b.Options.Describe()}). Run it: /ra nav load {r.Name}"; + string json = DungeonRouteMaker.Json(j => + { + j.WriteStartObject(); + j.WriteString("file", path); + j.WriteString("name", r.Name); + DungeonRouteMaker.WriteCounts(j, route, "circular"); + j.WriteString("landblock", DungeonRouteMaker.Hex(w.Landblock, 4)); + j.WritePropertyName("from"); + DungeonRouteMaker.WriteSpot(j, w, w.PlayerCell, w.X, w.Y, w.Z); + j.WriteString("startCell", DungeonRouteMaker.Hex(b.StartCell, 8)); + j.WriteNumber("cells", cells); + j.WriteNumber("reachable", reachable); + j.WriteNumber("covered", covered); + j.WriteNumber("doorwayPoints", DungeonRouteMaker.DoorwayPoints(route)); + j.WriteBoolean("overwrote", overwrote); + j.WriteString("coverage", b.Options.Describe()); + j.WriteStartArray("leftOut"); + foreach (string s in leftOut) j.WriteStringValue(s); + j.WriteEndArray(); + j.WriteStartArray("notes"); + foreach (string s in notes) j.WriteStringValue(s); + j.WriteEndArray(); + j.WriteEndObject(); + }); + return new DunRouteOutcome(true, false, detail, json, Under(leftOut, notes)); + } + + private DunRouteOutcome RunDunInfo(DunRouteRequest r) + { + string path = DungeonRouteMaker.PathFor(r.Name); + if (!File.Exists(path)) return DunRouteOutcome.Fail($"no route named '{r.Name}' in NavProfiles (/ra nav list shows them)"); + string? warning = null; + var route = NavRouteParser.Load(path, s => warning = s); + if (route.LoadWarning != null) warning = route.LoadWarning; + + uint playerCell = Host.TryGetPlayerPose(out uint pc, out _, out _, out _, out _, out _, out _, out _) ? pc : 0; + uint playerLb = playerCell >> 16; + bool inCell = (playerCell & 0xFFFF) >= 0x0100; + var cellDat = DungeonMapOverride == null ? _raycast?.GeometryLoader?.CellDat : null; + bool datOk = cellDat != null && cellDat.IsLoaded; + var dungeonOf = new Dictionary(); + bool? IsDungeon(uint lb) + { + if (lb == playerLb && inCell) return true; // the character is in one of its cells + if (dungeonOf.TryGetValue(lb, out bool? known)) return known; + bool? v = DungeonMapOverride != null ? DungeonMapOverride(lb) != null + : datOk ? NavRecoveryPlanner.ComputeIsDungeon(lb, cellDat!) : null; + return dungeonOf[lb] = v; + } + Dictionary? GraphOf(uint lb) + => DungeonMapOverride != null ? DungeonMapOverride(lb)?.Graph : datOk ? DungeonPathfinder.GraphOf(lb, cellDat!) : null; + + var info = DungeonRouteMaker.DescribeRoute(r.Name, path, route, playerCell, GraphOf, IsDungeon); + if (warning != null) info.Notes.Insert(0, warning); + var inv = CultureInfo.InvariantCulture; + string where = info.Landblock is uint rl + ? $"landblock {rl:X4}" + (info.Dungeon == true ? " (a dungeon)" : info.Dungeon == false ? " (not a dungeon)" : "") + : "no points"; + string mine = info.ForThisDungeon switch + { + "yes" => "made for this dungeon: yes", + "partly" => $"made for this dungeon: partly ({info.PointsHere} of {info.Waypoints} points are in it)", + "no" => "made for this dungeon: no", + _ => "made for this dungeon: can't tell (you aren't in one)", + }; + string detail = $"{r.Name}.nav: {DungeonRouteMaker.TypeName(info.Type)}, {info.Points} points ({info.Waypoints} walked), {info.Yards.ToString("0", inv)} yd, {where}" + + (info.Cells is int c ? $", {c} cells" + (info.StartCell != 0 ? $" ({info.StartCell:X8} to {info.EndCell:X8})" : "") : "") + + $"; {mine}"; + var lines = new List(); + var steps = info.Steps.Where(kv => kv.Value > 0).Select(kv => $"{kv.Key} {kv.Value}").ToList(); + if (steps.Count > 0) lines.Add("steps: " + string.Join(", ", steps)); + if (info.Landblocks.Count > 1) lines.Add("its points fall in landblocks " + string.Join(", ", info.Landblocks.Select(l => l.ToString("X4", inv)))); + if (info.Notes.Count > 0) lines.Add("note: " + string.Join("; ", info.Notes)); + return new DunRouteOutcome(true, false, detail, DungeonRouteMaker.InfoJson(info), lines); + } + + private DunRouteOutcome RunDunWhere() + { + if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _)) + return DunRouteOutcome.Waiting("Cannot get player position."); + uint lb = cell >> 16; + NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew); + var inv = CultureInfo.InvariantCulture; + if ((cell & 0xFFFF) < 0x0100) + { + string outside = DungeonRouteMaker.Json(j => + { + j.WriteStartObject(); + j.WriteBoolean("inDungeon", false); + j.WriteString("landblock", DungeonRouteMaker.Hex(lb, 4)); + j.WriteString("cell", DungeonRouteMaker.Hex(cell, 8)); + j.WriteNumber("x", Math.Round(x, 2)); j.WriteNumber("y", Math.Round(y, 2)); j.WriteNumber("z", Math.Round(z, 2)); + j.WriteNumber("ns", Math.Round(ns, 4)); j.WriteNumber("ew", Math.Round(ew, 4)); + j.WriteEndObject(); + }); + return new DunRouteOutcome(true, false, string.Format(inv, "not in a dungeon: landblock {0:X4}, cell {1:X8} at ({2:0.0}, {3:0.0}, {4:0.0})", lb, cell, x, y, z), outside, Array.Empty()); + } + + var w = TryGetDunWorld("dunroute where", "DunRoute", out _, out string error, out var refusal); + if (w == null) return refusal == DunBuildRefusal.NotReady ? DunRouteOutcome.Waiting(error) : DunRouteOutcome.Fail(error); + FillDunWorldExtras(w); + int reachable = DungeonRouteMaker.ReachableCount(w.Graph, w.StartCell, w.Hazards); + DungeonRooms? rooms = w.Geo != null ? DungeonPathfinder.BuildRooms(w.Graph, w.Geo) : null; + int room = rooms != null && rooms.RoomOf.TryGetValue(w.StartCell, out int rr) ? rr : -1; + var portals = DungeonRouteMaker.PortalsWhere(w); + int hz = w.HazardsHere; + + string json = DungeonRouteMaker.Json(j => + { + j.WriteStartObject(); + j.WriteBoolean("inDungeon", true); + j.WriteString("landblock", DungeonRouteMaker.Hex(lb, 4)); + j.WriteString("cell", DungeonRouteMaker.Hex(cell, 8)); + j.WriteNumber("x", Math.Round(x, 2)); j.WriteNumber("y", Math.Round(y, 2)); j.WriteNumber("z", Math.Round(z, 2)); + j.WriteNumber("ns", Math.Round(ns, 4)); j.WriteNumber("ew", Math.Round(ew, 4)); + j.WriteNumber("cells", w.Graph.Count); + j.WriteNumber("reachable", reachable); + j.WriteBoolean("map", w.Geo != null); + if (rooms != null) j.WriteNumber("rooms", rooms.Cells.Count); else j.WriteNull("rooms"); + if (room >= 0) j.WriteNumber("room", room); else j.WriteNull("room"); + if (w.Explored is double e) j.WriteNumber("explored", Math.Round(e, 3)); else j.WriteNull("explored"); + j.WriteNumber("hazards", hz); + if (w.Arrival is { } a) + { + j.WritePropertyName("arrival"); + DungeonRouteMaker.WriteSpot(j, w, a.Cell, a.X, a.Y, a.Z); + } + else j.WriteNull("arrival"); + j.WriteStartArray("portals"); + foreach (var p in portals) + { + j.WriteStartObject(); + j.WriteString("name", p.Portal.Name); + j.WriteString("id", DungeonRouteMaker.Hex(p.Portal.Id, 8)); + j.WriteString("cell", DungeonRouteMaker.Hex(p.Portal.Cell, 8)); + j.WriteNumber("x", Math.Round(p.Portal.X - w.OriginX, 2)); + j.WriteNumber("y", Math.Round(p.Portal.Y - w.OriginY, 2)); + j.WriteNumber("z", Math.Round(p.Portal.Z, 2)); + j.WriteNumber("yards", Math.Round(p.Yards, 1)); + if (p.WalkYards is double wy) j.WriteNumber("walkYards", Math.Round(wy, 1)); else j.WriteNull("walkYards"); + if (p.Exit != null) j.WriteString("exit", p.Exit); else j.WriteNull("exit"); + if (p.Destination != null) j.WriteString("destination", p.Destination); else j.WriteNull("destination"); + j.WriteEndObject(); + } + j.WriteEndArray(); + j.WriteEndObject(); + }); + + string detail = string.Format(inv, "in dungeon {0:X4}, cell {1:X8} at ({2:0.0}, {3:0.0}, {4:0.0}) (landblock-local); {5} cells, {6} walkable from here", + lb, cell, x, y, z, w.Graph.Count, reachable) + + (rooms != null ? $"; {rooms.Cells.Count} rooms, you're in room {room}" : "; the dungeon map isn't loaded yet (no rooms)") + + (w.Explored is double ex ? string.Format(inv, "; {0:0}% explored", ex * 100) : "") + + (hz > 0 ? $"; {hz} lava/acid cell(s) known" : ""); + var lines = new List(); + if (portals.Count == 0) lines.Add("portals: none known here yet (the client only knows the ones it has been sent)"); + foreach (var p in portals.Take(10)) + lines.Add($"portal '{p.Portal.Name}': {p.Yards:0} yd" + + (p.WalkYards is double wy ? $" ({wy:0} yd on foot)" : " (no walkable way)") + + (p.Exit != null ? $"; exit: {p.Exit}" : "") + + (p.Destination != null ? $"; goes to {p.Destination}" : "")); + if (portals.Count > 10) lines.Add($"... and {portals.Count - 10} more"); + lines.Add(w.Arrival is { } arr + ? string.Format(inv, "you came in at cell {0:X8} ({1:0.0}, {2:0.0}, {3:0.0})", arr.Cell, arr.X - w.OriginX, arr.Y - w.OriginY, arr.Z) + : "RynthAi didn't see you come in (it was loaded after): the exit is picked by its name"); + return new DunRouteOutcome(true, false, detail, json, lines); + } + + private static List Under(List leftOut, List notes) + { + var lines = new List(); + if (leftOut.Count > 0) lines.Add("left out: " + string.Join("; ", leftOut)); + if (notes.Count > 0) lines.Add("note: " + string.Join("; ", notes)); + return lines; + } + + // ── The chat commands ──────────────────────────────────────────────────── + + /// /ra dunroute <name> to <target> [overwrite] | info <name> | where. + private void HandleDunRouteCommand(string[] parts) + { + if (parts.Length < 3) + { + ChatLine(DunRouteUsage); + ChatLine("[RynthAi] targets: exit (the exit portal), far (the farthest spot on foot), portal , (landblock-local metres), room "); + return; + } + string sub = parts[2].ToLowerInvariant(); + if (sub == "where" && parts.Length == 3) + { + RunDunRouteForChat(new DunRouteRequest { Op = DunRouteOp.Where }); + return; + } + if (sub == "info" && (parts.Length < 4 || !parts[3].Equals("to", StringComparison.OrdinalIgnoreCase))) + { + if (parts.Length < 4) { ReplyFail("[RynthAi] Usage: /ra dunroute info (a nav in NavProfiles)"); return; } + if (!DunRouteRequest.TryName(string.Join(" ", parts, 3, parts.Length - 3), out string name, out string nameError)) + { ReplyFail($"[RynthAi] DunRoute: {nameError}."); return; } + RunDunRouteForChat(new DunRouteRequest { Op = DunRouteOp.Info, Name = name }); + return; + } + if (!TryParseDunRouteWords(parts.Skip(2).ToList(), out var request, out string error)) + { + ReplyFail($"[RynthAi] DunRoute: {error}. {DunRouteUsage[10..]}"); + return; + } + RunDunRouteForChat(request); + } + + /// /ra dunpatrol-save <name> [overwrite]. + private void HandleDunPatrolSaveCommand(string[] parts) + { + var words = parts.Skip(2).ToList(); + bool overwrite = words.Count > 0 && words[^1].Equals("overwrite", StringComparison.OrdinalIgnoreCase); + if (overwrite) words.RemoveAt(words.Count - 1); + if (words.Count == 0) { ReplyFail(DunPatrolSaveUsage); return; } + if (!DunRouteRequest.TryName(string.Join(" ", words), out string name, out string error)) + { + ReplyFail($"[RynthAi] DunPatrol-Save: {error}. {DunPatrolSaveUsage[10..]}"); + return; + } + RunDunRouteForChat(new DunRouteRequest { Op = DunRouteOp.DunPatrol, Name = name, Overwrite = overwrite }); + } + + /// + /// The words after "/ra dunroute": <name> to <target> [overwrite]. A name may hold "to" + /// itself ("Way to the hub to exit"): each "to" is tried from the left, and the first split whose + /// name and target both work is taken. False with the reason. + /// + internal static bool TryParseDunRouteWords(IReadOnlyList raw, out DunRouteRequest request, out string error) + { + request = new DunRouteRequest { Op = DunRouteOp.DunRoute }; + error = ""; + var words = raw.ToList(); + if (words.Count > 0 && words[^1].Equals("overwrite", StringComparison.OrdinalIgnoreCase)) + { + request.Overwrite = true; + words.RemoveAt(words.Count - 1); + } + string? firstError = null; + for (int i = 1; i < words.Count; i++) + { + if (!words[i].Equals("to", StringComparison.OrdinalIgnoreCase)) continue; + if (!DunRouteRequest.TryName(string.Join(" ", words.Take(i)), out string name, out string nameError)) { firstError ??= nameError; continue; } + if (!DunTarget.TryParseWords(words.Skip(i + 1).ToList(), out var target, out string targetError)) { firstError ??= targetError; continue; } + request.Name = name; + request.To = target; + return true; + } + error = firstError ?? (words.Count == 0 ? "no name given" : "no \"to\": name the route, then where it goes"); + return false; + } + + /// A request run for a chat command: one line, and the left-out / notes lines under it. + private void RunDunRouteForChat(DunRouteRequest r) + { + string label = r.Op == DunRouteOp.DunPatrol ? "DunPatrol-Save" : "DunRoute"; + var o = RunDunRouteRequest(r); + if (!o.Ok) + { + // A job waits for the client and tries again; a typed command says so instead. + ReplyFail($"[RynthAi] {label}: {o.Detail}" + (o.Wait ? " (try again in a moment)" : "")); + return; + } + bool query = r.Op is DunRouteOp.Info or DunRouteOp.Where; + if (query) ChatLine($"[RynthAi] {label}: {o.Detail}"); + else ReplyOk($"[RynthAi] {label}: {o.Detail}"); + foreach (string line in o.Lines) + { + if (query) ChatLine($"[RynthAi] {line}"); + else ReplyOk($"[RynthAi] {line}"); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.FellowOpen.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.FellowOpen.cs new file mode 100644 index 0000000..ddad28c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.FellowOpen.cs @@ -0,0 +1,72 @@ +// RynthAiPlugin.FellowOpen.cs - Open fellowship on create (2026-11-04). +// +// AC makes a new fellowship closed (only the leader recruits). VTank's auto fellow management opens +// the ones it makes, and players moving over asked for the same. With Auto Fellowship Management and +// Open fellowship on create on, a create RynthAi sends (/mt fellow create, typed or from a meta, or a +// meta's own /fellowship create line) waits for the fellowship to show up with this character leading +// it, then sends one "/fellowship open". Nothing is waited for when the character was already in a +// fellowship (the create fails), and nothing is sent for a fellowship made or closed by hand. +using System; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// How long a create waits for the server to make the fellowship. + internal const long FellowOpenWaitMs = 15_000; + + // Environment.TickCount64 the wait ends at; 0 = no create waiting. + private long _fellowOpenUntil; + + /// Tests: where the fellowship stands, in place of the tracker's read of AC's memory. + internal Func<(bool InFellowship, bool IsLeader, bool IsOpen)>? FellowStateOverride; + + private (bool InFellowship, bool IsLeader, bool IsOpen) FellowState() + { + if (FellowStateOverride != null) return FellowStateOverride(); + var t = _fellowshipTracker; + if (t == null || !t.IsInFellowship) return (false, false, false); + return (true, t.IsLeader, t.IsOpen); + } + + /// A meta's chat line that creates a fellowship through the client ("/fellowship create name"). + private static bool IsFellowshipCreateLine(string cmd) + { + string c = cmd.TrimStart(); + if (c.Length < 2 || (c[0] != '/' && c[0] != '@')) return false; + string[] w = c.Substring(1).Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); + return w.Length >= 3 + && w[0].Equals("fellowship", StringComparison.OrdinalIgnoreCase) + && w[1].Equals("create", StringComparison.OrdinalIgnoreCase); + } + + /// RynthAi just sent a fellowship create: wait for it, to open it, when the settings say so. + private void NoteFellowshipCreate() + { + var s = _dashboard?.Settings; + if (s == null || !s.AutoFellowMgmt || !s.OpenFellowOnCreate) return; + if (FellowState().InFellowship) return; // already in one: the create fails, and this one isn't ours + _fellowOpenUntil = Environment.TickCount64 + FellowOpenWaitMs; + } + + /// Plugin tick: the fellowship RynthAi created is here and ours to lead: open it, once. + private void TickFellowOpen() + { + if (_fellowOpenUntil == 0) return; + var s = _dashboard?.Settings; + if (s == null || !s.AutoFellowMgmt || !s.OpenFellowOnCreate) { _fellowOpenUntil = 0; return; } // switched off meanwhile + if (Environment.TickCount64 > _fellowOpenUntil) + { + _fellowOpenUntil = 0; + Log("[RynthAi] Open fellowship on create: no fellowship came of the create; nothing opened."); + return; + } + var (inFellowship, isLeader, isOpen) = FellowState(); + if (!inFellowship) return; + _fellowOpenUntil = 0; + if (!isLeader || isOpen) return; // someone else's, or already open + if (!Host.HasInvokeChatParser) return; + Host.InvokeChatParser("/fellowship open"); + Log("[RynthAi] Open fellowship on create: sent /fellowship open."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs index 31b63ee..bc0b014 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs @@ -26,6 +26,7 @@ namespace RynthCore.Plugin.RynthAi; // // Commands (/ra itemtool ...; the panel sends the same words through RynthPluginItemToolCommand): // chest set | key | start | stop | status | clear +// relock (also "chest relock"): "Chest re-lock wait (s)", saved in the profile (2026-11-05) // giveitem | givetarget | give | givestop | givestatus | clear // stop (both) // @@ -98,6 +99,7 @@ public sealed partial class RynthAiPlugin EnsureItemTool(); while (_itemToolCmds.TryDequeue(out var cmd)) RunItemToolCommand(cmd.Args, cmd.Trusted); + if (_dashboard?.Settings is LegacyUiSettings s) _chestKey!.RelockWaitSec = s.ChestRelockWaitSec; _chestKey!.Tick(); _quickGive!.Tick(); } @@ -131,7 +133,7 @@ public sealed partial class RynthAiPlugin case "": case "status": ChatLine("[RynthAi] Item Tool - " + _chestKey!.Status + " | " + _quickGive!.Status); - ChatLine("[RynthAi] /ra itemtool chest set|key|start|stop|status and /ra itemtool giveitem|givetarget|give|givestop|givestatus"); + ChatLine("[RynthAi] /ra itemtool chest set|key|start|stop|status /ra itemtool relock and /ra itemtool giveitem|givetarget|give|givestop|givestatus"); return; case "stop": if (_chestKey!.Running) _chestKey.Stop("stopped by you"); @@ -144,8 +146,12 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] Item Tool: the picks are cleared (anything running keeps its own)."); return; case "chest": + if (sub == "relock") { RunRelockCommand(t.Length > 2 ? t[2] : ""); return; } RunChestCommand(sub); return; + case "relock": + RunRelockCommand(sub); + return; case "giveitem": PickGiveItem(); return; case "givetarget": PickGiveTarget(); return; case "givestatus": ChatLine("[RynthAi] Quick give - " + _quickGive!.Status); return; @@ -186,11 +192,46 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] Chest looter - " + ck.Status); return; default: - ChatLine("[RynthAi] Usage: /ra itemtool chest set|key|start|stop|status"); + ChatLine("[RynthAi] Usage: /ra itemtool chest set|key|start|stop|status and /ra itemtool relock "); return; } } + private const string RelockUsage = "/ra itemtool relock "; + + /// + /// "/ra itemtool relock [seconds]" (the panel's "Chest re-lock wait (s)" sends the same): how long + /// after a chest was opened the next key goes on it. Saved in the settings profile; always answers + /// with the value now. + /// + private void RunRelockCommand(string arg) + { + string range = $"{ChestKeyLooter.MinRelockWaitSec}-{ChestKeyLooter.MaxRelockWaitSec} s, default {ChestKeyLooter.DefaultRelockWaitSec}"; + var dash = _dashboard; + LegacyUiSettings? s = dash?.Settings; + if (dash == null || s == null || !dash.ProfileLoaded) + { + ReplyFail($"[RynthAi] Chest looter: the settings profile isn't loaded yet (log in first); the re-lock wait is unchanged. Usage: {RelockUsage} ({range})."); + return; + } + if (arg.Length == 0) + { + ChatLine($"[RynthAi] Chest looter: re-lock wait = {s.ChestRelockWaitSec} s ({range}). Usage: {RelockUsage}."); + return; + } + if (!int.TryParse(arg.TrimEnd('s', 'S'), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int want)) + { + ReplyFail($"[RynthAi] Chest looter: '{arg}' isn't a number of seconds; the re-lock wait is still {s.ChestRelockWaitSec} s. Usage: {RelockUsage} ({range})."); + return; + } + int now = ChestKeyLooter.ClampRelockWaitSec(want); + s.ChestRelockWaitSec = now; + if (_chestKey != null) _chestKey.RelockWaitSec = now; + dash.SaveSettings(); + string clamped = now == want ? "" : now > want ? $" (the least is {now} s)" : $" (the most is {now} s)"; + ReplyOk($"[RynthAi] Chest looter: re-lock wait = {now} s{clamped}. The next key goes on the chest {now} s after it was opened, or sooner when it reads locked again."); + } + // ── Picking ────────────────────────────────────────────────────────────── private uint SelectedForItemTool(string what) @@ -372,7 +413,12 @@ public sealed partial class RynthAiPlugin AppendJson(sb, "key", ck?.KeyName ?? ""); sb.Append(','); AppendJson(sb, "status", ck?.Status ?? "Idle."); sb.Append(','); sb.Append("\"running\":").Append(ck?.Running == true ? "true" : "false").Append(','); - sb.Append("\"looted\":").Append(ck?.Looted ?? 0); + sb.Append("\"looted\":").Append(ck?.Looted ?? 0).Append(','); + // "Chest re-lock wait (s)": the panel's control (absent from an older RynthAi: the panel hides it). + sb.Append("\"relockSec\":").Append(_dashboard?.Settings?.ChestRelockWaitSec ?? ChestKeyLooter.DefaultRelockWaitSec).Append(','); + sb.Append("\"relockMin\":").Append(ChestKeyLooter.MinRelockWaitSec).Append(','); + sb.Append("\"relockMax\":").Append(ChestKeyLooter.MaxRelockWaitSec).Append(','); + sb.Append("\"relockReady\":").Append(_dashboard?.ProfileLoaded == true ? "true" : "false"); sb.Append("},\"give\":{"); AppendJson(sb, "item", qg?.Item.Name ?? ""); sb.Append(','); AppendJson(sb, "target", qg == null || qg.TargetId == 0 ? "" : (_giveTargetClass == (int)AcObjectClass.Player ? "PLAYER " : "") + qg.TargetName); sb.Append(','); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootByName.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootByName.cs new file mode 100644 index 0000000..86bc44a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootByName.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +// Loot by name (2026-11-02), the host side. See LootByName.cs for the list and the bookkeeping. +// +// /ra lootname add | remove | list | radius | clear +// +// While the bot runs with Looting on, an object in the world (not carried, not a corpse, a player or +// a monster) whose name is on the list and that lies inside the radius is USED, which is how AC opens +// a container or picks an item up: the client walks there by itself. Looting is the activity that +// does this, so it outranks hunting and navigation the way a corpse does (HasLootWork asks +// HasLootNameWork; TickCorpseOpening calls TryLootByName). A container that opens is looted by the +// chest looter (RynthAiPlugin.ChestLoot.cs) with the loaded loot profile. +public sealed partial class RynthAiPlugin +{ + private LootByNameList? _lootNames; + private readonly LootNameTracker _lootNameTracker = new(); + private int _lootNameTargetId; // the object the next TryLootByName works on (0 = none) + private long _lootNameScanAt; + private long _lootNameLoggedFor; + + private const long LootNameScanMs = 500; + + private string? _lootNamesSrc; + private float _lootNamesRadiusSrc; + + /// The list the settings hold (Settings > Looting > Loot By Name, or /ra lootname); rebuilt when they change. + private LootByNameList LootNames + { + get + { + var st = _dashboard?.Settings; + string names = st?.LootByNames ?? string.Empty; + float radius = st?.LootByNameRadius ?? (float)LootByNameList.DefaultRadius; + if (_lootNames == null || names != _lootNamesSrc || radius != _lootNamesRadiusSrc) + { + _lootNames = LootByNameList.Parse(names, radius); + _lootNamesSrc = names; + _lootNamesRadiusSrc = radius; + } + return _lootNames; + } + } + + // ── /ra lootname ─────────────────────────────────────────────────────── + + private void HandleLootNameCommand(string[] parts) + { + string sub = parts.Length > 2 ? parts[2].ToLowerInvariant() : "list"; + string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : ""; + var st = _dashboard?.Settings; + if (st == null) { ChatLine("[RynthAi] Settings not ready."); return; } + var list = LootByNameList.Parse(st.LootByNames, st.LootByNameRadius); // edited, then written back + switch (sub) + { + case "add": + if (rest.Length == 0) { ChatLine("[RynthAi] Usage: /ra lootname add (*part* matches part of a name)"); return; } + if (!list.Add(rest)) { ChatLine($"[RynthAi] Loot by name: '{rest}' is already on the list (or the list is full)."); return; } + SaveLootNames(list); + ChatLine($"[RynthAi] Loot by name: added '{rest}' ({list.Names.Count} on the list, radius {list.Radius:0} yd)."); + return; + case "remove": + case "delete": + if (!list.Remove(rest)) { ChatLine($"[RynthAi] Loot by name: '{rest}' isn't on the list."); return; } + SaveLootNames(list); + ChatLine($"[RynthAi] Loot by name: removed '{rest}'."); + return; + case "clear": + list.Clear(); + _lootNameTracker.Clear(); + SaveLootNames(list); + ChatLine("[RynthAi] Loot by name: the list is empty."); + return; + case "radius": + case "range": + if (!double.TryParse(rest, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double yd)) + { ChatLine($"[RynthAi] Usage: /ra lootname radius <{LootByNameList.MinRadius:0}-{LootByNameList.MaxRadius:0} yards>"); return; } + list.SetRadius(yd); + SaveLootNames(list); + ChatLine($"[RynthAi] Loot by name: radius {list.Radius:0} yd."); + return; + case "list": + case "status": + default: + if (list.IsEmpty) + ChatLine("[RynthAi] Loot by name: nothing on the list. /ra lootname add "); + else + ChatLine($"[RynthAi] Loot by name (radius {list.Radius:0} yd, while looting is on): {string.Join(" | ", list.Names)}"); + return; + } + } + + /// Writes the list back to the settings (the profile saves them like any other setting). + private void SaveLootNames(LootByNameList list) + { + var st = _dashboard?.Settings; + if (st == null) return; + st.LootByNames = list.ToSettingString(); + st.LootByNameRadius = (float)list.Radius; + } + + // ── The work ─────────────────────────────────────────────────────────── + + /// HasLootWork: a named object is in range and worth a use (nothing is changed but the pick). + private bool HasLootNameWork(LegacyUiSettings settings, long now) + { + var list = LootNames; + if (list.IsEmpty || _objectCache == null || _playerId == 0) { _lootNameTargetId = 0; return false; } + if (IsLootingBlockedByPack(settings)) { _lootNameTargetId = 0; return false; } + + // A scan twice a second; between scans the pick stands (it is dropped when it is no longer usable). + if (now - _lootNameScanAt >= LootNameScanMs || _lootNameTargetId == 0) + { + _lootNameScanAt = now; + _lootNameTargetId = PickLootNameTarget(list, now); + } + else if (_lootNameTracker.IsBlocked(_lootNameTargetId, now)) + _lootNameTargetId = 0; + return _lootNameTargetId != 0; + } + + private int PickLootNameTarget(LootByNameList list, long now) + { + var cache = _objectCache!; + int best = 0; + double bestDist = double.MaxValue; + var present = new HashSet(); + foreach (var wo in cache.GetLandscapeObjects()) + { + present.Add(wo.Id); + if (unchecked((uint)wo.Id) == _playerId) continue; + if (!list.MatchesAny(wo.Name)) continue; + if (wo.ObjectClass is AcObjectClass.Player or AcObjectClass.Monster or AcObjectClass.Corpse) continue; + if (wo.Container != 0 || wo.Wielder != 0) continue; + + // Opened (the chest looter has it, or is about to): finished until it is gone. + if (wo.Id == _chestCandidateId || wo.Id == _lootChestId) { _lootNameTracker.MarkDone(wo.Id); continue; } + if (_lootNameTracker.Exhausted(wo.Id, now)) { _lootNameTracker.GiveUp(wo.Id, now); continue; } + if (_lootNameTracker.IsBlocked(wo.Id, now)) continue; + + double d = cache.Distance(unchecked((int)_playerId), wo.Id); + if (d > list.Radius || d >= bestDist) continue; + best = wo.Id; + bestDist = d; + } + _lootNameTracker.Prune(present.Contains); + return best; + } + + /// + /// TickCorpseOpening, nothing claimed or open: uses the picked object when its turn comes, else waits for the + /// client to walk there. True when this tick belongs to it. + /// + private bool TryLootByName(LegacyUiSettings settings, long now) + { + int id = _lootNameTargetId; + if (id == 0 || _targetCorpseId != 0 || _openedContainerId != 0 || _chestCandidateId != 0) + return false; + if (_objectCache?[id] == null) { _lootNameTargetId = 0; return false; } + + if (_activity != BotActivity.Looting) + return true; // the arbiter has not given Looting the tick yet + + PauseNavigationForCorpse(); + if (!_lootNameTracker.CanUse(id, now)) + return true; // walking there / waiting for the server + + string name = _objectCache![id]?.Name ?? string.Empty; + int uses = _lootNameTracker.Uses(id) + 1; + StopCorpseMovement(); + bool sent = Host.UseFor(unchecked((uint)id), "LootName", $"loot by name: '{name}' (try {uses})", UseKind.Asked); + if (sent) + { + _lootNameTracker.NoteUse(id, now); + if (_lootNameLoggedFor != id) + { + _lootNameLoggedFor = id; + LootDiag($"[RynthAi] Loot by name: using 0x{(uint)id:X8} '{name}'."); + } + } + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MetaResume.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MetaResume.cs new file mode 100644 index 0000000..3c62edb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MetaResume.cs @@ -0,0 +1,102 @@ +// RynthAiPlugin.MetaResume.cs - Resume Meta After Reload (2026-11-07): the meta's runtime is saved when +// the plugin unloads in game (a hot reload) and put back when the same character comes back in the same +// client, so the meta carries on where it was instead of starting Default again (a meta that recalls in +// Default recalled on every reload). What goes over, and the checks: Meta/MetaResume.cs. +using System; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.Plugin.RynthAi.MonsterStats; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + private static readonly string MetaResumeDirectory = MetaResumeStore.DefaultDirectory(); + + /// Shutdown (before the session is torn down): saves the running meta for the next copy of RynthAi. + private void SaveMetaResume() + { + if (!_loginComplete || _playerId == 0 || _metaManager == null || _dashboard?.Settings == null) return; + try + { + if (!_dashboard.Settings.ResumeMetaOnReload) + { + MetaResumeStore.Delete(MetaResumeDirectory, Environment.ProcessId, _playerId); + return; + } + var s = new MetaResumeState + { + ProcessId = Environment.ProcessId, + ProcessStartUtcTicks = MonsterStatsStore.ProcessStartTicks, + CharacterId = _playerId, + SavedUtcTicks = DateTime.UtcNow.Ticks, + }; + _metaManager.ExportRuntime(s); + MetaResumeStore.Save(MetaResumeDirectory, s); + Log($"RynthAi: meta saved for the reload: state '{s.State}', macro {(s.MacroRunning ? "on" : "off")}, " + + $"{s.Variables.Count} variable(s), {s.FiredRules.Count} rule(s) fired, call depth {s.CallStack.Count}, " + + $"route {(s.RouteLines.Count > 0 ? $"{s.NavPath} at [{s.NavIndex}]" : "none")}."); + } + catch (Exception ex) + { + Log($"RynthAi: couldn't save the meta for the reload ({ex.GetType().Name}: {ex.Message}); it will start in Default."); + } + } + + /// A real logout: the next login starts the meta in Default, as always. + private void ForgetMetaResume() + { + if (_playerId == 0) return; + try { MetaResumeStore.Delete(MetaResumeDirectory, Environment.ProcessId, _playerId); } catch { } + } + + /// + /// OnLoginComplete, right after the new MetaManager is wired: on a hot reload of this character in this + /// client, with Resume Meta After Reload on and the same meta loaded, puts the saved runtime back. + /// True when it did (the macro's on/off then comes from the save, not Start Macro On Login). + /// + private bool TryResumeMeta() + { + if (_metaManager == null || _dashboard?.Settings == null || _playerId == 0) return false; + var settings = _dashboard.Settings; + try + { + MetaResumeStore.Cleanup(MetaResumeDirectory, DateTime.UtcNow); + if (!IsCarriedOverSession(_playerId)) + { + // A real login (or another character): an old save must never come back later. + MetaResumeStore.Delete(MetaResumeDirectory, Environment.ProcessId, _playerId); + return false; + } + if (!MetaResumeStore.TryLoad(MetaResumeDirectory, Environment.ProcessId, _playerId, out MetaResumeState s)) + return false; + // Read once: the next reload saves afresh. + MetaResumeStore.Delete(MetaResumeDirectory, Environment.ProcessId, _playerId); + if (!settings.ResumeMetaOnReload) + { + Log("RynthAi: hot reload - Resume Meta After Reload is off; the meta starts in Default."); + return false; + } + string signature; + lock (settings.MetaRulesLock) signature = MetaResumeStore.Signature(settings.MetaRules); + string? why = MetaResumeStore.WhyNot(s, Environment.ProcessId, MonsterStatsStore.ProcessStartTicks, _playerId, + settings.CurrentMetaPath ?? "", signature, DateTime.UtcNow); + if (why != null) + { + Log($"RynthAi: hot reload - the meta starts in Default ({why})."); + return false; + } + _metaManager.RestoreRuntime(s); + _patrolOnLoginPending = false; // the meta's own route (or patrol) carries on instead + Log($"RynthAi: hot reload - the meta carries on in state '{s.State}' (macro {(s.MacroRunning ? "on" : "off")}, " + + $"{s.Variables.Count} variable(s), {s.FiredRules.Count} rule(s) already fired, call depth {s.CallStack.Count}, " + + $"route {(s.RouteLines.Count > 0 ? $"at [{s.NavIndex}]" : "none")})."); + Host.WriteToChat($"[RynthAi] Reloaded: the meta carries on in state '{s.State}'.", 1); + return true; + } + catch (Exception ex) + { + Log($"RynthAi: couldn't put the meta back after the reload ({ex.GetType().Name}: {ex.Message}); it starts in Default."); + return false; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MonsterStats.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MonsterStats.cs index 0b64672..f1a391b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MonsterStats.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MonsterStats.cs @@ -14,6 +14,11 @@ // server messages: 0x01B1..0x01B4, asked for in Initialize); spells from the server's spell lines // in chat (CombatLines, one table); kills from the kill notice. Not a player's chat types, never a // player's or a pet's name, and an enchantment line only for a creature (items cast the same line). +// Experience per kill (2026-11-08): the kill notice and the rise of TotalExperience paired by +// KillXpMatcher; the session's rows carry it ("xp", "xk"), and MonsterXpTable learns it per +// character across logins for the Outdoor Hunt's Most XP choice. +// Damage taken by shield and facing (same day): the row's "mstats" also carries monster_damage.txt's +// TS cells (learned across logins, CombatManager.ShieldFacing.cs), sent even with nothing since login. // // Lifetime: from login to logout (per character), kept across a hot reload (MonsterStatsStore), // started over only by /ra mstats reset, the window's Reset or the Damage panel's Reset stats; not @@ -76,6 +81,18 @@ public sealed partial class RynthAiPlugin // Creature names around, by class (refreshed at most every 2 s): who a line's name is. private readonly Dictionary _creatureClassByName = new(StringComparer.OrdinalIgnoreCase); private long _creatureNamesAtMs = long.MinValue / 2; + // Experience per kill (2026-11-08, Tom: "the monster tab should record how much experience you get + // for killing x mob"): each credited kill notice and each rise of TotalExperience go to the + // matcher; a pair adds to the session's row and to the learned table the Outdoor Hunt reads. + private readonly KillXpMatcher _killXp = new(); + private readonly MonsterXpTable _xpTable = new(); + private const uint TotalExperienceQuad = 1; // PropertyInt64.TotalExperience + + /// The learned XP per kill of a kind of monster, kept across logins (MonsterXpTable), or null. + internal double? XpPerKill(string name) => _xpTable.XpPerKill(name); + + /// The learned table (tests). + internal MonsterXpTable XpTableForTests => _xpTable; /// Where the save goes (tests point it at a temp folder). internal string MonsterStatsDirectory { get; set; } = MonsterStatsStore.DefaultDirectory(); @@ -107,16 +124,52 @@ public sealed partial class RynthAiPlugin } /// The kill notice: a kill, and the killing blow by the combat mode it was struck in. - private void NoteMonsterStatsKill(string? notice) + /// The monster credited (null: none, or not in the world). + private string? NoteMonsterStatsKill(string? notice) { - if (!_loginComplete) return; + if (!_loginComplete) return null; KillBlow blow = _currentCombatMode switch { CombatMode.Melee or CombatMode.Missile => KillBlow.Physical, CombatMode.Magic => KillBlow.Spell, _ => KillBlow.None, }; - _monsterStats.OnKill(notice, blow, DateTime.UtcNow, CreatureNameIn); + DateTime now = DateTime.UtcNow; + string? credited = _monsterStats.OnKill(notice, blow, now, CreatureNameIn); + if (credited != null) + { + ApplyKillXp(_killXp.OnKill(credited, now), now); + _corpseTimer.OnKill(credited, CorpseNowMs); // its corpse comes after the death animation (RynthAiPlugin.DeathWait.cs) + } + return credited; + } + + /// The player's TotalExperience, read every tick, for the kills' XP. + private void WatchKillXp(DateTime now) + { + if (!_loginComplete || _playerId == 0 || !Host.HasGetObjectQuadProperty) return; + if (!Host.TryGetObjectQuadProperty(_playerId, TotalExperienceQuad, out long total)) return; + ApplyKillXp(_killXp.OnTotal(total, now), now); + } + + private void ApplyKillXp(IReadOnlyList kills, DateTime now) + { + foreach (KillXp k in kills) + { + _monsterStats.OnKillXp(k.Name, k.Xp, now); + _xpTable.Record(k.Name, k.Xp); + } + } + + /// The learned XP table follows the character's folder (next to monster_damage.txt); "" detaches it. + private void SetXpTableCharacter(string? charFolder) + { + try + { + _xpTable.SaveIfDirty(); + _xpTable.SetCharacter(charFolder); + } + catch (Exception ex) { Host.Log($"[RynthAi] Couldn't read the learned XP per kill: {ex.GetType().Name}: {ex.Message}"); } } /// @@ -207,6 +260,7 @@ public sealed partial class RynthAiPlugin } _monsterStatsSaveAtUtc = now + MonsterStatsSaveInterval; } + WatchKillXp(now); if (_monsterStatsResetWanted) { _monsterStatsResetWanted = false; @@ -251,19 +305,85 @@ public sealed partial class RynthAiPlugin /// A Damage-panel row's "mstats" field and its comma, for the monster named /// (UI/Data/DamageRowStats.cs in the engine reads it); "" for a monster without numbers. Any thread. /// - internal string MonsterStatsJsonFor(string name) + internal string MonsterStatsJsonFor(string name) => MonsterStatsJsonFor(name, Array.Empty(), 0); + + /// + /// with the damage it did to us by shield and facing + /// (monster_damage.txt's TS rows over , the row's kinds, at difficulty + /// ), learned across logins. Sent even when nothing was counted since login. + /// + internal string MonsterStatsJsonFor(string name, uint[] wcids, int tier) { - if (!_monsterStatsByName.TryGetValue(name, out MonsterStatsRow? r) || r.IsEmpty) return string.Empty; - return MonsterStatsJson(r) + ","; + _monsterStatsByName.TryGetValue(name, out MonsterStatsRow? r); + bool session = r != null && !r.IsEmpty; + ShieldTakenCells cells = ShieldTakenFor(wcids, tier); + if (!session && cells.IsEmpty) return string.Empty; + return MonsterStatsJson(session ? r : null, cells) + ","; + } + + /// + /// Damage taken by shield (s = in the off hand, n = none) and facing (f = front, b = behind, + /// u = unknown), added up over a row's kinds: per cell its hits, total damage (the mean is + /// total / hits) and biggest hit. Index = (shield ? 0 : 3) + front 0 / behind 1 / unknown 2. + /// + internal sealed class ShieldTakenCells + { + public static readonly string[] Keys = { "sf", "sb", "su", "nf", "nb", "nu" }; + public readonly int[] Hits = new int[6]; + public readonly double[] Total = new double[6]; + public readonly double[] Max = new double[6]; + public bool IsEmpty { get { foreach (int h in Hits) if (h > 0) return false; return true; } } + } + + internal ShieldTakenCells ShieldTakenFor(uint[] wcids, int tier) + { + var c = new ShieldTakenCells(); + var store = _damageStore; + if (store == null) return c; + foreach (uint w in wcids) + { + if (w == 0) continue; + foreach (var t in store.GetShieldTaken(w, tier)) + { + int i = (t.Shield ? 0 : 3) + (t.Facing == CreatureData.HitFacing.Front ? 0 : t.Facing == CreatureData.HitFacing.Behind ? 1 : 2); + c.Hits[i] += t.Hits; + c.Total[i] += t.Avg * t.Hits; + if (t.Max > c.Max[i]) c.Max[i] = t.Max; + } + } + return c; } /// "mstats":{...} for one monster (the field names DamageRowStats reads). - internal static string MonsterStatsJson(MonsterStatsRow r) + internal static string MonsterStatsJson(MonsterStatsRow r) => MonsterStatsJson(r, null); + + /// + /// "mstats":{...}: the numbers since login (, null = none) and the learned + /// damage taken by shield and facing (, null or empty = none): per cell + /// "h" + key hits, "d" + key total damage, "m" + key biggest hit (whole numbers: the engine reads integers). + /// + internal static string MonsterStatsJson(MonsterStatsRow? r, ShieldTakenCells? shield) { CultureInfo ic = CultureInfo.InvariantCulture; var sb = new StringBuilder(160); - sb.Append("\"mstats\":{") - .Append("\"sw\":").Append(r.Swings.ToString(ic)).Append(",\"ev\":").Append(r.Evaded.ToString(ic)) + sb.Append("\"mstats\":{"); + bool first = true; + if (shield != null && !shield.IsEmpty) + { + for (int i = 0; i < 6; i++) + { + if (shield.Hits[i] == 0) continue; + string k = ShieldTakenCells.Keys[i]; + if (!first) sb.Append(','); + first = false; + sb.Append("\"h").Append(k).Append("\":").Append(shield.Hits[i].ToString(ic)) + .Append(",\"d").Append(k).Append("\":").Append(((long)Math.Round(shield.Total[i], MidpointRounding.AwayFromZero)).ToString(ic)) + .Append(",\"m").Append(k).Append("\":").Append(((long)Math.Round(shield.Max[i], MidpointRounding.AwayFromZero)).ToString(ic)); + } + } + if (r == null) return sb.Append('}').ToString(); + if (!first) sb.Append(','); + sb.Append("\"sw\":").Append(r.Swings.ToString(ic)).Append(",\"ev\":").Append(r.Evaded.ToString(ic)) .Append(",\"sp\":").Append(r.SpellsAtIt.ToString(ic)).Append(",\"rs\":").Append(r.Resisted.ToString(ic)) .Append(",\"ne\":").Append(r.NoEffect.ToString(ic)) .Append(",\"at\":").Append(r.Attacks.ToString(ic)).Append(",\"yev\":").Append(r.YouEvaded.ToString(ic)) @@ -271,6 +391,11 @@ public sealed partial class RynthAiPlugin .Append(",\"yne\":").Append(r.NoEffectOnYou.ToString(ic)) .Append(",\"k\":").Append(r.Kills.ToString(ic)) .Append(",\"dd\":").Append(r.DamageDealt.ToString(ic)).Append(",\"dt\":").Append(r.DamageTaken.ToString(ic)) + // 2026-11-08: the XP of the kills whose rise was seen, and how many (XP/kill = xp / xk). + .Append(",\"xp\":").Append(r.Xp.ToString(ic)).Append(",\"xk\":").Append(r.XpKills.ToString(ic)) + // Same day: the kill-to-corpse time (the death animation), its average in ms and how many were timed. + .Append(",\"cd\":").Append(((long)Math.Round(r.CorpseAvgMs ?? 0, MidpointRounding.AwayFromZero)).ToString(ic)) + .Append(",\"cn\":").Append(r.CorpseKills.ToString(ic)) .Append('}'); return sb.ToString(); } @@ -310,6 +435,9 @@ public sealed partial class RynthAiPlugin { if (_monsterStatsStarted) DeleteMonsterStatsSave(); _monsterStats.Reset(); + _killXp.Reset(); // the next character's XP is a new starting point + _corpseTimer.Reset(); + EndDeathWait("logged out"); _monsterStatsStarted = false; _monsterStatsSavedVersion = -1; _creatureClassByName.Clear(); @@ -322,6 +450,7 @@ public sealed partial class RynthAiPlugin private void ShutdownMonsterStats() { if (_monsterStatsStarted) SaveMonsterStats(DateTime.UtcNow); + try { _xpTable.SaveIfDirty(); } catch { } } // ── Saving (MonsterStatsStore) ─────────────────────────────────────── diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs index 0c7dda5..9a1553e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs @@ -55,6 +55,9 @@ public sealed partial class RynthAiPlugin case "radius": SetHuntSetting(arg, parts.Length > 3 ? parts[3] : ""); break; + case "pick": + SetHuntPick(parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : ""); + break; case "panel": case "settings": ToggleHuntPanel(); @@ -63,11 +66,50 @@ public sealed partial class RynthAiPlugin if (_hunt.Active) StopHunt("stopped", say: true); else StartHunt(); break; default: - ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range | /ra hunt radius "); + ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range | /ra hunt radius | " + HuntPickUsage); break; } } + internal const string HuntPickUsage = "/ra hunt pick [nearest|pack|xp]"; + + /// The setting's words (OutdoorHuntPick 0 / 1 / 2): the short name, and what it does. + internal static (string Name, string Does) HuntPickWords(int pick) => Math.Clamp(pick, 0, 2) switch + { + 1 => ("Biggest pack", "goes for the biggest pack of monsters (a near pack wins unless a farther one is clearly bigger)"), + 2 => ("Most XP", "goes for the pack worth the most experience (the XP per kill it has learned; by size until it knows)"), + _ => ("Nearest", "goes for the nearest monster (the shortest walk)"), + }; + + /// "/ra hunt pick [nearest|pack|xp]": no word says the choice now and the usage; a word sets it and says so. + private void SetHuntPick(string value) + { + var s = _dashboard?.Settings; + if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; } + string v = value.Trim().ToLowerInvariant(); + if (v.Length == 0) + { + var (name, does) = HuntPickWords(s.OutdoorHuntPick); + ReplyOk($"[RynthAi] Outdoor hunt pick: {name}, it {does}. {HuntPickUsage} to change it."); + return; + } + int? pick = v switch + { + "nearest" or "near" or "closest" or "0" => 0, + "pack" or "biggest" or "biggest pack" or "dense" or "densest" or "most dense" or "1" => 1, + "xp" or "exp" or "experience" or "most xp" or "highest experience" or "2" => 2, + _ => null, + }; + if (pick is not int p) + { + ReplyFail($"[RynthAi] Outdoor hunt pick: '{value.Trim()}' isn't one of nearest, pack or xp (it is {HuntPickWords(s.OutdoorHuntPick).Name} now). Usage: {HuntPickUsage}"); + return; + } + s.OutdoorHuntPick = p; + var (n, d) = HuntPickWords(p); + ReplyOk($"[RynthAi] Outdoor hunt pick set: {n}, it {d}." + (_hunt.Active ? " In use from the next monster." : "")); + } + private void SetHuntSetting(string what, string value) { var s = _dashboard?.Settings; @@ -87,7 +129,8 @@ public sealed partial class RynthAiPlugin /// The two distances, each with what it does (Tom set Hunt Radius 2000 and saw no farther hunting: that one is the roaming limit). private static string HuntSettingsText(LegacyUiSettings s) => $"looks for monsters out to {s.OutdoorHuntRange:0} yd (Hunt Range), " - + (s.OutdoorHuntRadius > 0 ? $"and only within {s.OutdoorHuntRadius:0} yd of where it started (Hunt Radius)." : "anywhere it goes (Hunt Radius 0)."); + + (s.OutdoorHuntRadius > 0 ? $"and only within {s.OutdoorHuntRadius:0} yd of where it started (Hunt Radius)." : "anywhere it goes (Hunt Radius 0).") + + $" Pick: {HuntPickWords(s.OutdoorHuntPick).Name}."; // ── The Outdoor Hunt window (Tom 10-23: "we need a small panel to change the settings") ── // Right-click the dashboard's Hunt button, or /ra hunt panel. Render thread: the sliders write the @@ -162,6 +205,21 @@ public sealed partial class RynthAiPlugin s.OutdoorHuntRadius = radius < 1f ? 0f : radius; Wrapped("How far from where it started it may roam. Anywhere: no limit.", Ui.Text); ImGui.Spacing(); + + // Go for (2026-11-08): Nearest, Biggest pack or Most XP (OutdoorHuntPick). + using (Ui.PushFont(RynthUiFont.UiBold14)) ImGui.TextUnformatted("Go for"); + int pick = Math.Clamp(s.OutdoorHuntPick, 0, 2); + float third = (ImGui.GetContentRegionAvail().X - 2 * ImGui.GetStyle().ItemSpacing.X) / 3f; + for (int i = 0; i < 3; i++) + { + if (i > 0) ImGui.SameLine(); + bool chosen = pick == i; + if (chosen) ImGui.PushStyleColor(ImGuiCol.Button, Ui.Accent); + if (ImGui.Button(HuntPickWords(i).Name + "##huntpick" + i, new Vector2(Math.Max(40 * k, third), 0))) s.OutdoorHuntPick = i; + if (chosen) ImGui.PopStyleColor(); + } + Wrapped("It " + HuntPickWords(pick).Does + ".", Ui.Text); + ImGui.Spacing(); Wrapped("Ctrl+click a slider to type a number.", Ui.Mute); } finally { ImGui.PopStyleVar(2); } @@ -327,6 +385,8 @@ public sealed partial class RynthAiPlugin { _hunt.RangeYd = Math.Clamp(s.OutdoorHuntRange, OutdoorHuntRangeMin, OutdoorHuntRangeMax); _hunt.RadiusYd = Math.Clamp(s.OutdoorHuntRadius, 0, OutdoorHuntRadiusMax); + _hunt.Pick = (OutdoorHunt.PickMode)Math.Clamp(s.OutdoorHuntPick, 0, 2); + _hunt.XpLookup ??= XpPerKill; // the learned XP per kill (MonsterXpTable), for Most XP } // Range up to 2000 (Tom 10-23): past what the client knows of (the landblocks round you) it means "every monster in sight". diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs index a095161..2fad092 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs @@ -45,7 +45,8 @@ public sealed partial class RynthAiPlugin kind = ActionPacer.ClassifyUse(host, use.ObjectId, use.DoorOrCorpse); } string who = "RynthAi/" + use.Subsystem + (use.Kind == UseKind.Asked ? " (asked)" : ""); - ActionPacer.Begin(host, kind, use.ObjectId, use.What, who, use.UseDoneSeqBefore); + bool onSelf = use.TargetId != 0 && use.TargetId == player; // a kit on yourself (the pacer's heal grace) + ActionPacer.Begin(host, kind, use.ObjectId, use.What, who, use.UseDoneSeqBefore, onSelf: onSelf); } catch { } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs index a3625fc..6715270 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs @@ -81,7 +81,9 @@ public sealed partial class RynthAiPlugin if (portaling && !_wasPortalingForPacer) { RynthCore.Plugin.Shared.ActionPacer.Forget("portal space"); + RynthCore.Plugin.Shared.ActionPacer.ForgetLootJump(); // out of the air: the teleport moved the character _buffManager?.ForgetPendingWield("portal space"); + _petManager?.OnPortal(); // a pet never follows through a portal } _wasPortalingForPacer = portaling; } @@ -115,8 +117,10 @@ public sealed partial class RynthAiPlugin _combatManager?.ReleaseHeldTurn(); _navigationEngine?.Stop(); RynthCore.Plugin.Shared.ActionPacer.Forget("death"); // the server dropped whatever was open + RynthCore.Plugin.Shared.ActionPacer.ForgetLootJump(); // no landing to wait for after a death _buffManager?.CancelPendingRecall("death"); // no /lifestone or macro restart after the respawn _buffManager?.ForgetPendingWield("death"); // a swap the death cut short is not a failed swap + _petManager?.OnPlayerDeath(); // the pet out is left behind with the corpse StopHunt("died", say: true); // from the lifestone it would walk all the way back to where it started } else diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index c9e148a..3e85a09 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -98,6 +98,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private InventoryManager? _inventoryManager; private SalvageManager? _salvageManager; private ScrollLearner? _scrollLearner; // VTank ReadUnknownScrolls (Loot/ScrollLearner.cs) + private AetheriaUnboxer? _aetheriaUnboxer; // Unbox Aetheria When Idle (Loot/AetheriaUnboxer.cs) private ManaStoneManager? _manaStoneManager; private PetManager? _petManager; private Jumper? _jumper; @@ -309,6 +310,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Release the Monster Editor process handle (if the toggle button // launched one) rather than leaking it on plugin unload/hot-reload. try { _dashboard?.ReleaseMonsterEditorHandle(); } catch { } + try { SaveMetaResume(); } catch { } // a hot reload: the meta carries on where it was long tAfterSettings = Environment.TickCount64; TeardownSession(); long tAfterTeardown = Environment.TickCount64; @@ -326,6 +328,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"); + RynthCore.Plugin.Shared.ActionPacer.ForgetLootJump(); 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 @@ -365,6 +368,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _boostNavNoticeSaid = false; // the Boost Nav Priority notice: once per session // A real logout: the next OnLoginComplete is a fresh login, not a hot reload. ClearInGameMarker(); + ForgetMetaResume(); // and its meta starts in Default ServerPolicy.Forget(); // the next login's [REALM] line says whether the character is in a Thread TeardownSession(); } @@ -468,6 +472,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase while (_engineCommands.TryDequeue(out _)) { } // a fellowship button's command is for this character only // The server drops whatever it was doing for this character at logout. RynthCore.Plugin.Shared.ActionPacer.Forget("logout"); + RynthCore.Plugin.Shared.ActionPacer.ForgetLootJump(); _navigationEngine?.Stop(); _navigationEngine = null; // The dungeon cell graph is a static single-landblock cache; nothing may outlive the session. @@ -493,6 +498,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase Log($"RynthAi: TeardownSession — RadarWallFlush={tFlushMs} ms, RaycastDispose={tRayMs} ms"); _fellowshipTracker?.Dispose(); _fellowshipTracker = null; + _fellowOpenUntil = 0; // a create waiting to be opened was this character's // Pending pvar/gvar writes are throttled; write them before the manager goes, // or 'setpvar[RunDone,1]' then /logout (or a character swap) loses the value. try { _metaManager?.FlushPendingVars(); } catch { } @@ -503,6 +509,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _salvageManager = null; _scrollLearner?.Reset(); _scrollLearner = null; + _aetheriaUnboxer?.Reset(); + _aetheriaUnboxer = null; _manaStoneManager = null; _petManager = null; _buffManager?.Dispose(); @@ -523,6 +531,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // A /ub delay armed before logout must not fire into the next character's session. _delayedCommands.Clear(); ClearPropertyDump(); + // Where the character came into its dungeon: the next login's spot is not an arrival. + ForgetDunArrival(); // The engine drops its appraisal cache at logout; ask for worn gear again next login. _equipIdRequested.Clear(); // Callers save first (Shutdown, OnLogout); after this nothing writes to this @@ -530,6 +540,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _dashboard?.ResetCharacterSession(); // The learned-damage store is per character too: write it, then detach it. try { _damageStore?.SaveIfDirty(); _damageStore?.SetCharacter(string.Empty); } catch { } + SetXpTableCharacter(string.Empty); // the learned XP per kill too (saved first) // The next login may be another server, or a character in real Dereth. try { _creatureStore?.SaveIfDirty(); } catch { } _tier.Reset(); @@ -739,6 +750,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { _buffManager.SetTimerPath(_dashboard.CharFolder); _damageStore?.SetCharacter(_dashboard.CharFolder); + SetXpTableCharacter(_dashboard.CharFolder); lock (_seenMonstersThisSession) _seenMonstersThisSession.Clear(); } @@ -770,7 +782,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager.BuffingWantsTick = () => _buffManager != null && (_buffManager.PendingSpellId != 0 || _buffManager.WantsVitalRecharge || (_dashboard?.Settings?.EnableBuffing == true && _buffManager.NeedsAnyBuff())); - _combatManager.HoldNewTarget = BoostLootHoldsNewTarget; // Boost Loot Priority: one kill, one loot + _combatManager.HoldNewTarget = LootHoldsNewTarget; // Boost Loot Priority: one kill, one loot; the death wait (2026-11-08) + _combatManager.HoldNewTargetWhy = LootHoldWhy; _combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve _combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells _combatManager.SetStaleBusyCallback(OnCombatBusyStale); @@ -803,6 +816,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _missileCraftingManager.SetCharacterSkills(_charSkills); _missileCraftingManager.HoldWhile = () => _combatManager?.AmmoSwapInProgress == true; _missileCraftingManager.FightIsOn = () => FightIsOn(); // optional crafts wait for the fight (RynthAiPlugin.Chores.cs) + _combatManager.AmmoWieldedElsewhereAt = () => _missileCraftingManager?.LastAmmoEquipAt ?? DateTime.MinValue; // no second wield on top of crafting's _dashboard.SetMissileCraftingManager(_missileCraftingManager); _fellowshipTracker?.Dispose(); @@ -826,8 +840,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _metaManager.SetKillClock(_killClock); _metaManager.SetCorpseOpenedCheck(id => _completedCorpses.ContainsKey(id)); _metaManager.SetCombatTargetCount(() => _combatManager?.LastScanPossible ?? -1); + _metaManager.SetLastChestLooted(() => _lastChestLootedId); if (_dashboard != null) _dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot(); + // A hot reload: the meta carries on where it was (Resume Meta After Reload). + TryResumeMeta(); if (_objectCache != null) { @@ -860,6 +877,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _loadedLootProfile?.SalvageCombine ?? _nativeLootProfile?.SalvageCombine; _scrollLearner = CreateScrollLearner(_dashboard.Settings); + _aetheriaUnboxer = CreateAetheriaUnboxer(_dashboard.Settings); // The jumper's own lines are refusals (busy, a bad heading or hold time, no jump hook). _jumper = new Jumper(Host, _dashboard.Settings, ReplyFail); @@ -927,6 +945,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase || (settings.CurrentRoute != null && settings.CurrentRoute.RouteType == NavRouteType.Follow && settings.CurrentRoute.FollowTargetName.Length > 0); + /// + /// The macro was just switched off: does RynthAi stop the character? Only when something of + /// RynthAi's may be moving it: autorun or a motion RynthAi started (MoveAudit), or the + /// server walking it to a target or a corpse for RynthAi (Combat, Looting). A player running + /// by hand who switches the macro off keeps running (the owner, 2026-11-07). + /// + internal static bool MacroStopHalts(bool ownMovementActive, string? botAction) + => ownMovementActive || botAction == "Combat" || botAction == "Looting"; + /// /// The arbiter's WantNav input: the macro runs, navigation is on, and there is a route (or a /// follow) to run. Travelling back to your corpse (RynthNav walks): RynthAi's own route waits. @@ -1151,7 +1178,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["DunPatrolWallDistance"] = (DungeonPatrolOptions.WallClearanceMin, DungeonPatrolOptions.WallClearanceMax), ["DunPatrolLookInSize"] = (DungeonPatrolOptions.LookInRoomMin, DungeonPatrolOptions.LookInRoomMax), ["DunPatrolSightYd"] = (DungeonPatrolOptions.SightMin, DungeonPatrolOptions.SightMax), - ["OutdoorHuntRange"] = (OutdoorHuntRangeMin, OutdoorHuntRangeMax), ["OutdoorHuntRadius"] = (0, OutdoorHuntRadiusMax), + ["OutdoorHuntRange"] = (OutdoorHuntRangeMin, OutdoorHuntRangeMax), ["OutdoorHuntRadius"] = (0, OutdoorHuntRadiusMax), ["OutdoorHuntPick"] = (0, 2), ["T2Speed"] = (0.1, 5), ["T2WalkWithinYd"] = (1, 50), ["T2DistanceTo"] = (0.1, 10), ["T2ReissueMs"] = (100, 10000), ["T2MaxRangeYd"] = (50, 2000), ["T2MaxLandblocks"] = (1, 20), ["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600), ["RebuffIdleMarginMinutes"] = (0, 60), @@ -1512,6 +1539,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (_loginComplete) Guard(TickStep.DataWriteProblems, PostDataWriteProblems); // a save that failed / folder not writable: say so in chat Guard(TickStep.CombatHook, CombatHook.ObserveUseDone); // ctx.last.err: the answer to the hook's last cast Guard(TickStep.DelayedCommands, TickDelayedCommands); // /ub delay + if (_loginComplete) Guard(TickStep.FellowOpen, TickFellowOpen); // Open fellowship on create (RynthAiPlugin.FellowOpen.cs) Guard(TickStep.GameInput, GameInput.Pump); // release keys held for /mt movement | jump | strafe Guard(TickStep.Dashboard, TickDashboard); // the dashboard window's clicks, vitals and prefs Guard(TickStep.EngineCommands, DrainEngineCommands); // fellowship command buttons (RynthCore's Fellowship section) @@ -1572,6 +1600,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { _creatureStore?.SaveIfDirty(); _damageStore?.SaveIfDirty(); + _xpTable.SaveIfDirty(); }); } @@ -1609,6 +1638,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { _buffManager?.SetTimerPath(_dashboard.CharFolder); _damageStore?.SetCharacter(_dashboard.CharFolder); + SetXpTableCharacter(_dashboard.CharFolder); _patrolOnLoginPending = _dashboard.Settings.PatrolOnLogin; if (_miniRemote == null) { @@ -1649,6 +1679,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase }); Guard(TickStep.QuestTracker, () => _questTracker?.Tick()); Guard(TickStep.LocalFeatures, TickLocalFeatures); + Guard(TickStep.RouteJobs, TickDunRoutes); // RynthAi.Routes jobs, one a tick (RynthAiPlugin.DunRoutes.cs) if (diag) Host.Log("[RynthAi] OnTick: after quest tracker"); Guard(TickStep.GiveQueue, DrainGiveQueue); Guard(TickStep.ItemTool, TickItemTool); // the Item Tool: chest looter + Quick give (RynthAiPlugin.ItemTool.cs) @@ -1739,6 +1770,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Healing and buffs: essential, never switched off by its guard (TickGuard). Guard(TickStep.BuffsAndVitals, () => _buffManager?.OnHeartbeat()); if (diag) Host.Log("[RynthAi] OnTick: after buffManager"); + // Combat's wields in flight, checked against the equipment list every tick, ahead of + // the buffing hold below (which skips combat's heartbeat): a weapon that reached the + // hand and was swapped out for the wand by buffing is not a failed wield. + // Reads only, and catches its own faults. + _combatManager?.NoteSwapWieldsSeen(); Guard(TickStep.ReloadBlocker, () => { NoteCarriedOverSessionReady(); @@ -1759,6 +1795,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // minus the peace-mode switch. if (_macroWasRunning && !settings.IsMacroRunning) { + bool ownMovementAtStop = MoveAudit.OwnMovementActive; // before the turn release below clears it _combatManager?.ReleaseHeldTurn(); // A door the nav detour asked for (or one half-way through opening) must // not be opened at the next macro start: TickDoorInteraction only runs @@ -1772,14 +1809,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { int busyBefore = Host.HasGetBusyState ? Host.GetBusyState() : -1; if (Host.HasCancelAttack) Host.CancelAttack(); - if (Host.HasStopCompletely) Host.StopCompletelyBy("MacroStop"); + // Only RynthAi's own movement is stopped: a player running by hand who + // switches the macro off keeps running (the owner, 2026-11-07). + bool halt = MacroStopHalts(ownMovementAtStop, settings.BotAction); + if (halt && Host.HasStopCompletely) Host.StopCompletelyBy("MacroStop"); if (busyBefore > 0 && Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); _busyCount = 0; _busyCountLastIncrementAt = 0; _busyCountBecamePositiveAt = 0; if (_combatManager != null) _combatManager.BusyCount = 0; if (_buffManager != null) _buffManager.BusyCount = 0; - Host.Log($"[RynthAi] Macro stopped: attack cancelled, movement stopped, busy {busyBefore} cleared."); + Host.Log($"[RynthAi] Macro stopped: attack cancelled, " + + (halt ? "movement stopped" : $"movement left alone (nothing of RynthAi's was moving, action {settings.BotAction})") + + $", busy {busyBefore} cleared."); } catch (Exception ex) { Host.Log($"[RynthAi] Macro-stop cleanup failed: {ex.Message}"); } } @@ -1829,7 +1871,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase bool wantBuffRaw = _buffManager != null && (_buffManager.PendingSpellId != 0 || _buffManager.WantsVitalRecharge - || (settings.EnableBuffing && _buffManager.NeedsAnyBuff())); + || (settings.EnableBuffing && _buffManager.NeedsAnyBuff() + && !_buffManager.BuffsWaitForHealth())); // hurt in a fight: combat, not buffs bool wantBuff = wantBuffRaw; // ── Buffing-coma watchdog (STEP 5: decides, no longer falls through) ── @@ -1909,7 +1952,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // combat and no monster is within LootStarveCloseYards. A busy spawn always // has a monster inside MonsterRange, so without this corpses waited until // the area emptied and were usually left behind (2026-10-03). - bool lootStarved = IsLootStarvedTurn(wantLoot, wantCombat); + // An open chest goes first too (it closes when you walk away; RynthAiPlugin.ChestLoot.cs). + bool lootStarved = IsLootStarvedTurn(wantLoot, wantCombat) || IsOpenChestTurn(wantLoot, wantCombat); var inputs = new ArbiterInputs( settings.IsMacroRunning, wantBuff, wantCombat, wantLoot, wantSalvage, wantNav, combatEngaged: engaged, @@ -1917,7 +1961,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase boostLoot: settings.BoostLootPriority, followActive: followActive, lootStarved: lootStarved, - forcedLoot: wantLoot && ForcedLootHolds()); + forcedLoot: wantLoot && ForcedLootHolds(), + deathWait: wantLoot && _deathWaitHeld); // the kill's corpse first (RynthAiPlugin.DeathWait.cs) _activity = _arbiter.Apply(in inputs, settings); _lootStarveTurn = lootStarved && _activity == BotActivity.Looting; // Boost Nav Priority skipped a fight or a corpse: say so, once (RynthAiPlugin.BoostNav.cs). @@ -2109,6 +2154,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase return; // Block combat, nav, looting until crafting finishes } + // Unbox Aetheria When Idle (and /ra aetheria unbox): a mana stone on a coalesced aetheria, + // only at a safe moment (no fight: the server switches to peace for the clap), holding + // the bot still while the clap plays. Ahead of the scroll reader so the two never overlap. + if (inventorySettled && _aetheriaUnboxer != null && TickAetheriaUnbox(settings)) + { + StopNavFor(BotActivity.Idle); + KeepThreatScanFresh(settings); + FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held + ThinkMeta(); + return; + } + // Learn unknown spells (VTank ReadUnknownScrolls): reads a scroll only at a safe // moment, and holds the bot still while the read animation plays (a few seconds). if (inventorySettled && _scrollLearner != null && TickScrollLearner(settings)) @@ -2475,6 +2532,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager?.HandleChatForDamage(text, chatType); _missileCraftingManager?.HandleChat(text); _scrollLearner?.OnChat(text); + _aetheriaUnboxer?.OnChat(text); _metaManager?.HandleChat(text, chatType); _questTracker?.OnChatLine(text); CheckChatForSafetyStops(text); @@ -2490,11 +2548,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Mini Remote stats count every notice, as RynthTracker does (an empty message is still a kill). try { _sessionStats?.OnKillNotification(deathMessage); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats kill"); } - try { NoteMonsterStatsKill(deathMessage); } + string? killed = null; + try { killed = NoteMonsterStatsKill(deathMessage); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats kill"); } if (string.IsNullOrEmpty(deathMessage)) return; _killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone NoteBoostLootKill(); // before combat sees the kill: its next target waits for the corpse + try { StartDeathWait(killed); } // with Looting on: no walking off during the death animation (RynthAiPlugin.DeathWait.cs) + catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "death wait"); } _combatManager?.OnKillNotification(deathMessage); _dashboard?.RecordKill(); // feeds the kills/hour session stat } @@ -2519,6 +2580,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { _objectCache?.OnCreateObject(objectId); _combatManager?.OnEnvironmentObjectCreated(objectId); // spell projectiles for the environment-impact throttle + NoteCorpseCreated(objectId); // a kill's corpse: its death timed, the death wait told (RynthAiPlugin.DeathWait.cs) } catch (Exception ex) { @@ -2534,6 +2596,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _objectCache?.OnDeleteObject(objectId); _combatManager?.OnObjectDeleted(objectId); // D7/D8: free per-id maps + clear cast-wait if it was our target _scrollLearner?.OnObjectDeleted(objectId); // a read scroll is consumed + _aetheriaUnboxer?.OnObjectDeleted(objectId); Loot.T11ItemSupport.Forget(unchecked((int)objectId)); HandleCorpseObjectDeleted(objectId); } @@ -2839,7 +2902,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (wcids.Length > 1) sb.Append("\"wcids\":[").Append(string.Join(",", wcids)).Append("],"); // Its evades and resists both ways since login (RynthAiPlugin.MonsterStats.cs): the line under // the monster on an engine that draws it; an older one ignores the field. - sb.Append(MonsterStatsJsonFor(name)); + // 2026-11-08: with the damage it did to us by shield and facing, learned (TS rows). + sb.Append(MonsterStatsJsonFor(name, wcids, vt)); sb.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',') .Append("\"tiers\":["); @@ -3980,6 +4044,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _buffManager.PrintItemBuffDebug(); else if (parts.Length >= 3 && parts[2].Equals("tiers", StringComparison.OrdinalIgnoreCase)) _buffManager.PrintBuffTierDebug(); + else if (parts.Length >= 3 && parts[2].Equals("unbuffable", StringComparison.OrdinalIgnoreCase)) + { + bool clear = parts.Length >= 4 && parts[3].Equals("clear", StringComparison.OrdinalIgnoreCase); + if (parts.Length >= 4 && !clear) { ReplyFail("[RynthAi] Usage: /ra buffs unbuffable [clear]"); break; } + var lines = _buffManager.UnbuffableCommand(clear); + for (int i = 0; i < lines.Count; i++) { if (i == 0) ReplyOk(lines[i]); else ChatLine(lines[i]); } + } else _buffManager.PrintBuffDebug(); break; @@ -4028,6 +4099,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "buffprofile": HandleBuffProfileCommand(parts); break; case "groundloot": HandleGroundLootCommand(parts); break; case "addnavpt": HandleAddNavPointCommand(); break; + case "lootname": HandleLootNameCommand(parts); break; case "navheading": HandleNavHeadingCommand(parts); break; case "nav": HandleNavCommand(parts); break; case "meta": HandleMetaCommand(parts); break; @@ -4049,6 +4121,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "metamgr": QueueMetaMgrCommand(parts); Reply.Answered(); break; // Meta Manager: applied (and answered) on the next tick case "dunnav": HandleDungeonNavCommand(parts); break; case "dunnav-patrol": HandleDungeonNavPatrolCommand(parts); break; + case "dunroute": HandleDunRouteCommand(parts); break; // RynthAiPlugin.DunRoutes.cs + case "dunpatrol-save": HandleDunPatrolSaveCommand(parts); break; case "hunt": HandleHuntCommand(parts); break; case "hazard": HandleHazardCommand(parts); break; case "lootparse": HandleLootParseCommand(trimmed); break; @@ -4067,6 +4141,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "dumpinv": HandleDumpInventoryCommand(); break; case "combat": HandleCombatStateCommand(); break; case "mstats": HandleMonsterStatsCommand(parts); break; // RynthAiPlugin.MonsterStats.cs + case "aetheria": HandleAetheriaCommand(parts); break; // RynthAiPlugin.Aetheria.cs case "why": HandleWhyCommand(); break; case "ghost": case "ghosts": HandleGhostsCommand(cmd, parts); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiSelfRatings.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiSelfRatings.cs index d322567..a0eb540 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiSelfRatings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiSelfRatings.cs @@ -98,9 +98,9 @@ public sealed partial class RynthAiPlugin string prefix = s?.Prefix ?? "[RynthAi Item] "; int headerType = s?.ChatType ?? 1; int detailType = s == null || s.DetailChatType == MagItemInfoSettings.SameAsHeader ? headerType : s.DetailChatType; - Host.WriteToChat(prefix + lines[0], headerType); + WriteItemInfoLine(prefix + lines[0], headerType); for (int i = 1; i < lines.Count; i++) - Host.WriteToChat(prefix + " " + lines[i], detailType); + WriteItemInfoLine(prefix + " " + lines[i], detailType); } /// One of the player's int properties from the cache (PlayerDescription, else the last identify); 0 when absent. diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthClock.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthClock.cs index 9b82b80..ed5e160 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthClock.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthClock.cs @@ -23,5 +23,12 @@ internal static class RynthClock private static readonly long AnchorStamp = Stopwatch.GetTimestamp(); /// Local time that only moves forward with real time; use for intervals and timeouts. - public static DateTime Now => Anchor + Stopwatch.GetElapsedTime(AnchorStamp); + public static DateTime Now => TestNow?.Invoke() ?? Anchor + Stopwatch.GetElapsedTime(AnchorStamp); + + /// + /// Host tests only (null in the plugin): a simulated clock, so a whole fight (a weapon swap, the + /// casts, the swap back) runs in simulated seconds with every interval and timeout as in play + /// (MissileAmmoSwapTests). Set and restored around one test. + /// + internal static Func? TestNow; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index 084766a..2253e9f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -40,6 +40,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs b/Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs index f1fd14e..c73c3fb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs @@ -17,8 +17,8 @@ namespace RynthCore.Plugin.RynthAi; /// Network hall; wiki.acdreamweave.com/index.php/Threads). 24 retail dungeons are in its rotation and the same /// dungeons can still be walked outside a Thread, so the rule follows the Thread run, not a landblock list. /// Everywhere else on DreamWeave the patrol works as before, and nothing else changes in a Thread: recorded nav -/// routes, going to a dungeon cell (dunnav) and the rest work as they always did. The patrol is built in one -/// place (BuildDunPatrol), which asks here first. +/// routes, going to a dungeon cell (dunnav, /ra dunroute) and the rest work as they always did. The patrol is +/// built in one place (TryBuildDunPatrol: /ra dunnav-patrol and /ra dunpatrol-save), which asks here first. /// /// How a client knows it is in a Thread, from DreamWeave's own chat (our clients' logs, 2026-10-07..10-15): /// "The Thread Gem opens a way into Watery Grotto. It will bring you back 5 more time(s) ..." diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs index c7274ff..f87b1b7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs @@ -78,6 +78,9 @@ public sealed partial class RynthAiPlugin /// internal bool HandleMetaChatCommand(string cmd) => RunAsMeta(() => { + // A meta's own "/fellowship create" goes on to the chat parser; Open fellowship on create + // still opens it (RynthAiPlugin.FellowOpen.cs). + if (IsFellowshipCreateLine(cmd)) NoteFellowshipCreate(); if (cmd.StartsWith("/ub ", StringComparison.OrdinalIgnoreCase)) { var (verb, args) = SplitUbLine(cmd); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs index b9dd984..1d58b8e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs @@ -34,7 +34,10 @@ namespace RynthCore.Plugin.RynthAi.Vendor; /// internal sealed class AutoVendorManager { - public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor"); + public static readonly string DefaultMainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor"); + /// RynthAi\AutoVendor: the main folder, with one folder per server in it. The host tests point it at their scratch folder. + public static string MainProfileDir => MainProfileDirOverride ?? DefaultMainProfileDir; + internal static string? MainProfileDirOverride; public const string ProfileSubfolder = "AutoVendor"; private const long BailMs = 60_000; // UB bailTimer @@ -502,7 +505,9 @@ internal sealed class AutoVendorManager string path = ResolveProfilePath(fromArg ? profileArg : _vendorName + ".utl", fromArg); if (!File.Exists(path)) { - Error($"No vendor profile exists: {path}"); + // Every folder it looked in: the main folder's path alone read as "only the main + // folder is read", with the character and server folders beside it (2026-11-04). + Error($"No vendor profile exists: no {Path.GetFileName(path)} or default.utl in {string.Join(", ", ProfileDirs())}"); Stop(false); return; } @@ -519,6 +524,9 @@ internal sealed class AutoVendorManager } _profilePath = path; + // The vendor's own profile (or one named on /ub autovendor) is the player's word for this + // vendor; default.utl is not (see SellsForNothing). + _profileIsVendors = fromArg || !string.Equals(Path.GetFileName(path), "default.utl", StringComparison.OrdinalIgnoreCase); _failures = 0; _sessionSkip.Clear(); _sellSkipLogged.Clear(); @@ -526,6 +534,13 @@ internal sealed class AutoVendorManager _bailAt = Now(); _nextActionAt = 0; _host.Log($"[RynthAi] AutoVendor: {_vendorName} [0x{merchantId:X8}] profile '{path}' ({_profile.Rules.Count} rules)"); + if (_settings.AutoVendorEnableSelling && TryGetVendor(out VendorView zv, out _) && zv.Id == merchantId && SellsForNothing(zv)) + { + string why = $"{_vendorName} pays nothing for items (buy rate 0): nothing is sold to it with default.utl. " + + $"To hand it items anyway (a storage vault), give it its own profile, {_vendorName}.utl."; + Tool(why); + _host.Log($"[RynthAi] AutoVendor: {why}"); + } BuildIdQueue(); _phase = Phase.Identifying; @@ -555,7 +570,7 @@ internal sealed class AutoVendorManager _idState.Clear(); if (_profile == null || !_settings.AutoVendorEnableSelling || !_host.HasRequestId || !_host.HasHasAppraisalData) return; - if (!TryGetVendor(out VendorView v, out _)) + if (!TryGetVendor(out VendorView v, out _) || SellsForNothing(v)) return; var ctx = NewContext(); @@ -1110,6 +1125,11 @@ internal sealed class AutoVendorManager var result = new List(); if (!_settings.AutoVendorEnableSelling || _profile == null) return result; + if (SellsForNothing(v)) + { + heldBack?.Add($"everything - {_vendorName} pays nothing (buy rate 0) and the profile is default.utl"); + return result; + } uint player = PlayerId(); var packOrder = PackOrder(inv, player); @@ -1369,10 +1389,11 @@ internal sealed class AutoVendorManager double bestDist = double.MaxValue; foreach (var wo in _cache.GetLandscapeObjects()) { - if (wo.ObjectClass != AcObjectClass.Vendor || wo.Id == player) continue; + if (wo.Id == player) continue; string n = (wo.Name ?? string.Empty).ToLowerInvariant(); bool match = lower.Length == 0 || (partial ? n.Contains(lower) : n == lower); if (!match) continue; + if (!IsVendorObject(wo)) continue; // after the name test: the bitfield read costs more double d = _cache.Distance(player, wo.Id); if (best == null || d < bestDist) { best = wo; bestDist = d; } } @@ -1382,7 +1403,42 @@ internal sealed class AutoVendorManager private bool IsVendor(uint id, out WorldObject? wo) { wo = id != 0 ? _cache[unchecked((int)id)] : null; - return wo != null && wo.ObjectClass == AcObjectClass.Vendor; + return wo != null && IsVendorObject(wo); + } + + // The session's profile is the vendor's own (.utl) or one named on /ub autovendor, not default.utl. + private bool _profileIsVendors; + + /// + /// A vendor that pays nothing for what it takes (buy rate 0), met with default.utl: nothing is + /// sold to it. Since the engine trades with zero-rate vendors (a free storage vault), a + /// default.utl's Sell rules, written to turn loot into pyreals, would otherwise hand every + /// matching item to such a vendor for nothing (on stock ACE for 1 pyreal a stack). A vault the + /// player means to fill gets its own profile, which sells (deposits) as written. Buying is not + /// changed: a vendor that charges 0 already ends the session at its first buy ("No vendor price + /// found"). + /// + private bool SellsForNothing(VendorView v) => v.BuyRate == 0f && !_profileIsVendors; + + // PublicWeenieDesc._bitfield BF_VENDOR (retail's ObjectDescriptionFlag.Vendor, which ACE sets too). + private const uint BfVendor = 0x00000200; + + /// + /// A vendor by the server's own vendor flag. The world cache files a vendor by its type (a + /// creature: Npc or Monster) and never as , so + /// /ub vendor open by name, id or "selected" found no vendor at all. The cache class still + /// counts should it ever be Vendor. An engine without the bitfield read: as before. + /// + private bool IsVendorObject(WorldObject wo) + { + if (wo.ObjectClass == AcObjectClass.Vendor) return true; + try + { + return _host.HasGetObjectBitfield + && _host.TryGetObjectBitfield(unchecked((uint)wo.Id), out uint bf) + && (bf & BfVendor) != 0; + } + catch { return false; } } // ── /ub vendor addsell ── @@ -1780,7 +1836,10 @@ internal sealed class AutoVendorManager /// /// First existing file of: character folder, server folder, main folder (the named - /// profile), then default.utl in the same three; else the main-folder path (missing). + /// profile), then default.utl in the same three; else where a new one goes (missing): + /// the server folder, or the main folder while the server's name isn't known. UB says + /// the main folder there; ours made the dashboard's Edit save every new profile in the + /// main folder, beside the server folders it had just made (2026-11-04). /// A name typed on /ub autovendor also tries name + ".utl". /// public string ResolveProfilePath(string profileName, bool addUtlGuess) @@ -1801,8 +1860,9 @@ internal sealed class AutoVendorManager string p = SafeCombine(dir, "default.utl"); if (p.Length > 0 && File.Exists(p)) return p; } - string fallback = SafeCombine(MainProfileDir, profileName); - return fallback.Length > 0 ? fallback : Path.Combine(MainProfileDir, "default.utl"); + string home = ServerDir() ?? MainProfileDir; + string fallback = SafeCombine(home, profileName); + return fallback.Length > 0 ? fallback : Path.Combine(home, "default.utl"); } /// Character, server, main - UB's order. @@ -1812,12 +1872,73 @@ internal sealed class AutoVendorManager string charFolder = _charFolder() ?? string.Empty; if (!string.IsNullOrEmpty(charFolder)) dirs.Add(Path.Combine(charFolder, ProfileSubfolder)); - if (_host.HasGetWorldName && _host.TryGetWorldName(out string world) && !string.IsNullOrWhiteSpace(world)) - dirs.Add(Path.Combine(MainProfileDir, Sanitize(world))); + string? server = ServerDir(); + if (server != null) dirs.Add(server); dirs.Add(MainProfileDir); return dirs; } + /// AutoVendor\<server>, or null while the server's name isn't known. + private string? ServerDir() + => _host.HasGetWorldName && _host.TryGetWorldName(out string world) && !string.IsNullOrWhiteSpace(world) + ? Path.Combine(MainProfileDir, Sanitize(world)) + : null; + + /// + /// The profile pickers' list (the Loot Editor's): the .utl files in + /// (ProfileDirs: character, server, main), in that order, then the other servers' folders, + /// each marked by its folder: "AutoVendor (character): ", "AutoVendor (<server>): ", + /// "AutoVendor: " for the main folder. The picker listed the main folder and its server + /// folders as one tree and never the character folder (2026-11-04). + /// + public static List<(string Path, string Display)> ListProfiles(IReadOnlyList dirs) + { + var list = new List<(string Path, string Display)>(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + string main = FullPath(MainProfileDir); + var folders = new List(); + foreach (string d in dirs ?? Array.Empty()) + if (!string.IsNullOrWhiteSpace(d)) folders.Add(d); + if (!folders.Exists(d => SameDir(d, main))) folders.Add(MainProfileDir); + try + { + if (Directory.Exists(MainProfileDir)) + { + var others = new List(Directory.GetDirectories(MainProfileDir)); + others.Sort(StringComparer.OrdinalIgnoreCase); + folders.AddRange(others); + } + } + catch { } + + foreach (string dir in folders) + { + string full = FullPath(dir); + if (full.Length == 0 || !seen.Add(full)) continue; + string label = SameDir(full, main) ? "AutoVendor: " + : SameDir(Path.GetDirectoryName(full) ?? string.Empty, main) ? $"AutoVendor ({Path.GetFileName(full)}): " + : "AutoVendor (character): "; + try + { + if (!Directory.Exists(full)) continue; + var files = new List(Directory.GetFiles(full, "*.utl")); + files.Sort(StringComparer.OrdinalIgnoreCase); + foreach (string f in files) list.Add((f, label + Path.GetFileName(f))); + } + catch { } + } + return list; + } + + private static string FullPath(string dir) + { + try { return dir.Length == 0 ? string.Empty : Path.TrimEndingDirectorySeparator(Path.GetFullPath(dir)); } + catch { return string.Empty; } + } + + private static bool SameDir(string a, string b) + => string.Equals(FullPath(a), FullPath(b), StringComparison.OrdinalIgnoreCase); + /// Create the per-character and per-server folders so players can see where profiles go (UB Init). public void EnsureProfileFolders() { diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Clock/DayNightWindow.cs b/Plugins/RynthCore.Plugin.RynthDefective/Clock/DayNightWindow.cs new file mode 100644 index 0000000..fe76b70 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDefective/Clock/DayNightWindow.cs @@ -0,0 +1,155 @@ +// ============================================================================ +// RynthDefective - Clock/DayNightWindow.cs +// The Day/Night timer (2026-11-04, a request on 2026-11-01: a tiny window with +// the real minutes until the next day/night change): a sun or a moon, then +// "Night in 23m" / "Day in 4m 10s", and the hour's name when there's room. +// "—" until the player is in world (the clock can't be read before). +// Plugins/Shared/DerethClock.cs has the math; RynthCore hosts the frameless +// window (plugin API v90) and remembers where it is. +// +// anywhere drag to move; Ctrl+wheel: bigger or smaller (30-250%); +// right-click: hide it (/rdef daynight, the bar button, or +// Settings > UI > Toolbar show it again). +// +// AC's render thread; reads the view the tick built (DayNightView) and counts +// the seconds down from when it was read, so the seconds move every frame. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthDefective.ShortcutBar; +using RynthCore.Plugin.Shared; +using RynthCore.Plugin.Shared.RynthUi; +using RynthCore.PluginSdk; +using static RynthCore.Plugin.Shared.RynthUi.RynthUi; + +namespace RynthCore.Plugin.RynthDefective.Clock; + +/// The clock as the tick read it; Ready = in world with a usable reading. +internal sealed record DayNightView(bool Ready, DerethNow Now, long ReadAtMs) +{ + public static readonly DayNightView NotReady = new(false, default, 0); + + /// The real seconds to the change at (counted down from the reading). + public double SecondsLeft(long nowMs) => Math.Max(0, Now.SecondsToChange - (nowMs - ReadAtMs) / 1000.0); +} + +internal sealed class DayNightWindow +{ + public const string Title = "Day/Night"; + public const string NotInWorld = "—"; + + private readonly RynthCoreHost _host; + private float _k = 1f, _r = 1f; + + // The label, made again only when the second it shows changes (no string every frame). + private long _shownSecond = -1; + private bool _shownDay; + private string _label = NotInWorld; + + public DayNightWindow(RynthCoreHost host) => _host = host; + + private float Px(float v) => v * _k; + private float Fs(ImFontPtr f) => f.FontSize * _r; + + private void Scale() + { + float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f); + int pct = _host.PanelScale(Title); + _k = pct > 0 ? pct / 100f : fontK; + _r = _k / fontK; + } + + private const float Pad = 5, RowH = 16, Mark = 14, Gap = 4, Radius = 4; + + private static readonly uint SunColor = Argb(0xFFF2C14E), MoonColor = Argb(0xFFB8C7F0); + private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f)); + + /// Draws the timer into the host's window; returns the height it needs (pixels). Render thread. + public float Draw(DayNightView v) + { + Scale(); + uint bg = Color(RynthUiColor.Background), line = Color(RynthUiColor.Hairline); + uint text = Color(RynthUiColor.Text), faint = Color(RynthUiColor.Faint); + + Vector2 origin = ImGui.GetCursorScreenPos(); + origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y)); + float width = MathF.Floor(ImGui.GetContentRegionAvail().X); + float pad = Px(Pad), rowH = Px(RowH); + float height = MathF.Ceiling(2 * pad + rowH); + if (width < 30) return height; + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + Vector2 max = origin + new Vector2(width, height); + dl.AddRectFilled(origin, max, A(bg, 0.94f), Px(Radius)); + dl.AddRect(origin, max, line, Px(Radius)); + + // The whole window is the drag surface. + ImGui.SetCursorScreenPos(origin); + ImGui.InvisibleButton("##daynight_drag", new Vector2(width, height)); + _host.PanelDragWithLastItem(); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close); + bool hot = ImGui.IsItemHovered(); + + long nowMs = Environment.TickCount64; + double left = v.Ready ? v.SecondsLeft(nowMs) : 0; + string label = Label(v, left); + + // The sun by day, the moon at night (an engine from before the moon was baked: a star). + Vector2 at = origin + new Vector2(pad, pad); + string icon = !v.Ready || v.Now.IsDay ? RynthIcons.Sun : HasGlyph(RynthIcons.Moon) ? RynthIcons.Moon : RynthIcons.Star; + uint iconColor = !v.Ready ? faint : v.Now.IsDay ? SunColor : MoonColor; + PanelButtonsWindow.DrawIcon(dl, icon, at, new Vector2(Px(Mark), rowH), Px(13), iconColor); + + ImFontPtr nf = Font(RynthUiFont.NarrowBold11), sf = Font(RynthUiFont.Narrow9); + float tx = at.X + Px(Mark) + Px(Gap), right = origin.X + width - pad; + float lw = nf.CalcTextSizeA(Fs(nf), float.MaxValue, 0f, label).X; + dl.AddText(nf, Fs(nf), new Vector2(MathF.Round(tx), MathF.Round(at.Y + (rowH - Fs(nf)) * 0.5f)), v.Ready ? text : faint, label); + + // The hour's name, right-aligned, only when it fits whole. + if (v.Ready) + { + string hour = v.Now.HourName; + float hw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, hour).X; + if (tx + lw + Px(8) + hw <= right) + dl.AddText(sf, Fs(sf), new Vector2(MathF.Round(right - hw), MathF.Round(at.Y + (rowH - Fs(sf)) * 0.5f)), faint, hour); + } + + if (hot) SafeImGui.SetItemTooltip(Tip(v, left)); + + ImGui.SetCursorScreenPos(origin); + ImGui.Dummy(new Vector2(width, height)); + return height; + } + + private string Label(DayNightView v, double left) + { + if (!v.Ready) { _shownSecond = -1; return _label = NotInWorld; } + long second = (long)Math.Ceiling(left); + if (second != _shownSecond || v.Now.IsDay != _shownDay) + { + _shownSecond = second; + _shownDay = v.Now.IsDay; + _label = DerethClock.Label(v.Now, left); + } + return _label; + } + + /// The tooltip (built only while hovered). + internal static string Tip(DayNightView v, double left) + { + const string help = "A Dereth day is 2 h 7 min of real time: 63.5 minutes of day, then 63.5 of night.\n" + + "Drag to move; Ctrl+wheel: bigger or smaller; right-click: hide (/rdef daynight)."; + if (!v.Ready) return "Day or night in Dereth, and the real minutes until it changes. Shown once you're in the world.\n" + help; + TimeSpan t = TimeSpan.FromSeconds(Math.Ceiling(left)); + string until = t.TotalMinutes >= 1 ? $"{(int)t.TotalMinutes} min {t.Seconds} s" : $"{t.Seconds} s"; + return $"{(v.Now.IsDay ? "Day" : "Night")} now ({v.Now.HourName}). {v.Now.Next} comes at {v.Now.NextHourName}, in {until} of real time.\n" + help; + } + + /// Whether the engine's atlas has (an icon baked after this engine was built isn't). + private static unsafe bool HasGlyph(string glyph) + { + ImFontPtr font = Font(RynthUiFont.Ui18); + return font.NativePtr != null && ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]) != null; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs b/Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs index 35bcbbd..95eee36 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs @@ -67,18 +67,39 @@ internal sealed class DefSession // ── Using ─────────────────────────────────────────────────────────────── - /// The slot's button or key: use what it holds. Returns what to tell the player when nothing could be queued. - public string? UseSlot(int slotNumber) + // A slot is on bar 0 (the main bar's own slots: DefData.Slots, /rdef use N) or on extra bar 2-4 + // (2026-11-04, ExtraBar: slots of its own, no keys). The slot actions below take the bar last. + + /// "Slot 3", or "Bar 2 slot 3" for an extra bar's. + public static string SlotName(int bar, int slotNumber) => bar == 0 ? $"Slot {slotNumber}" : $"Bar {bar} slot {slotNumber}"; + + /// The slot list slot of is in; what is wrong when there is none. + private string? Locate(int bar, int slotNumber, out List slots) { - if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}."; - DefSlot slot = Data.Slots[slotNumber - 1]; + slots = Data.Slots; + if (bar == 0) return slotNumber < 1 || slotNumber > DefSettings.SlotsMax ? $"There is no slot {slotNumber}." : null; + ExtraBar? b = Data.Extra(bar); + if (b == null) return $"There is no Shortcuts bar {bar}."; + slots = b.Slots; + return slotNumber < 1 || slotNumber > ExtraBar.SlotsMax ? $"Bar {bar} has no slot {slotNumber}." : null; + } + + /// The slot's button or key: use what it holds. Returns what to tell the player when nothing could be queued. + public string? UseSlot(int slotNumber, int bar = 0) + { + if (Locate(bar, slotNumber, out List slots) is { } problem) return problem; + DefSlot slot = slots[slotNumber - 1]; + string source = (bar == 0 ? "slot " : $"bar {bar} slot ") + slotNumber; if (slot.IsSpell) { - Use.Request(UseRequest.Cast(slot.SpellId, slot.SpellLabel, "slot " + slotNumber, Now())); + Use.Request(UseRequest.Cast(slot.SpellId, slot.SpellLabel, source, Now())); return null; } - if (slot.Item == null) return $"Slot {slotNumber} is empty. Set it from the bar (Edit slots) or with /rdef set {slotNumber}."; - Use.Request(new UseRequest(slot.Item, null, slot.Mode, "slot " + slotNumber, Now())); + if (slot.Item == null) + return bar == 0 + ? $"Slot {slotNumber} is empty. Set it from the bar (Edit slots) or with /rdef set {slotNumber}." + : $"{SlotName(bar, slotNumber)} is empty: drag an item onto it, or right-click it to put the selected item or one of your spells there."; + Use.Request(new UseRequest(slot.Item, null, slot.Mode, source, Now())); return null; } @@ -107,21 +128,21 @@ internal sealed class DefSession // ── Slots ─────────────────────────────────────────────────────────────── - public string SetFromSelected(int slotNumber) + public string SetFromSelected(int slotNumber, int bar = 0) { uint sel = SelectedId(); if (sel == 0) return "Select the item in the game first (click it in your pack), then set the slot."; CarriedItem? it = FindById(sel); if (it == null) return "The selected object isn't in your pack, so it can't go in a slot."; - return SetSlot(slotNumber, it); + return SetSlot(slotNumber, it, bar); } /// An item dragged onto the slot (its object id). - public string SetFromId(int slotNumber, uint objectId) + public string SetFromId(int slotNumber, uint objectId, int bar = 0) { CarriedItem? it = FindById(objectId); if (it == null) return "That isn't in your pack, so it can't go in a slot."; - return SetSlot(slotNumber, it); + return SetSlot(slotNumber, it, bar); } public string SetFromName(int slotNumber, string name) @@ -131,17 +152,17 @@ internal sealed class DefSession return SetSlot(slotNumber, it); } - public string SetSlot(int slotNumber, CarriedItem it) + public string SetSlot(int slotNumber, CarriedItem it, int bar = 0) { - if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}."; - DefSlot slot = Data.Slots[slotNumber - 1]; + if (Locate(bar, slotNumber, out List slots) is { } problem) return problem; + DefSlot slot = slots[slotNumber - 1]; slot.Item = ItemRef.From(it); slot.SpellId = 0; slot.SpellName = string.Empty; slot.Mode = UseMode.Auto; Save(); ItemKind kind = ItemKinds.Classify(it); - return $"Slot {slotNumber}: {it.FullName} ({UseModes.Describe(ItemKinds.DefaultAction(kind))} when pressed)."; + return $"{SlotName(bar, slotNumber)}: {it.FullName} ({UseModes.Describe(ItemKinds.DefaultAction(kind))} when pressed)."; } /// @@ -149,9 +170,9 @@ internal sealed class DefSession /// known spells; the engine can't tell which spell is selected in the game's spellbook). Refused for /// a spell the character doesn't know, when the spellbook can be read. /// - public string SetSpell(int slotNumber, uint spellId) + public string SetSpell(int slotNumber, uint spellId, int bar = 0) { - if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}."; + if (Locate(bar, slotNumber, out List slots) is { } problem) return problem; if (spellId == 0) return "That isn't a spell."; IReadOnlyList known = KnownSpells(); SpellInfo? spell = null; @@ -159,9 +180,9 @@ internal sealed class DefSession if (s.Id == spellId) { spell = s; break; } if (spell == null && known.Count > 0) return $"You don't know {SpellTable.Name(spellId)}, so it can't go in a slot."; SpellInfo info = spell ?? (SpellTable.TryGet(spellId, out SpellInfo t) ? t : new SpellInfo(spellId, SpellTable.Name(spellId), false, false)); - Data.Slots[slotNumber - 1] = new DefSlot { SpellId = spellId, SpellName = info.Name }; + slots[slotNumber - 1] = new DefSlot { SpellId = spellId, SpellName = info.Name }; Save(); - return $"Slot {slotNumber}: {info.Name} ({SpellTargeting.Describe(info)} when pressed)."; + return $"{SlotName(bar, slotNumber)}: {info.Name} ({SpellTargeting.Describe(info)} when pressed)."; } /// /rdef spell <slot> <name>: one of the character's spells by what the player typed. @@ -178,12 +199,12 @@ internal sealed class DefSession return SetSpell(slotNumber, found[0].Id); } - public string ClearSlot(int slotNumber) + public string ClearSlot(int slotNumber, int bar = 0) { - if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}."; - Data.Slots[slotNumber - 1] = new DefSlot(); + if (Locate(bar, slotNumber, out List slots) is { } problem) return problem; + slots[slotNumber - 1] = new DefSlot(); Save(); - return $"Slot {slotNumber} cleared."; + return $"{SlotName(bar, slotNumber)} cleared."; } /// Swaps slot with (1-based), as moving one place. @@ -226,6 +247,9 @@ internal sealed class DefSession bool changed = false; foreach (DefSlot s in Data.Slots) if (s.Item != null && ItemMatcher.Maintain(s.Item, items)) changed = true; + foreach (ExtraBar bar in Data.ExtraBars) + foreach (DefSlot s in bar.Slots) + if (s.Item != null && ItemMatcher.Maintain(s.Item, items)) changed = true; foreach (ItemRef f in Data.Favourites) if (ItemMatcher.Maintain(f, items)) changed = true; foreach (ItemRef r in Data.Recent) @@ -364,6 +388,55 @@ internal sealed class DefSession return string.IsNullOrWhiteSpace(name) ? null : new ItemRef { Id = id, Name = name.Trim() }; } + // ── Extra bars (2026-11-04) ───────────────────────────────────────────── + + /// Adds an extra Shortcuts bar (the lowest free number). : its number, 0 when none could be. + public string AddBar(out int added) + { + ExtraBar? bar = Data.AddExtraBar(); + added = bar?.Number ?? 0; + if (bar == null) + return $"There are {ExtraBar.Max} extra Shortcuts bars already, as many as there can be (the engine hosts 8 windows for a plugin, " + + $"and RynthDefective draws 5 others). Remove one first: /rdef bars remove <{ExtraBar.FirstNumber}-{ExtraBar.LastNumber}>."; + Save(); + return $"Shortcuts bar {bar.Number} added, {bar.SlotCount} slots: drag items from your pack onto it, or right-click a slot for " + + "the selected item or one of your spells. It shows in a moment; drag its title to move it."; + } + + /// Removes extra bar ; its slots are forgotten. + public string RemoveBar(int number) + { + if (number == 1) return "Bar 1 is the Shortcuts bar itself: it can't be removed (/rdef hides it)."; + ExtraBar? bar = Data.Extra(number); + if (bar == null) return $"There is no Shortcuts bar {number}. {DescribeBars()}"; + int filled = bar.Filled; + Data.RemoveExtraBar(number); + Save(); + return $"Shortcuts bar {number} removed" + (filled > 0 ? $" ({filled} of its slots held an item or a spell: they are forgotten)." : "."); + } + + /// How many slots extra bar shows. + public string SetBarSlots(int number, int count) + { + ExtraBar? bar = Data.Extra(number); + if (bar == null) return $"There is no Shortcuts bar {number}. {DescribeBars()}"; + bar.SlotCount = Math.Clamp(count, ExtraBar.SlotsMin, ExtraBar.SlotsMax); + Save(); + return $"Shortcuts bar {number} shows {bar.SlotCount} slot{(bar.SlotCount == 1 ? "" : "s")}" + + (count != bar.SlotCount ? $" ({ExtraBar.SlotsMin} to {ExtraBar.SlotsMax})." : "."); + } + + /// The extra bars in a line (/rdef bars). + public string DescribeBars() + { + if (Data.ExtraBars.Count == 0) + return "No extra Shortcuts bars. Add one: Add a shortcut bar in the bar's right-click menu, or /rdef bars add."; + var parts = new List(Data.ExtraBars.Count); + foreach (ExtraBar b in Data.ExtraBars) + parts.Add($"{b.Number} ({b.SlotCount} slots, {b.Filled} set)"); + return $"Extra Shortcuts bars: {string.Join(", ", parts)}; {ExtraBar.Max - Data.ExtraBars.Count} more can be added."; + } + // ── Favourites ────────────────────────────────────────────────────────── public string ToggleFavourite(ItemRef r) diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs index 54ff30c..c910512 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs @@ -3,21 +3,34 @@ using System; namespace RynthCore.Plugin.RynthDefective.Model; internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses, - Quantity, Split, Give, Buy } + Quantity, Split, Give, Buy, DayNight, Bars, Shortcuts } /// /// A parsed "/rdef ..." line. Use: (1-based) or (an item name). /// The quantity box's verbs (qty, split, give, buy): (null = the box's number) and /// (split: the pack; buy: the item's name). +/// Bars (the extra Shortcuts bars): what to do (list, add, remove, slots, show), +/// the bar's number, its slots. +/// Shortcuts ("shortcuts clearbusy on|off"): "on", "off" or "" (say what it is). /// -internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "", QtyAmount? Amount = null); +internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "", QtyAmount? Amount = null, int Count = 0); internal static class DefCommandParser { public const string Usage = "/rdef [use | set [item name] | spell | clear | bind | unbind | " + "weapons [search] | fav | slots | list | status | settings | panels (the game panel buttons) | selection | corpses [clear] | " - + "qty [number|max|half] | split [number] [into ] | give [number] | buy [number] [item name]]"; + + "bars [add | remove | slots | show ] | shortcuts clearbusy [on|off] | " + + "qty [number|max|half] | split [number] [into ] | give [number] | buy [number] [item name] | daynight [show|hide]]"; + + public const string DayNightUsage = "Usage: /rdef daynight [show|hide], e.g. /rdef daynight show (the Day/Night timer: real minutes to the next dawn or dusk)"; + + public const string ClearBusyUsage = + "Usage: /rdef shortcuts clearbusy on|off, e.g. /rdef shortcuts clearbusy on (a press held only by a stuck busy count clears it first; off by default)"; + + public const string BarsUsage = + "Usage: /rdef bars [list | add | remove | slots | show ], e.g. /rdef bars add or /rdef bars remove 2 " + + "(the extra Shortcuts bars are 2-4)"; public const string QtyUsage = "Usage: /rdef qty , e.g. /rdef qty 25 (the Selection window's number)"; public const string SplitUsage = "Usage: /rdef split [number|max|half] [into ], e.g. /rdef split 25 or /rdef split 25 into Sack"; @@ -44,6 +57,15 @@ internal static class DefCommandParser case "selection": case "target": // "/rdef selection 0x80001234": select that object (a test hook for the Selection window). return new DefCommand(DefVerb.Selection, Text: rest); + // The Day/Night timer (2026-11-04): Text "show", "hide" or "" (toggle). + case "daynight": + return rest.ToLowerInvariant() switch + { + "" or "toggle" => new DefCommand(DefVerb.DayNight), + "show" or "on" or "open" => new DefCommand(DefVerb.DayNight, Text: "show"), + "hide" or "off" or "close" => new DefCommand(DefVerb.DayNight, Text: "hide"), + _ => Fail($"'{rest}' isn't show or hide. {DayNightUsage}"), + }; case "fav": case "favourite": case "favorite": return new DefCommand(DefVerb.Favourite); case "weapons": case "weapon": case "picker": return new DefCommand(DefVerb.Weapons, Text: rest); case "use": case "wield": case "equip": @@ -79,6 +101,22 @@ internal static class DefCommandParser return int.TryParse(rest, out int count) && count >= DefSettings.SlotsMin && count <= DefSettings.SlotCountMax ? new DefCommand(DefVerb.Slots, count) : Fail($"How many slots? {DefSettings.SlotsMin} to {DefSettings.SlotCountMax}, e.g. /rdef slots 10"); + // The extra Shortcuts bars (2026-11-04, ExtraBar). + case "bars": + return ParseBars(rest); + // Shortcuts clear a stuck busy state (2026-11-04, DefSettings.ClearStuckBusy). + case "shortcuts": + { + string[] words = rest.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (words.Length == 0 || words.Length > 2 || !words[0].Equals("clearbusy", StringComparison.OrdinalIgnoreCase)) return Fail(ClearBusyUsage); + if (words.Length == 1) return new DefCommand(DefVerb.Shortcuts, Text: ""); + return words[1].ToLowerInvariant() switch + { + "on" or "true" or "1" or "yes" => new DefCommand(DefVerb.Shortcuts, Text: "on"), + "off" or "false" or "0" or "no" => new DefCommand(DefVerb.Shortcuts, Text: "off"), + _ => Fail($"'{words[1]}' isn't on or off. {ClearBusyUsage}"), + }; + } // The quantity box (2026-10-30, Quantity/QuantityController.cs). case "qty": case "quantity": case "amount": { @@ -110,6 +148,32 @@ internal static class DefCommandParser } } + /// "/rdef bars ...": list (alone too), add, remove N, slots N count, show N. + private static DefCommand ParseBars(string rest) + { + string[] words = rest.Split(' ', StringSplitOptions.RemoveEmptyEntries); + string sub = words.Length == 0 ? "list" : words[0].ToLowerInvariant(); + int n = 0; + bool hasBar = words.Length >= 2 && int.TryParse(words[1], out n); + switch (sub) + { + case "list": case "ls": + return words.Length <= 1 ? new DefCommand(DefVerb.Bars, Text: "list") : Fail(BarsUsage); + case "add": case "new": + return words.Length <= 1 ? new DefCommand(DefVerb.Bars, Text: "add") : Fail(BarsUsage); + case "remove": case "delete": case "rm": + return hasBar && words.Length == 2 ? new DefCommand(DefVerb.Bars, n, "remove") : Fail("Which bar? e.g. /rdef bars remove 2 (/rdef bars lists them)"); + case "show": case "hide": case "toggle": + return hasBar && words.Length == 2 ? new DefCommand(DefVerb.Bars, n, "show") : Fail("Which bar? e.g. /rdef bars show 2 (shows it, or hides it when it shows)"); + case "slots": + return hasBar && words.Length == 3 && int.TryParse(words[2], out int count) && count >= ExtraBar.SlotsMin && count <= ExtraBar.SlotsMax + ? new DefCommand(DefVerb.Bars, n, "slots", Count: count) + : Fail($"How many slots? Usage: /rdef bars slots , e.g. /rdef bars slots 2 12 ({ExtraBar.SlotsMin} to {ExtraBar.SlotsMax})"); + default: + return Fail($"'{words[0]}' isn't something /rdef bars does. {BarsUsage}"); + } + } + /// The slot number a hotkey runs for slot (1-based). public static string UseCommand(int slot) => "/rdef use " + slot; diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs index 21193ec..526286c 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs @@ -117,6 +117,17 @@ internal sealed class DefSettings /// /rdef qty, split, give and buy work either way. /// public bool QuantityBox = true; + /// + /// Shortcuts clear a stuck busy state (2026-11-04, a player's ask): a press held only by the client's + /// busy count (nothing of ours or RynthAi's in flight, no gesture, no "You're too busy" just now) resets + /// the count as RynthAi's /ra clearbusy does (the engine's ForceResetBusyCount), then goes, once per + /// press (Use/BusyGate.cs BusyClearRule). Off (the default, and what a file from before reads as): a + /// reset also zeroes actions the server hasn't answered that RynthDefective can't see (the game's own + /// clicks and toolbar keys, another plugin's), and each late answer then takes the count below zero; + /// RynthAi stopped resetting it for that on 2026-10-06. The leftover rules let a press through anyway + /// within 4 s; this only saves those seconds. + /// + public bool ClearStuckBusy; public bool BarOpen; public bool PickerOpen; @@ -131,6 +142,69 @@ internal sealed class DefSettings } } +/// +/// One of the extra Shortcuts bars (2026-11-04): a window of its own ("Shortcuts 2" ... "Shortcuts 4", +/// the engine remembers its place, size and whether it shows), with slots of its own, filled as the +/// main bar's own slots are (drag an item from the pack, the selected item, one of your spells) and +/// clicked the same way. Its slots have no keys: the keys are the main bar's ("/rdef use N"). +/// Per character, with the main bar's slots. +/// +/// At most : the engine hosts at most 8 windows per plugin (SectionManifest.MaxWindows, +/// later ones are dropped without a word) and RynthDefective already draws 4 (the bar, Game Panels, +/// Selection, Corpses). 4 extra bars of up to 24 slots are 96 slots more than the game's 18 and the +/// main bar's 24. +/// +internal sealed class ExtraBar +{ + public const int Max = 3, FirstNumber = 2, LastNumber = FirstNumber + Max - 1; + public const int SlotsMin = 1, SlotsMax = 24, DefaultSlots = 10; + + /// Its number, - (the main bar is 1): its window's title and id. + public int Number; + /// How many slots it shows (-). + public int SlotCount = DefaultSlots; + /// Always entries: fewer slots hides them, it doesn't forget them. + public List Slots = NewSlots(); + + public ExtraBar(int number) => Number = number; + + /// "Shortcuts 2": the window's title (the engine's key for its place, size and open state). + public static string TitleOf(int number) => "Shortcuts " + number.ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// "window:bar2": the surface its window draws (RynthPluginRenderEmbed). + public static string SurfaceOf(int number) => "window:bar" + number.ToString(System.Globalization.CultureInfo.InvariantCulture); + + public static bool ValidNumber(int number) => number >= FirstNumber && number <= LastNumber; + + public string Title => TitleOf(Number); + + /// How many of its slots (all of them, shown or not) hold an item or a spell. + public int Filled + { + get + { + int n = 0; + foreach (DefSlot s in Slots) if (!s.Empty) n++; + return n; + } + } + + public static List NewSlots() + { + var l = new List(SlotsMax); + for (int i = 0; i < SlotsMax; i++) l.Add(new DefSlot()); + return l; + } + + /// Pads or cuts the slot list to the fixed length; the count into its range. + public void Fix() + { + while (Slots.Count < SlotsMax) Slots.Add(new DefSlot()); + if (Slots.Count > SlotsMax) Slots.RemoveRange(SlotsMax, Slots.Count - SlotsMax); + SlotCount = Math.Clamp(SlotCount, SlotsMin, SlotsMax); + } +} + /// One character's slots, favourites, recent weapons and settings. internal sealed class DefData { @@ -142,6 +216,31 @@ internal sealed class DefData public List Favourites = new(); /// The weapons wielded from the picker or a slot, newest first. public List Recent = new(); + /// The extra Shortcuts bars (2026-11-04), by number; at most , none by default. + public List ExtraBars = new(); + + /// Extra bar , or null. + public ExtraBar? Extra(int number) => ExtraBars.Find(b => b.Number == number); + + /// + /// Adds an extra bar with the lowest free number (a removed bar's number is used again, so its window + /// comes back where it was). Returns it, or null at . + /// + public ExtraBar? AddExtraBar() + { + for (int n = ExtraBar.FirstNumber; n <= ExtraBar.LastNumber; n++) + { + if (Extra(n) != null) continue; + var bar = new ExtraBar(n); + ExtraBars.Add(bar); + ExtraBars.Sort((a, b) => a.Number.CompareTo(b.Number)); + return bar; + } + return null; + } + + /// Removes extra bar and forgets its slots. False when there is none. + public bool RemoveExtraBar(int number) => ExtraBars.RemoveAll(b => b.Number == number) > 0; public static List NewSlots() { @@ -177,7 +276,7 @@ internal sealed class DefData if (Recent.Count > MaxRecent) Recent.RemoveRange(MaxRecent, Recent.Count - MaxRecent); } - /// The slot (1-based number) that holds an item of this identity, or 0. + /// The slot (1-based number) of the main bar's own slots that holds an item of this identity, or 0. public int SlotOf(ItemRef r) { for (int i = 0; i < Slots.Count; i++) diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs index a53ba5d..8a947c3 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs @@ -18,6 +18,21 @@ internal static class DefReplies _ => (false, $"This RynthCore has no {title} window (it needs plugin API v90)."), }; + /// + /// /rdef daynight [show|hide]: the Day/Night timer after it ( as ), + /// then the time now when the clock can be read (null = not in world): "Day/Night timer shown. Night now + /// (Evensong); day in 23m of real time." + /// + public static (bool Ok, string Text) DayNight(int state, DerethNow? now) + { + string time = now is { } n + ? $" {(n.IsDay ? "Day" : "Night")} now ({n.HourName}); {n.Next.ToLowerInvariant()} in {DerethClock.Countdown(n.SecondsToChange)} of real time." + : ""; + return state < 0 + ? (false, "This RynthCore has no Day/Night timer window (it needs plugin API v90)." + time) + : (true, CommandReply.Shown("Day/Night timer", state == 1) + time); + } + /// A slot's use started (the result shows on the bar; a problem is said in chat). public static string UseSlot(DefSlot slot, int number) => slot.IsSpell ? $"Casting {slot.SpellLabel} (slot {number})." @@ -45,6 +60,13 @@ internal static class DefReplies return false; } + /// "/rdef shortcuts clearbusy [on|off]": what the option is now. + public static string ClearBusy(bool on) => on + ? "Shortcuts clear a stuck busy state: on. A press held only by the client's busy count (nothing of RynthDefective's or " + + "RynthAi's in flight, no animation, no 'too busy' from the server just now) resets the count as /ra clearbusy does, then goes." + : "Shortcuts clear a stuck busy state: off (the default). A busy count left by a death or a login holds a press for up to 4 s, " + + "then is ignored; the count itself is left alone."; + /// "/rdef selection stack" with no stack in the pack. public const string NoStack = "No stack in your pack to select."; diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs index 855b976..e761706 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs @@ -69,35 +69,58 @@ internal sealed class DefStore st.WeaponsButtonOnBar = Bool(s, "weaponsButtonOnBar", st.WeaponsButtonOnBar); // missing (a file from before 2026-10-29): off st.IndependentBar = Bool(s, "independentBar", st.IndependentBar); // missing (a file from before 2026-10-27): off st.QuantityBox = Bool(s, "quantityBox", st.QuantityBox); // missing (a file from before 2026-10-30): on + st.ClearStuckBusy = Bool(s, "clearStuckBusy", st.ClearStuckBusy); // missing (a file from before 2026-11-04): off st.BarOpen = Bool(s, "barOpen", st.BarOpen); st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen); st.Clamp(); } - if (root.TryGetProperty("slots", out JsonElement slots) && slots.ValueKind == JsonValueKind.Array) - { - int i = 0; - foreach (JsonElement e in slots.EnumerateArray()) - { - if (i >= DefSettings.SlotsMax) break; - DefSlot slot = d.Slots[i++]; - if (e.ValueKind != JsonValueKind.Object) continue; - slot.Item = ParseRef(e, "item"); - int mode = Int(e, "mode", 0); - slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto; - // A spell (2026-10-28; a file from before has none): only in a slot without an item. - if (slot.Item == null && e.TryGetProperty("spell", out JsonElement sp) && sp.ValueKind == JsonValueKind.Object) - { - slot.SpellId = UInt(sp, "id"); - slot.SpellName = slot.SpellId != 0 ? Str(sp, "name") : string.Empty; - } - } - } + if (root.TryGetProperty("slots", out JsonElement slots)) ParseSlots(slots, d.Slots); ParseRefs(root, "favourites", d.Favourites, DefData.MaxFavourites); ParseRefs(root, "recent", d.Recent, DefData.MaxRecent); + + // The extra bars (2026-11-04; a file from before has none): a bad entry, a number out of range or + // seen before, is skipped; at most ExtraBar.Max. + if (root.TryGetProperty("extraBars", out JsonElement bars) && bars.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement e in bars.EnumerateArray()) + { + if (d.ExtraBars.Count >= ExtraBar.Max) break; + if (e.ValueKind != JsonValueKind.Object) continue; + int number = Int(e, "number", 0); + if (!ExtraBar.ValidNumber(number) || d.Extra(number) != null) continue; + var bar = new ExtraBar(number) { SlotCount = Int(e, "slotCount", ExtraBar.DefaultSlots) }; + if (e.TryGetProperty("slots", out JsonElement bs)) ParseSlots(bs, bar.Slots); + bar.Fix(); + d.ExtraBars.Add(bar); + } + d.ExtraBars.Sort((a, b) => a.Number.CompareTo(b.Number)); + } return d; } + /// A "slots" array into (fixed length: the extra entries are ignored). + private static void ParseSlots(JsonElement slots, List into) + { + if (slots.ValueKind != JsonValueKind.Array) return; + int i = 0; + foreach (JsonElement e in slots.EnumerateArray()) + { + if (i >= into.Count) break; + DefSlot slot = into[i++]; + if (e.ValueKind != JsonValueKind.Object) continue; + slot.Item = ParseRef(e, "item"); + int mode = Int(e, "mode", 0); + slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto; + // A spell (2026-10-28; a file from before has none): only in a slot without an item. + if (slot.Item == null && e.TryGetProperty("spell", out JsonElement sp) && sp.ValueKind == JsonValueKind.Object) + { + slot.SpellId = UInt(sp, "id"); + slot.SpellName = slot.SpellId != 0 ? Str(sp, "name") : string.Empty; + } + } + } + private static void ParseRefs(JsonElement root, string name, List into, int max) { if (!root.TryGetProperty(name, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return; @@ -168,26 +191,12 @@ internal sealed class DefStore w.WriteBoolean("weaponsButtonOnBar", s.WeaponsButtonOnBar); w.WriteBoolean("independentBar", s.IndependentBar); w.WriteBoolean("quantityBox", s.QuantityBox); + w.WriteBoolean("clearStuckBusy", s.ClearStuckBusy); w.WriteBoolean("barOpen", s.BarOpen); w.WriteBoolean("pickerOpen", s.PickerOpen); w.WriteEndObject(); - w.WriteStartArray("slots"); - foreach (DefSlot slot in d.Slots) - { - w.WriteStartObject(); - if (slot.Item != null) WriteRef(w, "item", slot.Item); - else if (slot.SpellId != 0) - { - w.WriteStartObject("spell"); - w.WriteNumber("id", slot.SpellId); - w.WriteString("name", slot.SpellLabel); - w.WriteEndObject(); - } - w.WriteNumber("mode", (int)slot.Mode); - w.WriteEndObject(); - } - w.WriteEndArray(); + WriteSlots(w, d.Slots); w.WriteStartArray("favourites"); foreach (ItemRef r in d.Favourites) WriteRefValue(w, r); @@ -195,11 +204,42 @@ internal sealed class DefStore w.WriteStartArray("recent"); foreach (ItemRef r in d.Recent) WriteRefValue(w, r); w.WriteEndArray(); + + w.WriteStartArray("extraBars"); + foreach (ExtraBar bar in d.ExtraBars) + { + w.WriteStartObject(); + w.WriteNumber("number", bar.Number); + w.WriteNumber("slotCount", bar.SlotCount); + WriteSlots(w, bar.Slots); + w.WriteEndObject(); + } + w.WriteEndArray(); w.WriteEndObject(); } return Encoding.UTF8.GetString(ms.ToArray()) + "\n"; } + private static void WriteSlots(Utf8JsonWriter w, List slots) + { + w.WriteStartArray("slots"); + foreach (DefSlot slot in slots) + { + w.WriteStartObject(); + if (slot.Item != null) WriteRef(w, "item", slot.Item); + else if (slot.SpellId != 0) + { + w.WriteStartObject("spell"); + w.WriteNumber("id", slot.SpellId); + w.WriteString("name", slot.SpellLabel); + w.WriteEndObject(); + } + w.WriteNumber("mode", (int)slot.Mode); + w.WriteEndObject(); + } + w.WriteEndArray(); + } + private static void WriteRef(Utf8JsonWriter w, string name, ItemRef r) { w.WritePropertyName(name); diff --git a/Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs index e0772e2..1589698 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/PluginExports.cs @@ -88,7 +88,7 @@ public static unsafe class PluginExports catch { return IntPtr.Zero; } } - /// The bar's and the panel buttons' window bodies ("window:bar", "window:panels"; ":popout" when popped out). 1 drawn, 0 not ready, -2 failed. + /// The bar's and the panel buttons' window bodies ("window:bar", "window:panels", the extra bars' "window:bar2" ...; ":popout" when popped out). 1 drawn, 0 not ready, -2 failed. [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) { @@ -106,6 +106,8 @@ public static unsafe class PluginExports else if (name == RynthDefectivePlugin.PanelsSurface) result = plugin.RenderPanels(out wantH); else if (name == RynthDefectivePlugin.SelectionSurface) result = plugin.RenderSelection(out wantH); else if (name == RynthDefectivePlugin.CorpsesSurface) result = plugin.RenderCorpses(out wantH); + else if (name == RynthDefectivePlugin.DayNightSurface) result = plugin.RenderDayNight(out wantH); + else if (RynthDefectivePlugin.TryExtraSurface(name, out int extra)) result = plugin.RenderExtraBar(extra, popped, out wantH); else return 0; if (result != 1) return result; if (wantWidth != null) *wantWidth = width; diff --git a/Plugins/RynthCore.Plugin.RynthDefective/README.md b/Plugins/RynthCore.Plugin.RynthDefective/README.md index cd6c5d5..899ac07 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/README.md +++ b/Plugins/RynthCore.Plugin.RynthDefective/README.md @@ -35,6 +35,17 @@ all three go. game's toolbar and its keys are not changed. Turning it off shows the game's 18 first again, RynthDefective's slot 1 at 19. +* **More bars** (up to 4: *Shortcuts 2* to *Shortcuts 5*): *Add a shortcut bar* in the bar's right-click menu + (or Defective Settings, or `/rdef bars add`) opens another bar in a window of its own, to put anywhere: drag + its title to move it, its edge to fit more slots in a row. Each has its own slots (10 to start, 1-24 with the + edit button's - / + or the settings' slider), filled as the bar's own slots are: drag an item from the pack + onto a slot, or right-click it for *Put the selected item here* or *Put a spell here...*. A click uses the + item one-touch, as on the bar. Their slots have no keys (keys go on the bar's own slots). The engine remembers + each bar's place, size and whether it shows; the slots are kept per character with the others. They have no + RynthCore bar button: the Shortcuts bar's right-click menu shows or hides each, and removes one (*Remove a + bar*, or *Remove this bar* in that bar's own menu; a bar that holds something asks once more, and its slots + are forgotten). Why 4: the engine hosts at most 8 windows for a plugin, and RynthDefective draws 4 others. + On an older engine the bar below is a script window, with its settings under its *Settings* button. ## What it does @@ -108,6 +119,16 @@ number (the game gets no keys while the box has the keyboard) or pick 1, 10, 100 `/rdef buy` (below). It doesn't need the Inventory panel or RynthInventory. * Retail AC kept this number in its toolbar; RynthCore's *Hide retail toolbar* hides it with the toolbar. +## The Day/Night timer + +A one-row window (its RynthCore bar button is the sun; `/rdef daynight [show|hide]`; Settings > UI > Toolbar > +*Day/Night timer*): a sun by day, a moon at night, and the **real** time until the next change, "Night in 23m", +"Day in 4m 10s" (seconds from 10 minutes down), with the Dereth hour's name when there is room. A Dereth day is +16 hours of 476.25 s, 2 h 7 min of real time: day (Dawnsong to Warmtide-and-Half) and night (Evensong to +Foredawn-and-Half) are 63.5 real minutes each; the clock and calendar are RynthAi's meta expressions' +(`getisday`, `getminutesuntilnight`). It shows "—" until you're in the world: the game clock isn't read before. +`/rdef daynight` also says the time in chat. Drag it anywhere; Ctrl+wheel resizes it; right-click hides it. + ## Busy, combat and RynthAi * One item action at a time: a request waits while the client is busy, a gesture animates, RynthAi waits on @@ -118,8 +139,18 @@ number (the game gets no keys while the box has the keyboard) or pick 1, 10, 100 up with nothing in flight after a death, a login or an interrupted action (and RynthAi's "waiting on the server" with it). A count that hasn't moved for 4 s with nothing of RynthDefective's in flight, a gesture that has "animated" for 4 s, or RynthAi's bit on for 5.5 s holds nothing (logged once); only a count above - that leftover holds again. RynthDefective never resets the count itself (the engine owns it). If the server - really is busy it answers "You're too busy" and the use is tried once more a second later. + that leftover holds again. RynthDefective doesn't reset the count itself (the engine owns it) unless you turn + on the option below. If the server really is busy it answers "You're too busy" and the use is tried once more + a second later. +* **Shortcuts clear a stuck busy state** (Defective Settings, `/rdef shortcuts clearbusy on|off`; per character, + off by default): a press held only by the client's busy count, with nothing of RynthDefective's in flight or + unanswered, no animation, RynthAi with no action of its own out, and no "You're too busy" from the server in + the last 5 s, resets the count as RynthAi's `/ra clearbusy` does (the engine's busy-count reset; not its + *stop moving*), then the item is used: once per press, logged. Off by default because a reset also wipes + actions the server hasn't answered that RynthDefective can't see (a click in the game's own windows, its own + toolbar keys, another plugin's), and their late answers then take the count below zero (the engine repairs + that after 2 s); RynthAi stopped resetting the count for that reason. With it off a leftover holds a press + for at most 4 s. * A key pressed in portal space (a death's too) is not kept for later: it says so. * After a wield from a fighting stance the stance follows the weapon (wand: magic, melee weapon: melee, launcher with ammunition in hand: missile) once the character is still. At peace you stay at peace. A bow @@ -142,11 +173,15 @@ number (the game gets no keys while the box has the keyboard) or pick 1, 10, 100 /rdef weapons [search] show the weapon picker /rdef fav make the selected weapon a favourite (or take it out) /rdef slots how many slots the script-window bar shows (1-24) +/rdef bars the extra Shortcuts bars; /rdef bars add | remove <2-5> | slots <2-5> <1-24> | + show <2-5> (show or hide it) +/rdef shortcuts clearbusy [on|off] a press held only by a stuck busy count clears it first (off by default) /rdef qty [n | max | half] the quantity box's number (alone: what it is and what it's of) /rdef split [n] [into ] split n (or the box's number) off the selected stack; pack: main, a side pack's name, or open (the chest you have open) /rdef give [n] give n of the selected stack to the last player or NPC you selected /rdef buy [n] [item name] buy n of the selected vendor item (or the one named) from the open vendor +/rdef daynight [show | hide] show / hide the Day/Night timer (alone: toggle); says the time now /rdef list | status | help ``` @@ -156,8 +191,10 @@ slot N is bar slot 18+N, or bar slot N when the bar is independent of the game's ## Settings Shortcuts bar: the windows shown, the quantity box under the selection (on by default), independent of the -game's toolbar, slot picture size, allow weapon swaps under RynthAi, picker row icon size. Script-window bar: slots (1-24), slots per row, button size, picker row -icon size, item icons on/off, counts and keys on/off, allow weapon swaps under RynthAi. Kept per character +game's toolbar, slot picture size, shortcuts clear a stuck busy state (off by default), the extra bars (shown, +slots, remove, add), allow weapon swaps under RynthAi, picker row icon size. Script-window bar: slots (1-24), slots per row, button size, picker row +icon size, item icons on/off, counts and keys on/off, allow weapon swaps under RynthAi, shortcuts clear a stuck +busy state. Kept per character with the slots, favourites and recent weapons in `\RynthDefective\characters\_.json`. diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj b/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj index a6a9ec9..f406de2 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj +++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj @@ -31,7 +31,7 @@ pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). --> 66 - Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window (with a quantity box: split, give or buy that many): one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings. + Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window (with a quantity box: split, give or buy that many), and a Day/Night timer: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings. @@ -44,6 +44,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.Bar.cs b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.Bar.cs index e80d3d8..367d87c 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.Bar.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.Bar.cs @@ -14,11 +14,21 @@ // // The tick: the window's clicks (queued from the render thread), the snapshot // it draws (4 times a second while it shows). +// +// Extra bars (2026-11-04, Model/DefData.cs ExtraBar): up to 4 more windows, +// "Shortcuts 2" ... "Shortcuts 4", each with slots of its own (no AC slots, no +// keys), drawn by the same ShortcutBarWindow class. They are in the manifest +// while a character with them is logged in (the engine hosts them then, and +// remembers each one's place, size and open state by its title); a new one +// is opened once the engine hosts it (the manifest is read every ~2 s). No +// RynthCore bar button: the Shortcuts bar's menu and the settings show them. // ============================================================================ using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Globalization; +using RynthCore.Plugin.RynthDefective.Items; using RynthCore.Plugin.RynthDefective.Model; using RynthCore.Plugin.RynthDefective.ShortcutBar; using RynthCore.Plugin.Shared.RynthUi; @@ -39,6 +49,26 @@ public sealed partial class RynthDefectivePlugin : IBarActions private long _barDrawnMs = long.MinValue / 2, _nextBarBuildMs; private int _barFailures; + // The extra bars, by number - ExtraBar.FirstNumber. + private readonly ShortcutBarWindow?[] _extraWindows = new ShortcutBarWindow?[ExtraBar.Max]; // render thread + private readonly ExtraBarActions?[] _extraActions = new ExtraBarActions?[ExtraBar.Max]; // render thread + private readonly BarSnapshot[] _extraViews = NotReadyViews(); // tick writes, render reads (Volatile) + private readonly long[] _extraDrawnMs = { long.MinValue / 2, long.MinValue / 2, long.MinValue / 2, long.MinValue / 2 }; + private readonly int[] _extraFailures = new int[ExtraBar.Max]; + /// The extra bars the manifest lists (the logged-in character's); empty when nobody is. Tick writes, any thread reads. + private volatile int[] _extraNumbers = Array.Empty(); + /// Extra bars to open once the engine hosts their window, and until when to try (tick only). + private readonly Dictionary _openWhenHosted = new(); + private const long OpenWhenHostedMs = 8000; + private long _nextOpenTryMs; + + private static BarSnapshot[] NotReadyViews() + { + var a = new BarSnapshot[ExtraBar.Max]; + Array.Fill(a, BarSnapshot.NotReady); + return a; + } + /// The engine has v90's shortcuts and frameless windows: the new bar, not the script window one. internal bool UsesShortcutBar => Host.HasShortcuts && Host.HasFramelessWindows; @@ -69,7 +99,62 @@ public sealed partial class RynthDefectivePlugin : IBarActions "\",\"icon\":\"\\u" + ((int)RynthIcons.Skull[0]).ToString("X4", CultureInfo.InvariantCulture) + "\",\"width\":290,\"height\":80,\"minWidth\":140,\"minHeight\":30,\"bar\":true,\"edgeToEdge\":true," + "\"chrome\":\"none\",\"fitHeight\":true,\"scale\":\"draw\"}"; - return "{\"version\":1,\"windows\":[" + bar + panels + selection + corpses + "]}"; + // Day or night and the real minutes to the change (a bar button of its own; one row, any width). + string dayNight = ",{\"id\":\"daynight\",\"title\":\"" + Clock.DayNightWindow.Title + "\",\"surface\":\"" + DayNightSurface + + "\",\"icon\":\"\\u" + ((int)RynthIcons.Sun[0]).ToString("X4", CultureInfo.InvariantCulture) + + "\",\"width\":150,\"height\":26,\"minWidth\":70,\"minHeight\":20,\"bar\":true,\"edgeToEdge\":true," + + "\"chrome\":\"none\",\"fitHeight\":true,\"scale\":\"draw\"}"; + // The extra bars (the engine hosts at most 8 windows for a plugin: these five and up to three of them). + string extras = ""; + foreach (int n in _extraNumbers) + extras += ",{\"id\":\"bar" + n.ToString(CultureInfo.InvariantCulture) + "\",\"title\":\"" + ExtraBar.TitleOf(n) + "\",\"surface\":\"" + + ExtraBar.SurfaceOf(n) + "\",\"icon\":\"\\u" + ((int)RynthIcons.Lightning[0]).ToString("X4", CultureInfo.InvariantCulture) + + "\",\"width\":300,\"height\":80,\"minWidth\":90,\"minHeight\":40,\"bar\":false,\"edgeToEdge\":true," + + "\"chrome\":\"none\",\"fitHeight\":true,\"scale\":\"draw\"}"; + return "{\"version\":1,\"windows\":[" + bar + panels + selection + corpses + dayNight + extras + "]}"; + } + + /// "window:bar2" ... "window:bar4": an extra bar's surface, and its number. + internal static bool TryExtraSurface(string surface, out int number) + { + number = 0; + const string prefix = "window:bar"; + if (surface.Length != prefix.Length + 1 || !surface.StartsWith(prefix, StringComparison.Ordinal)) return false; + number = surface[^1] - '0'; + return ExtraBar.ValidNumber(number); + } + + /// The extra bars' numbers for the manifest, from the logged-in character's data (empty when nobody is). + private void RefreshExtraNumbers() + { + if (!_identityKnown) { _extraNumbers = Array.Empty(); return; } + var list = _session.Data.ExtraBars; + var a = new int[list.Count]; + for (int i = 0; i < a.Length; i++) a[i] = list[i].Number; + _extraNumbers = a; + for (int i = 0; i < ExtraBar.Max; i++) + if (Array.IndexOf(a, i + ExtraBar.FirstNumber) < 0) System.Threading.Volatile.Write(ref _extraViews[i], BarSnapshot.NotReady); + } + + /// RynthPluginRenderEmbed "window:barN" (an extra bar). 1 drawn, 0 not ready, -2 failed (three in a row). Render thread. + internal int RenderExtraBar(int number, bool popped, out float wantHeight) + { + wantHeight = 0; + if (!UsesShortcutBar || !ExtraBar.ValidNumber(number)) return 0; + int i = number - ExtraBar.FirstNumber; + System.Threading.Volatile.Write(ref _extraDrawnMs[i], Environment.TickCount64); + try + { + _extraWindows[i] ??= new ShortcutBarWindow(Host, _extraActions[i] ??= new ExtraBarActions(this, number), ExtraBar.TitleOf(number)); + wantHeight = _extraWindows[i]!.Draw(System.Threading.Volatile.Read(ref _extraViews[i]), popped); + _extraFailures[i] = 0; + return 1; + } + catch (Exception ex) + { + Host.Log($"[RynthDefective] shortcut bar {number} draw failed: {ex.GetType().Name}: {ex.Message}"); + return ++_extraFailures[i] >= 3 ? -2 : 0; + } } /// RynthPluginRenderEmbed "window:panels". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread. @@ -120,11 +205,50 @@ public sealed partial class RynthDefectivePlugin : IBarActions catch (Exception ex) { Host.Log($"[RynthDefective] bar action failed: {ex.GetType().Name}: {ex.Message}"); } } if (!UsesShortcutBar || !_identityKnown) return; + TickOpenBars(now); + if (now < _nextBarBuildMs) return; bool shown = now - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000; - if (!shown || now < _nextBarBuildMs) return; + int[] extras = _extraNumbers; + bool extraShown = false; + foreach (int n in extras) extraShown |= ExtraShown(n, now); + if (!shown && !extraShown) return; _nextBarBuildMs = now + 250; - _barBuilder ??= new BarSnapshotBuilder(Host); - _barView = _barBuilder.Build(_session, _session.Items(), now); + IReadOnlyList items = _session.Items(); + if (shown) + { + _barBuilder ??= new BarSnapshotBuilder(Host); + _barView = _barBuilder.Build(_session, items, now); + } + foreach (int n in extras) + if (ExtraShown(n, now)) + System.Threading.Volatile.Write(ref _extraViews[n - ExtraBar.FirstNumber], BarSnapshotBuilder.BuildExtra(_session, n, items, Host.HasCastSpell)); + } + + /// Extra bar 's window was drawn in the last 2 s. + private bool ExtraShown(int number, long now) => + ExtraBar.ValidNumber(number) && now - System.Threading.Volatile.Read(ref _extraDrawnMs[number - ExtraBar.FirstNumber]) < 2000; + + /// Any extra bar shows (the inventory is kept fresh for it). + private bool AnyExtraShown(long now) + { + foreach (int n in _extraNumbers) if (ExtraShown(n, now)) return true; + return false; + } + + /// Opens the extra bars just added (or asked for) once the engine hosts their windows. + private void TickOpenBars(long now) + { + if (_openWhenHosted.Count == 0 || now < _nextOpenTryMs) return; + _nextOpenTryMs = now + 250; + List? done = null; + foreach ((int n, long until) in _openWhenHosted) + { + bool open = Host.SetPanelOpen(ExtraBar.TitleOf(n), RynthPanelOpen.Open) >= 0; + if (!open && now < until) continue; + if (!open) Host.Log($"[RynthDefective] Shortcuts bar {n}: the engine didn't host its window within {OpenWhenHostedMs / 1000} s; not opened."); + (done ??= new List()).Add(n); + } + if (done != null) foreach (int n in done) _openWhenHosted.Remove(n); } private void QueueBar(Action action) @@ -132,6 +256,143 @@ public sealed partial class RynthDefectivePlugin : IBarActions if (_barActions.Count < 32) _barActions.Enqueue(action); } + // ── Extra bars: add, remove, show (the bars' menus, the settings window and /rdef bars) ── + + /// Adds an extra bar; it opens once the engine hosts it. Tick only. + private void AddExtraBar() + { + string text = _session.AddBar(out int n); + if (n == 0) { PrintFail(text); return; } + RefreshExtraNumbers(); + _openWhenHosted[n] = Environment.TickCount64 + OpenWhenHostedMs; + _nextBarBuildMs = 0; + Print(text); + } + + /// Removes extra bar (its window leaves with the next manifest read). Tick only. + private void RemoveExtraBar(int number) + { + bool had = _session.Data.Extra(number) != null; + string text = _session.RemoveBar(number); + if (!had) { PrintFail(text); return; } + _openWhenHosted.Remove(number); + Host.SetPanelOpen(ExtraBar.TitleOf(number), RynthPanelOpen.Close); // at once: the manifest drops it at its next read + RefreshExtraNumbers(); + _nextBarBuildMs = 0; + Print(text); + } + + /// /rdef bars ...: list, add, remove N, slots N count, show N. Every one answers. + private void RunBarsCommand(DefCommand c) + { + if (!UsesShortcutBar) + { + PrintFail("This RynthCore can't show more Shortcuts bars (they are plugin windows: plugin API v90)."); + return; + } + switch (c.Text) + { + case "add": + AddExtraBar(); + break; + case "remove": + RemoveExtraBar(c.Slot); + break; + case "slots": + if (_session.Data.Extra(c.Slot) == null) PrintFail(_session.SetBarSlots(c.Slot, c.Count)); + else { Print(_session.SetBarSlots(c.Slot, c.Count)); _nextBarBuildMs = 0; } + break; + case "show": + if (c.Slot == 1) { Answer(DefReplies.Window("Shortcuts bar", Host.SetPanelOpen(ShortcutBarWindow.Title, RynthPanelOpen.Toggle))); break; } + if (_session.Data.Extra(c.Slot) == null) { PrintFail($"There is no Shortcuts bar {c.Slot}. {_session.DescribeBars()}"); break; } + int state = Host.SetPanelOpen(ExtraBar.TitleOf(c.Slot), RynthPanelOpen.Toggle); + if (state >= 0) Answer(DefReplies.Window($"Shortcuts bar {c.Slot}", state)); + else + { + // Not hosted yet (just added, or the manifest not read since the login): open it when it is. + _openWhenHosted[c.Slot] = Environment.TickCount64 + OpenWhenHostedMs; + Print($"Shortcuts bar {c.Slot} shows in a moment."); + } + break; + default: + Print(_session.DescribeBars()); + break; + } + } + + /// + /// What an extra bar's window asks (render thread: queue only): its own slots through the session's + /// bar-aware slot actions; no keys; the rest is the Shortcuts bar's. + /// + private sealed class ExtraBarActions : IBarActions + { + private readonly RynthDefectivePlugin _p; + private readonly int _bar; + + public ExtraBarActions(RynthDefectivePlugin plugin, int bar) + { + _p = plugin; + _bar = bar; + } + + private DefSession S => _p._session; + + public void Use(int number) => _p.QueueBar(() => + { + string? problem = S.UseSlot(number, _bar); + if (problem != null) { S.SetStatus(problem, warning: true); _p.Print(problem); } + }); + + public void SetFromSelected(int number) => _p.QueueBar(() => { _p.Print(S.SetFromSelected(number, _bar)); _p._nextBarBuildMs = 0; }); + + public void Clear(int number) => _p.QueueBar(() => { _p.Print(S.ClearSlot(number, _bar)); _p._nextBarBuildMs = 0; }); + + public void DropItem(int number, uint objectId) => _p.QueueBar(() => { _p.Print(S.SetFromId(number, objectId, _bar)); _p._nextBarBuildMs = 0; }); + + public void SetSpell(int number, uint spellId) => _p.QueueBar(() => { _p.Print(S.SetSpell(number, spellId, _bar)); _p._nextBarBuildMs = 0; }); + + public void ChangeSlotCount(int delta) => _p.QueueBar(() => + { + ExtraBar? b = S.Data.Extra(_bar); + if (b == null) return; + b.SlotCount = Math.Clamp(b.SlotCount + delta, ExtraBar.SlotsMin, ExtraBar.SlotsMax); + _p.RequestSave(); + _p._nextBarBuildMs = 0; + }); + + public void KeysChanged() { } + + public void ShowWeapons() => _p.ShowWeapons(); + + public void ShowSettings() => _p.ShowSettings(); + + public void Hide() => _p.QueueBar(() => _p.Host.SetPanelOpen(ExtraBar.TitleOf(_bar), RynthPanelOpen.Close)); + + public void AddBar() => _p.AddBar(); + + public void RemoveBar(int number) => _p.RemoveBar(number); + + private const string NoKeys = "An extra Shortcuts bar's slots have no keys: keys go on the Shortcuts bar's own slots."; + + public RynthKeyCheck CheckKey(BarSlot slot, string key, out string message) + { + message = NoKeys; + return RynthKeyCheck.Invalid; + } + + public bool BindKey(BarSlot slot, string key, out string message) + { + message = NoKeys; + return false; + } + + public bool UnbindKey(BarSlot slot, string key, out string message) + { + message = NoKeys; + return false; + } + } + /// Bar slot is one of AC's 18 (never on an independent bar). private bool IsRetail(int number) => BarMapping.IsRetail(number, _session.Settings.IndependentBar); @@ -268,4 +529,8 @@ public sealed partial class RynthDefectivePlugin : IBarActions public void ShowSettings() => QueueBar(() => ShowSettingsWindow(true)); public void Hide() => QueueBar(() => Host.SetPanelOpen(ShortcutBarWindow.Title, RynthPanelOpen.Close)); + + public void AddBar() => QueueBar(AddExtraBar); + + public void RemoveBar(int number) => QueueBar(() => RemoveExtraBar(number)); } diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.DayNight.cs b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.DayNight.cs new file mode 100644 index 0000000..1078978 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.DayNight.cs @@ -0,0 +1,66 @@ +// ============================================================================ +// RynthDefective - RynthDefectivePlugin.DayNight.cs +// The Day/Night timer (2026-11-04): day or night in Dereth now and the real +// time until the next dawn or dusk (Clock/DayNightWindow.cs draws it, +// Plugins/Shared/DerethClock.cs has the math). +// +// The tick reads the game clock twice a second while the window shows, and +// only in world: the clock's address isn't readable before world entry, and +// a fault there can't be caught (RynthAi's ReadGameClock has the same guard). +// Before that the window shows "—". +// ============================================================================ + +using System; +using RynthCore.Plugin.RynthDefective.Clock; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthDefective; + +public sealed partial class RynthDefectivePlugin +{ + internal const string DayNightSurface = "window:daynight"; + + private DayNightWindow? _dayNightWindow; // render thread + private volatile DayNightView _dayNightView = DayNightView.NotReady; // tick writes, render reads + private long _dayNightDrawnMs = long.MinValue / 2, _nextDayNightMs; + private int _dayNightFailures; + + /// RynthPluginRenderEmbed "window:daynight". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread. + internal int RenderDayNight(out float wantHeight) + { + wantHeight = 0; + if (!UsesShortcutBar) return 0; + System.Threading.Volatile.Write(ref _dayNightDrawnMs, Environment.TickCount64); + try + { + _dayNightWindow ??= new DayNightWindow(Host); + wantHeight = _dayNightWindow.Draw(_dayNightView); + _dayNightFailures = 0; + return 1; + } + catch (Exception ex) + { + Host.Log($"[RynthDefective] day/night draw failed: {ex.GetType().Name}: {ex.Message}"); + return ++_dayNightFailures >= 3 ? -2 : 0; + } + } + + /// Plugin tick: the clock's view while the window shows. + private void TickDayNight(long now) + { + if (!UsesShortcutBar) return; + if (now - System.Threading.Volatile.Read(ref _dayNightDrawnMs) > 2000 || now < _nextDayNightMs) return; + _nextDayNightMs = now + 500; + try { _dayNightView = ReadDayNight(now); } + catch (Exception ex) { Host.Log($"[RynthDefective] day/night read failed: {ex.GetType().Name}: {ex.Message}"); } + } + + /// The clock now; NotReady out of world (never read then) or before the clock is set. + private DayNightView ReadDayNight(long now) + { + if (!_inWorld || !_identityKnown || Host.GetPlayerId() == 0) return DayNightView.NotReady; + long bits = System.Runtime.InteropServices.Marshal.ReadInt64(new IntPtr(unchecked((int)DerethClock.ClockAddress))); + double raw = BitConverter.Int64BitsToDouble(bits); + return DerethClock.IsUsable(raw) ? new DayNightView(true, DerethClock.At(raw), now) : DayNightView.NotReady; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs index d59b2be..5ea7b11 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs @@ -98,6 +98,8 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase ShowWindow = (title, show) => Host.SetPanelOpen(title, show ? RynthPanelOpen.Open : RynthPanelOpen.Close), Tell = text => { _session.SetStatus(text); Print(text); _nextBarBuildMs = 0; }, ShowWeapons = () => ShowPicker(true), + AddBar = AddExtraBar, + RemoveBar = RemoveExtraBar, }; _settingsWindow = _ui.Add(new UiWindow("RynthDefective/Settings", "Defective Settings") { @@ -126,12 +128,15 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase StopCorpses(); _inWorld = false; _identityKnown = false; + RefreshExtraNumbers(); // the extra bars leave with the character (the engine opens them again when they come back) + _openWhenHosted.Clear(); _session.LoggedIn = false; _session.Use.ResetSession(); _world?.Reset(); _qty.Reset(); _qtyWorld?.Reset(); _barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady; + _dayNightView = Clock.DayNightView.NotReady; foreach (UiWindow? w in new[] { _barWindow, _pickerWindow, _settingsWindow }) if (w != null) { w.Visible = false; w.NeedsPass = true; } _session.DeclineCopy(); @@ -225,6 +230,15 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase if (UsesShortcutBar) Answer(DefReplies.Window("Corpses window", Host.SetPanelOpen(Corpses.CorpsesWindow.Title, RynthPanelOpen.Toggle))); else PrintFail("This RynthCore can't show the corpses window (it needs plugin API v90)."); break; + case DefVerb.DayNight: + { + // The window shown or hidden, and the time now in the reply (an engine without the window: the time only). + RynthPanelOpen mode = c.Text == "show" ? RynthPanelOpen.Open : c.Text == "hide" ? RynthPanelOpen.Close : RynthPanelOpen.Toggle; + int state = UsesShortcutBar ? Host.SetPanelOpen(Clock.DayNightWindow.Title, mode) : -1; + Clock.DayNightView clock = ReadDayNight(Environment.TickCount64); + Answer(DefReplies.DayNight(state, clock.Ready ? clock.Now : null)); + break; + } case DefVerb.Panels: if (UsesPanelButtons) Answer(DefReplies.Window("Game Panels buttons", Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.PanelButtonsWindow.Title, RynthPanelOpen.Toggle))); else PrintFail("This RynthCore can't open the game's panels from buttons (it needs plugin API v90)."); @@ -281,6 +295,21 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase case DefVerb.Status: PrintStatus(); break; + case DefVerb.Bars: + RunBarsCommand(c); + break; + case DefVerb.Shortcuts: + { + // Shortcuts clear a stuck busy state (per character; alone: what it is now). + DefSettings st = _session.Settings; + if (c.Text.Length > 0 && st.ClearStuckBusy != (c.Text == "on")) + { + st.ClearStuckBusy = c.Text == "on"; + RequestSave(); + } + Print(DefReplies.ClearBusy(st.ClearStuckBusy)); + break; + } case DefVerb.Quantity: case DefVerb.Split: case DefVerb.Give: @@ -298,6 +327,9 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase if (UsesShortcutBar) Print("RynthDefective draws the Shortcuts bar, the Game Panels buttons and the Selection window. Its settings: /rdef settings, " + "or the gear on the bar; right-click the bar's title to show or hide Game Panels and Selection."); + if (UsesShortcutBar) + Print($"More bars, anywhere on screen: Add a shortcut bar in the bar's right-click menu, or /rdef bars add (up to {ExtraBar.Max}); " + + "/rdef bars lists them, /rdef bars remove 2 takes one off."); Print("A key for a slot: /rdef bind 1 F9 (or Edit slots in the bar). Any item by name from Settings > Hotkeys: /rc hotkey add F9 /rdef use Stamina Kit."); Print("How many of a stack or a vendor's item: the box under it in the Selection window, or /rdef qty 25, then /rdef split, /rdef give " + "(to the last player or NPC you selected) or /rdef buy (the selected vendor item, or /rdef buy 25 )."); @@ -330,7 +362,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase { int filled = 0; for (int i = 0; i < _session.Settings.SlotCount; i++) if (!_session.Data.Slots[i].Empty) filled++; - Print($"{_character}: {filled}/{_session.Settings.SlotCount} slots set, {_session.Data.Favourites.Count} favourite weapons; " + Print($"{_character}: {filled}/{_session.Settings.SlotCount} slots set, {_session.Data.ExtraBars.Count} extra bars, {_session.Data.Favourites.Count} favourite weapons; " + $"{(_session.Use.InFlight ? "an action is in flight" : _session.Use.HasPending ? "an action is waiting" : "idle")}; file {_store.PathFor(_server, _character)}"); } @@ -456,6 +488,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase TickSelection(now); TickQuantity(now); TickCorpses(now); + TickDayNight(now); // With the shortcut bar the old script-window bar stays shut (the weapon picker is still one), and // has no RynthBar button (one that opened a window shut again at once). Its settings have their @@ -489,7 +522,8 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase /// Re-reads the inventory while a window shows or an action waits; slots follow their items. private void TickInventory() { - bool barShown = Environment.TickCount64 - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000; + long now = Environment.TickCount64; + bool barShown = now - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000 || AnyExtraShown(now); bool wanted = (_barWindow?.Visible ?? false) || (_pickerWindow?.Visible ?? false) || barShown || _session.Use.HasPending; if (!wanted || _world == null) return; List items = _world.Snapshot(InventoryAgeMs); @@ -515,6 +549,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase _session.Character = name; _session.LoggedIn = true; _identityKnown = true; + RefreshExtraNumbers(); _revisionSeen = -1; RefreshIconSupport(); StartCorpses(); diff --git a/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/BarSnapshot.cs b/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/BarSnapshot.cs index f8e05a1..458c2fe 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/BarSnapshot.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/BarSnapshot.cs @@ -13,6 +13,8 @@ // N is own slot N (BarMapping), and AC's toolbar isn't read at all. // An own slot can hold a spell (2026-10-28): its picture is the spell's, and // the snapshot carries the character's spells for the slot menu's search. +// An extra bar (2026-11-04, ExtraBar: "Shortcuts 2" ...) is built the same +// way from its own slots (BuildExtra): no AC slots, no keys. // ============================================================================ using System; @@ -57,6 +59,17 @@ internal sealed record BarSnapshot(BarSlot[] Slots, bool Ready, int IconSize, bo public static readonly BarSnapshot NotReady = new(Array.Empty(), false, 36); public IReadOnlyList KnownSpells => Spells ?? Array.Empty(); + + /// The extra bar this is (2-4; 0 = the Shortcuts bar itself): no AC slots, no keys. + public int Bar { get; init; } + /// The fewest and most slots the edit buttons allow. + public int MinSlots { get; init; } = DefSettings.BarSlotsMin; + public int MaxSlots { get; init; } = DefSettings.BarSlotsMax; + /// The extra bars there are (number, slots holding something), for the bars' menus. + public IReadOnlyList<(int Number, int Filled)> Extras { get; init; } = Array.Empty<(int, int)>(); + + /// Another extra bar can be added (fewer than ). + public bool CanAddBar => Extras.Count < ExtraBar.Max; } /// Builds the snapshot on the plugin tick (reads the host and the carried items). @@ -94,12 +107,13 @@ internal sealed class BarSnapshotBuilder DefSettings st = session.Settings; IReadOnlyList spells = session.KnownSpells(); bool canCast = _host.HasCastSpell; + var extras = Extras(session); if (st.IndependentBar) { // Every slot is RynthDefective's own: AC's toolbar isn't read or shown (BarMapping). var own = new BarSlot[st.BarSlots]; for (int n = 1; n <= st.BarSlots; n++) own[n - 1] = Own(n, BarMapping.OwnSlot(n, true), true, session, items, spells, _host); - return new BarSnapshot(own, true, st.ButtonSize, true, spells, canCast, st.WeaponsButtonOnBar); + return new BarSnapshot(own, true, st.ButtonSize, true, spells, canCast, st.WeaponsButtonOnBar) { Extras = extras }; } if (_host.GetShortcuts(_ids, _spells) == 0) return BarSnapshot.NotReady; RefreshKeys(now); @@ -109,7 +123,52 @@ internal sealed class BarSnapshotBuilder var slots = new BarSlot[st.BarSlots]; for (int n = 1; n <= st.BarSlots; n++) slots[n - 1] = BarMapping.IsRetail(n, false) ? Retail(n, byId) : Own(n, BarMapping.OwnSlot(n, false), false, session, items, spells, _host); - return new BarSnapshot(slots, true, st.ButtonSize, false, spells, canCast, st.WeaponsButtonOnBar); + return new BarSnapshot(slots, true, st.ButtonSize, false, spells, canCast, st.WeaponsButtonOnBar) { Extras = extras }; + } + + /// The extra bars there are, for the menus. + private static (int, int)[] Extras(DefSession session) + { + var list = session.Data.ExtraBars; + var a = new (int, int)[list.Count]; + for (int i = 0; i < list.Count; i++) a[i] = (list[i].Number, list[i].Filled); + return a; + } + + /// + /// Extra bar (2026-11-04): its own slots, the first SlotCount of them, + /// shown as the main bar's own ones are (picture, count, spell), with no keys. Pure apart from the + /// spell table: the tests build it offline. + /// + public static BarSnapshot BuildExtra(DefSession session, int number, IReadOnlyList items, bool canCast) + { + ExtraBar? bar = session.Data.Extra(number); + if (bar == null) return BarSnapshot.NotReady; + IReadOnlyList spells = session.KnownSpells(); + var slots = new BarSlot[bar.SlotCount]; + for (int n = 1; n <= bar.SlotCount; n++) slots[n - 1] = ExtraSlot(n, number, bar.Slots[n - 1], items, spells); + DefSettings st = session.Settings; + return new BarSnapshot(slots, true, st.ButtonSize, true, spells, canCast, st.WeaponsButtonOnBar) + { + Bar = number, + MinSlots = ExtraBar.SlotsMin, + MaxSlots = ExtraBar.SlotsMax, + Extras = Extras(session), + }; + } + + private static BarSlot ExtraSlot(int n, int bar, DefSlot slot, IReadOnlyList items, IReadOnlyList spells) + { + string whose = $"Shortcuts bar {bar}: clicks only, no keys"; + if (slot.IsSpell) return OwnSpell(n, n, slot, whose, string.Empty, string.Empty, spells, keys: false); + if (slot.Item == null) + return new BarSlot(n, false, n, 0, 0, string.Empty, string.Empty, CountTone.Plain, string.Empty, string.Empty, + $"Slot {n} ({whose}): empty.\nDrag an item from your pack onto it, or right-click: put the selected item or one of your spells here."); + SlotStatus s = ItemMatcher.Status(slot.Item, items); + string count = SlotText.Count(s, out uint color); + CountTone tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain; + string tip = SlotText.Tooltip(n, slot.Item, s, slot.Mode, null, keys: false) + $"\n({whose}.)"; + return new BarSlot(n, false, n, s.Item?.Id ?? 0, 0, s.Item?.FullName ?? slot.Item.FullName, count, tone, string.Empty, string.Empty, tip); } private BarSlot Retail(int n, Dictionary byId) @@ -167,16 +226,17 @@ internal sealed class BarSnapshotBuilder /// A spell slot: the spell's picture and name. A spell the character doesn't know (another /// character's file, a spell lost) shows dimmed with "?" (when the spellbook can be read at all). /// - private static BarSlot OwnSpell(int n, int own, DefSlot slot, string whose, string key, string all, IReadOnlyList spells) + private static BarSlot OwnSpell(int n, int own, DefSlot slot, string whose, string key, string all, IReadOnlyList spells, bool keys = true) { string name = slot.SpellLabel; SpellInfo? info = SpellTable.TryGet(slot.SpellId, out SpellInfo si) ? si : null; bool known = spells.Count == 0; foreach (SpellInfo s in spells) if (s.Id == slot.SpellId) { known = true; break; } - string tip = $"Slot {n}: {name}, a spell.\nClick or press the key: {SpellTargeting.Describe(info)} (Magic mode first)." + string tip = $"Slot {n}: {name}, a spell.\n{(keys ? "Click or press the key" : "Click")}: {SpellTargeting.Describe(info)} (Magic mode first)." + (known ? "" : "\nYou don't know this spell: pressing it does nothing.") - + (key.Length > 0 ? "\nKey: " + key : "\nNo key yet.") + $"\n({whose}.)\nRight-click: change the slot or its keys."; + + (!keys ? "" : key.Length > 0 ? "\nKey: " + key : "\nNo key yet.") + + $"\n({whose}.)\nRight-click: change the slot{(keys ? " or its keys" : "")}."; return new BarSlot(n, false, own, 0, slot.SpellId, name, known ? string.Empty : "?", known ? CountTone.Plain : CountTone.Missing, SlotText.ShortKey(key), all, tip); } diff --git a/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/ShortcutBarWindow.cs b/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/ShortcutBarWindow.cs index da19556..1b0752e 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/ShortcutBarWindow.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/ShortcutBarWindow.cs @@ -25,6 +25,10 @@ // /rdef use N. A key comes off whatever had it, after the player says so. // An independent bar (DefSettings.IndependentBar) has only RynthDefective's // own slots: every key is an engine hotkey (BarMapping, BarSlot.Own). +// Extra bars (2026-11-04, ExtraBar): the same window class draws "Shortcuts +// 2" ... with that bar's own slots (BarSnapshot.Bar): no AC slots and no keys, +// 1-24 slots. The bars' menu adds one (at most ExtraBar.Max), shows or hides +// them and removes one (its own menu: "Remove this bar"). // Spells (2026-10-28): an own slot's menu has "Put a spell here...", a search // over the character's spells (the engine can't read the spell selected in // the game's spellbook); the slot then casts it (UseController). @@ -62,6 +66,10 @@ internal interface IBarActions /// RynthDefective's settings window (the weapon swap switch, the independent bar ...). void ShowSettings(); void Hide(); + /// Adds an extra Shortcuts bar (2026-11-04: "Shortcuts 2" ..., at most ExtraBar.Max). + void AddBar(); + /// Removes extra bar and forgets its slots. + void RemoveBar(int number); // A slot's keys (any thread: the engine queues the change). AC's slot: AC's keymap action // UseQuickSlot_N; one of RynthDefective's own: its seam for own-slot keys (BindOwnSlotKey). @@ -76,13 +84,16 @@ internal sealed class ShortcutBarWindow private readonly RynthCoreHost _host; private readonly IBarActions _act; + /// The window this one draws: , or an extra bar's ("Shortcuts 2", ExtraBar.TitleOf). + private readonly string _title; private bool _edit; private float _k = 1f, _r = 1f; - public ShortcutBarWindow(RynthCoreHost host, IBarActions actions) + public ShortcutBarWindow(RynthCoreHost host, IBarActions actions, string title = Title) { _host = host; _act = actions; + _title = title; } private float Px(float v) => v * _k; @@ -97,7 +108,7 @@ internal sealed class ShortcutBarWindow private void Scale() { float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f); - int pct = _host.PanelScale(Title); + int pct = _host.PanelScale(_title); _k = pct > 0 ? pct / 100f : fontK; _r = _k / fontK; } @@ -154,7 +165,7 @@ internal sealed class ShortcutBarWindow ImGui.SetCursorScreenPos(origin); ImGui.Dummy(new Vector2(width, height)); SlotMenu(view); - BarMenu(); + BarMenu(view); if (_openKeyPopup) { _openKeyPopup = false; @@ -193,12 +204,13 @@ internal sealed class ShortcutBarWindow bool menu = ImGui.IsItemClicked(ImGuiMouseButton.Right); _host.PanelDragWithLastItem(); if (menu) ImGui.OpenPopup(BarMenuId); - SafeImGui.SetItemTooltip("Drag to move the bar. Ctrl+wheel here: bigger or smaller. Right-click: settings, Game Panels, Selection.\n" + SafeImGui.SetItemTooltip("Drag to move the bar. Ctrl+wheel here: bigger or smaller. Right-click: settings, Game Panels, Selection, more bars.\n" + "Drag the window's edge to change how many slots fit in a row."); ImFontPtr tf = Font(RynthUiFont.NarrowBold11); float size = Fs(tf) * 10f / 11f; - float tx = Tracked(dl, tf, size, new Vector2(x0, MathF.Round(y + (h - size) * 0.5f)), _text, "SHORTCUTS", 0.18f * size); + string name = view.Bar > 0 ? HeaderName(view.Bar) : "SHORTCUTS"; + float tx = Tracked(dl, tf, size, new Vector2(x0, MathF.Round(y + (h - size) * 0.5f)), _text, name, 0.18f * size); ImFontPtr nf = Font(RynthUiFont.Dash9); string count = view.Ready ? view.Slots.Length.ToString(System.Globalization.CultureInfo.InvariantCulture) : ""; dl.AddText(nf, Fs(nf), new Vector2(MathF.Round(tx + Px(6)), MathF.Round(y + (h - Fs(nf)) * 0.5f + Px(1))), _faint, count); @@ -218,11 +230,25 @@ internal sealed class ShortcutBarWindow "Settings (/rdef settings): weapon swaps under RynthAi, a bar independent of the game's toolbar,\nand showing the Game Panels buttons and the Selection window.")) _act.ShowSettings(); cx += chip + Px(1); - if (Chip("##sb_hide", RynthIcons.X, new Vector2(cx, cy), _faint, "Hide the bar (/rdef shows it again). Its keys keep working.")) + if (Chip("##sb_hide", RynthIcons.X, new Vector2(cx, cy), _faint, view.Bar > 0 + ? $"Hide this bar (the Shortcuts bar's right-click menu, or /rdef bars show {view.Bar}, shows it again)." + : "Hide the bar (/rdef shows it again). Its keys keep working.")) _act.Hide(); return y + h; } + private static readonly string[] HeaderNames = BuildHeaderNames(); + + private static string[] BuildHeaderNames() + { + var a = new string[ExtraBar.LastNumber + 1]; + for (int n = ExtraBar.FirstNumber; n <= ExtraBar.LastNumber; n++) a[n] = "SHORTCUTS " + n; + return a; + } + + /// "SHORTCUTS 2" (no string built per frame). + private static string HeaderName(int bar) => bar >= 0 && bar < HeaderNames.Length && HeaderNames[bar] != null ? HeaderNames[bar] : "SHORTCUTS"; + private bool Chip(string id, string icon, Vector2 pos, uint color, string tip, bool held = false) { Vector2 size = new(Px(ChipSize), Px(ChipSize)); @@ -256,7 +282,7 @@ internal sealed class ShortcutBarWindow // Items dragged out of AC's UI: the slots' area takes them (the engine keeps the drop from AC). Vector2 areaMin = new(x0, y), areaMax = new(x0 + perRow * (cell + gap), y + rows * (cell + gap)); - uint dropped = _host.HasDropTargets ? _host.DropTarget(Title, areaMin, areaMax, true, out _dragging) : 0; + uint dropped = _host.HasDropTargets ? _host.DropTarget(_title, areaMin, areaMax, true, out _dragging) : 0; int under = SlotAt(ImGui.GetIO().MousePos, x0, y, cell, gap, perRow, view.Slots.Length); _dropSlot = _dragging ? under : 0; if (dropped != 0 && under > 0) _act.DropItem(under, dropped); @@ -266,7 +292,7 @@ internal sealed class ShortcutBarWindow int col = i % perRow, row = i / perRow; Vector2 p = new(MathF.Round(x0 + col * (cell + gap)), MathF.Round(y + row * (cell + gap))); if (i < view.Slots.Length) Slot(dl, view.Slots[i], p, cell); - else EditButton(dl, i == view.Slots.Length ? -1 : 1, p, cell, view.Slots.Length, view.Independent); + else EditButton(dl, i == view.Slots.Length ? -1 : 1, p, cell, view); } return y + rows * (cell + gap) - gap; } @@ -345,16 +371,18 @@ internal sealed class ShortcutBarWindow } } - private void EditButton(ImDrawListPtr dl, int delta, Vector2 p, float cell, int count, bool independent) + private void EditButton(ImDrawListPtr dl, int delta, Vector2 p, float cell, BarSnapshot view) { Vector2 size = new(cell, cell); - bool can = delta < 0 ? count > DefSettings.BarSlotsMin : count < DefSettings.BarSlotsMax; + int count = view.Slots.Length; + bool can = delta < 0 ? count > view.MinSlots : count < view.MaxSlots; ImGui.SetCursorScreenPos(p); bool clicked = ImGui.InvisibleButton(delta < 0 ? "##sb_less" : "##sb_more", size); bool hot = can && ImGui.IsItemHovered(); SafeImGui.SetItemTooltip(delta < 0 ? "One slot fewer (the last one's item stays: add the slot back and it is there)." - : independent ? "One more slot (RynthCore's: this bar is independent of the game's toolbar)." + : view.Bar > 0 ? $"One more slot (up to {view.MaxSlots})." + : view.Independent ? "One more slot (RynthCore's: this bar is independent of the game's toolbar)." : count < DefSettings.RetailSlots ? "One more slot (the game's own, up to 18)." : "One more slot (RynthCore's: the game's toolbar holds 18)."); float r = Px(3); @@ -378,7 +406,7 @@ internal sealed class ShortcutBarWindow { BarSlot? s = _menuSlot >= 1 && _menuSlot <= view.Slots.Length ? view.Slots[_menuSlot - 1] : null; if (s == null) { ImGui.CloseCurrentPopup(); return; } - ImGui.TextDisabled($"Slot {s.Number}{(s.Retail ? " (the game's own)" : " (RynthCore's)")}"); + ImGui.TextDisabled(view.Bar > 0 ? $"Slot {s.Number} (Shortcuts bar {view.Bar})" : $"Slot {s.Number}{(s.Retail ? " (the game's own)" : " (RynthCore's)")}"); if (s.Name.Length > 0) SafeImGui.Text(s.Name); ImGui.Separator(); bool hasSelection = _host.HasGetSelectedItemId && _host.GetSelectedItemId() != 0; @@ -394,7 +422,13 @@ internal sealed class ShortcutBarWindow } if (ImGui.MenuItem("Empty this slot", null, false, !s.Empty)) _act.Clear(s.Number); ImGui.Separator(); - if (!_host.HasKeyBinding) + if (view.Bar > 0) + { + // An extra bar's slots are clicked: the keys are the Shortcuts bar's own slots' (/rdef use N). + ImGui.TextDisabled("No keys: click it"); + SafeImGui.SetItemTooltip("Keys go on the Shortcuts bar's own slots (right-click one there > Add a key)."); + } + else if (!_host.HasKeyBinding) { ImGui.TextDisabled(s.AllKeys.Length > 0 ? "Keys: " + s.AllKeys : s.Retail ? "No key: bind UseQuickSlot_" + s.Number + " in Configure Keyboard." : "No key: /rdef bind " + s.Own + " F9"); @@ -425,7 +459,7 @@ internal sealed class ShortcutBarWindow private const string BarMenuId = "##sb_bar_menu"; - private void BarMenu() + private void BarMenu(BarSnapshot view) { if (!ImGui.IsPopupOpen(BarMenuId)) return; ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA)); @@ -438,17 +472,82 @@ internal sealed class ShortcutBarWindow if (!open) return; try { - ImGui.TextDisabled("RynthDefective's Shortcuts bar"); + ImGui.TextDisabled(view.Bar > 0 ? $"RynthDefective's Shortcuts bar {view.Bar}" : "RynthDefective's Shortcuts bar"); ImGui.Separator(); BarMenuItems(); ImGui.Separator(); + MoreBarsItems(view); + ImGui.Separator(); if (ImGui.MenuItem("Weapons...")) _act.ShowWeapons(); - if (ImGui.MenuItem("Hide the bar")) _act.Hide(); - SafeImGui.SetItemTooltip("/rdef, or the lightning button on the RynthCore bar, shows it again. Its keys keep working."); + if (ImGui.MenuItem(view.Bar > 0 ? "Hide this bar" : "Hide the bar")) _act.Hide(); + SafeImGui.SetItemTooltip(view.Bar > 0 + ? $"The Shortcuts bar's right-click menu, Defective Settings, or /rdef bars show {view.Bar} shows it again." + : "/rdef, or the lightning button on the RynthCore bar, shows it again. Its keys keep working."); } finally { ImGui.EndPopup(); } } + /// + /// The extra bars (2026-11-04): add one; on the Shortcuts bar, show or hide each (they have no RynthCore + /// bar button) and remove one; on an extra bar, remove it. Removing asks once more (a submenu) when the + /// bar holds something: its slots are forgotten. + /// + private void MoreBarsItems(BarSnapshot view) + { + if (ImGui.MenuItem("Add a shortcut bar", null, false, view.CanAddBar)) _act.AddBar(); + SafeImGui.SetItemTooltip(view.CanAddBar + ? $"Another bar of {ExtraBar.DefaultSlots} slots in a window of its own, to put anywhere (/rdef bars add).\n" + + "Fill it as this one: drag items from your pack onto it, or right-click a slot. Its slots are clicked; they have no keys." + : $"There are {ExtraBar.Max} extra bars, as many as there can be. Remove one first."); + if (view.Bar > 0) + { + int filled = 0; + foreach ((int n, int f) in view.Extras) if (n == view.Bar) filled = f; + RemoveItem("Remove this bar", view.Bar, filled); + return; + } + if (view.Extras.Count == 0) return; + foreach ((int n, _) in view.Extras) + PanelToggle(ExtraBar.TitleOf(n), BarLabel(n), $"Show or hide Shortcuts bar {n} (/rdef bars show {n})."); + if (ImGui.BeginMenu("Remove a bar")) + { + try + { + foreach ((int n, int f) in view.Extras) RemoveItem(BarLabel(n), n, f); + } + finally { ImGui.EndMenu(); } + } + } + + /// A bar's remove item: at once when it is empty, else a submenu that says what goes with it. + private void RemoveItem(string label, int bar, int filled) + { + if (filled == 0) + { + if (ImGui.MenuItem(label)) _act.RemoveBar(bar); + SafeImGui.SetItemTooltip($"Shortcuts bar {bar} is empty: it goes (/rdef bars remove {bar})."); + return; + } + if (!ImGui.BeginMenu(label)) return; + try + { + if (ImGui.MenuItem($"Remove bar {bar} and its {filled} slot{(filled == 1 ? "" : "s")}")) _act.RemoveBar(bar); + SafeImGui.SetItemTooltip("Its slots are forgotten (the items stay in your pack)."); + } + finally { ImGui.EndMenu(); } + } + + private static readonly string[] BarLabels = BuildBarLabels(); + + private static string[] BuildBarLabels() + { + var a = new string[ExtraBar.LastNumber + 1]; + for (int n = ExtraBar.FirstNumber; n <= ExtraBar.LastNumber; n++) a[n] = "Shortcuts bar " + n; + return a; + } + + private static string BarLabel(int n) => n >= 0 && n < BarLabels.Length && BarLabels[n] != null ? BarLabels[n] : "Shortcuts bar " + n; + /// Settings..., and the two windows RynthDefective draws besides the bar (no RynthBar buttons of their own). private void BarMenuItems() { diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Use/BusyGate.cs b/Plugins/RynthCore.Plugin.RynthDefective/Use/BusyGate.cs index 27a8566..c96701e 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Use/BusyGate.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Use/BusyGate.cs @@ -37,11 +37,23 @@ // After a death or a login RynthAi's stream of rebuffs kept the count moving, // so it never read "steady" and a press waited until it gave up. // -// RynthDefective never resets the client's count itself (ForceResetBusyCount): -// the count is the engine's (its reconciler and watchdogs own it), RynthAi -// stopped resetting it on 2026-10-06 because a reset zeroes actions the server -// hasn't answered yet (each later answer then drives it negative), and nothing -// here needs it at zero: ignoring a leftover is enough to send. +// RynthDefective doesn't reset the client's count itself (ForceResetBusyCount) +// unless the player asks: the count is the engine's (its reconciler and +// watchdogs own it), RynthAi stopped resetting it on 2026-10-06 because a reset +// zeroes actions the server hasn't answered yet (each later answer then drives +// it negative), and nothing here needs it at zero: ignoring a leftover is +// enough to send. +// +// "Shortcuts clear a stuck busy state" (DefSettings.ClearStuckBusy, 2026-11-04, +// off by default; a player's ask): a press held ONLY by the count (BusyHold.Busy +// with nothing of ours in flight or unanswered, no gesture, RynthAi with no +// action of its own, no "You're too busy" from the server in ServerBusyRecentMs) +// sends the reset RynthAi's /ra clearbusy sends (the engine's +// ForceResetBusyCount: the count to 0, the cursor re-read, every plugin's +// mirror told), once per press, then the press goes (BusyClearRule; the use +// controller waits ClearSettleMs for the reset to land on the game's tick, +// then takes what is left as a leftover). Not /ra clearbusy's StopCompletely: +// a press must not stop a run. Never with a real action in flight. // ============================================================================ using System; @@ -128,6 +140,34 @@ internal static class BusyRule } } +/// +/// Whether a press held by the busy count clears it first (DefSettings.ClearStuckBusy, off by default). +/// Pure: the use controller asks, the tests check every case. +/// +internal static class BusyClearRule +{ + /// The server answered "You're too busy" this recently: it really is busy, nothing is cleared. + public const long ServerBusyRecentMs = 5000; + + /// The player's option. + /// What says holds the press. + /// The readings it said it from. + /// A use or cast of ours is in flight (sent, not answered or let go). + /// Our own last use or cast was answered (UseDone, the item in hand, a refusal); false while one went unanswered. + /// Since the server last answered "You're too busy". + public static bool ShouldClear(bool enabled, BusyHold hold, in BusyFacts f, bool ownInFlight, bool ownAnswered, long sinceServerBusyMs) + { + if (!enabled || hold != BusyHold.Busy || f.Count <= 0) return false; // only the count, and only when it holds + if (ownInFlight) return false; // ours, under way + if (f.SinceOwnSendMs < BusyRule.OwnTrustMs && !ownAnswered) return false; // ours, never answered: it may still be + if (f.Animating) return false; // a gesture: the character is acting + if (f.BotPaced == true) return false; // RynthAi's own action, unanswered + // A RynthAi that doesn't say what it has in flight: its "waiting on the server" bit while fresh. + if (f.BotPaced == null && f.BotWaiting == true && f.BotSteadyMs < BusyRule.BotTrustMs) return false; + return sinceServerBusyMs >= ServerBusyRecentMs; // the server said busy just now + } +} + /// /// The clocks behind : how long each reading has read the same, our own last /// send, and the leftover count. every tick (in or out of the world: a count @@ -194,6 +234,15 @@ internal sealed class BusyGate /// Our own use or cast went out now. public void NoteOwnSend(long now) => _ownSendMs = now; + /// + /// The count as it reads now is a leftover (after the player's clear: what the reset didn't take holds + /// this press no more). Only a count above it holds again. + /// + public void AcceptLeftover() + { + if (_count > _leftover) _leftover = _count; + } + public BusyFacts Facts(long now) => Facts(now, false); /// RynthAi holds for the press (its PacedAction bit is meaningful). diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Use/HostDefWorld.cs b/Plugins/RynthCore.Plugin.RynthDefective/Use/HostDefWorld.cs index 27c52a2..c734b37 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Use/HostDefWorld.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Use/HostDefWorld.cs @@ -44,6 +44,14 @@ internal sealed unsafe class HostDefWorld : IDefWorld public bool HoldBot(uint ms) => BotYield.Hold(_host, ms); public void ReleaseBot() => BotYield.Release(_host); + /// The busy-count reset of /ra clearbusy (ForceResetBusyCount; the engine runs it on the game's thread). + public bool ClearBusyCount() + { + if (!_host.HasForceResetBusyCount) return false; + _host.ForceResetBusyCount(); + return true; + } + public int RefusalSeq => _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0; public bool RefusalNamed(uint objectId) => diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Use/UseController.cs b/Plugins/RynthCore.Plugin.RynthDefective/Use/UseController.cs index 307e366..203e3b3 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Use/UseController.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Use/UseController.cs @@ -39,6 +39,12 @@ internal interface IDefWorld bool HoldBot(uint ms); /// Ends the player's turn. void ReleaseBot(); + /// + /// Resets the client's busy count as RynthAi's /ra clearbusy does (the engine's ForceResetBusyCount: + /// the count to 0 and the cursor re-read, on the game's next tick; every plugin's copy of the count is + /// told). False when this engine can't. Only for "Shortcuts clear a stuck busy state" (BusyClearRule). + /// + bool ClearBusyCount(); /// Count of the server's UseDone events; 0 when the engine can't report them. int UseDoneSeq { get; } /// The error of the server's first UseDone after (0x1D: "You're too busy"); 0 = none or unknown. @@ -155,6 +161,10 @@ internal static class Stance /// behind that stream until it gave up. While RynthAi holds, it also says exactly what it has in /// flight, so only that and our own last use hold a press: the busy count beyond them is a leftover. /// +/// Shortcuts clear a stuck busy state (2026-11-04, Settings.ClearStuckBusy, off by default): a press held +/// only by the busy count, with nothing real in flight (), resets the count as +/// /ra clearbusy does, once per press, then goes ( for the reset to read; logged). +/// /// After a portal (2026-10-29): the engine takes no game action until 5 s after portal space ends /// (its world-transition gate: AC is still loading the new place), so a press then was refused and /// reported as "the client didn't take the request". Within of @@ -188,6 +198,11 @@ internal sealed class UseController public const long PortalRetryWindowMs = 6000; /// How often a refused use or cast is tried again after a portal. public const long RefusedRetryMs = 250; + /// + /// After "Shortcuts clear a stuck busy state" cleared the count for a press: it waits this long for the + /// engine's reset (on the game's next tick) to read, then goes, what is left taken as a leftover. + /// + public const long ClearSettleMs = 500; private enum Stage { Sent, WaitWield, Stance, Magic } @@ -227,6 +242,14 @@ internal sealed class UseController private long _worldBackMs = long.MinValue / 4; private long _refusedRetryAtMs = long.MinValue / 4; private UseRequest? _refusedSaid; + // "Shortcuts clear a stuck busy state" (Settings.ClearStuckBusy): the press a clear was sent (or tried) + // for, once per press; when; whether the engine took it. Our own last send answered; the server's last + // "You're too busy". + private UseRequest? _clearedFor; + private long _clearedAtMs; + private bool _clearSent; + private bool _ownAnswered = true; + private long _tooBusyAtMs = long.MinValue / 4; /// The engine refused sends this soon after the character came out of portal space: they are tried again. private bool JustArrived(long now) => now - _worldBackMs < PortalRetryWindowMs; @@ -277,6 +300,7 @@ internal sealed class UseController _lastWait = string.Empty; _retryNotBeforeMs = long.MinValue / 4; _refusedRetryAtMs = long.MinValue / 4; + _clearedFor = null; } /// @@ -288,6 +312,8 @@ internal sealed class UseController { Reset(); _busy.Reset(); + _ownAnswered = true; + _tooBusyAtMs = long.MinValue / 4; } public void Tick(IDefWorld w) @@ -340,7 +366,7 @@ internal sealed class UseController if (_pending == null) return; UseRequest req = _pending; - string? wait = WaitReason(w, now); + string? wait = WaitReason(w, req, now); if (wait != null) { _lastWait = wait; @@ -355,12 +381,18 @@ internal sealed class UseController Send(w, req, now); } - private string? WaitReason(IDefWorld w, long now) + private string? WaitReason(IDefWorld w, UseRequest req, long now) { if (now - _lastDoneMs < MinGapMs) return "the last action just finished"; if (now < _retryNotBeforeMs) return "the server said the character was busy"; if (now < _refusedRetryAtMs) return "the game is still loading after the portal"; - return Hold(now) switch + BusyHold hold = Hold(now); + if (hold == BusyHold.Busy && Settings.ClearStuckBusy) + { + if (ClearStuckBusy(w, req, now) is { } clearing) return clearing; + hold = Hold(now); + } + return hold switch { BusyHold.Busy => "the character is busy", BusyHold.Animation => "an animation is playing", @@ -369,6 +401,40 @@ internal sealed class UseController }; } + /// + /// "Shortcuts clear a stuck busy state": is held by the busy count. When nothing + /// real is in flight (BusyClearRule) the count is reset as /ra clearbusy does, once for this press, and + /// the press waits for the reset to read; then what is left is a leftover + /// and it goes. Returns the wait while the clear settles, null for the usual rules (nothing cleared, or + /// the clear has settled). + /// + private string? ClearStuckBusy(IDefWorld w, UseRequest req, long now) + { + const string Clearing = "a stuck busy state is being cleared"; + if (ReferenceEquals(_clearedFor, req)) + { + if (!_clearSent) return null; // the engine couldn't: the usual rules + if (now - _clearedAtMs < ClearSettleMs) return Clearing; + _busy.AcceptLeftover(); + return null; + } + BusyFacts f = _busy.Facts(now, _botHeld); + if (!BusyClearRule.ShouldClear(true, BusyHold.Busy, f, _flight != null, _ownAnswered, now - _tooBusyAtMs)) return null; + _clearedFor = req; + _clearedAtMs = now; + _clearSent = w.ClearBusyCount(); + if (!_clearSent) + { + Log?.Invoke($"[RynthDefective] {req.Source}: held only by the client's busy count ({f.Count}), but this RynthCore can't reset it " + + "(ForceResetBusyCount): waiting as usual"); + return null; + } + Log?.Invoke($"[RynthDefective] {req.Source}: held only by the client's busy count ({f.Count}; nothing of ours or RynthAi's in flight, " + + "no gesture, no 'too busy' from the server): reset it as /ra clearbusy does (Shortcuts clear a stuck busy state), then the use"); + Say?.Invoke($"{req.Label}: clearing a stuck busy state..."); + return Clearing; + } + /// The busy gate's verdict now; a leftover it ignores for the first time is logged. private BusyHold Hold(long now) { @@ -444,6 +510,7 @@ internal sealed class UseController return; } _busy.NoteOwnSend(now); + _ownAnswered = false; _flight = new Flight { @@ -602,6 +669,7 @@ internal sealed class UseController return true; } _busy.NoteOwnSend(now); + _ownAnswered = false; f.Stage = Stage.Sent; f.SentMs = now; f.StageMs = now; @@ -627,7 +695,12 @@ internal sealed class UseController { if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.What} after {age} ms; carrying on"); Finish(now); - if (answered && w.UseDoneError(f.UseDoneAtSend) == TooBusyError) RetryTooBusy(f, now); + if (answered) _ownAnswered = true; + if (answered && w.UseDoneError(f.UseDoneAtSend) == TooBusyError) + { + _tooBusyAtMs = now; // the server really is busy: nothing is cleared for a while (BusyClearRule) + RetryTooBusy(f, now); + } return true; } return false; @@ -638,6 +711,7 @@ internal sealed class UseController if (live != null && live.Wielded) { Wielded?.Invoke(live); + _ownAnswered = true; // a wield's answer is the item in hand f.Item = live; f.Stage = Stage.Stance; f.StageMs = now; @@ -645,6 +719,7 @@ internal sealed class UseController } if (w.RefusalSeq != f.RefusalAtSend && w.RefusalNamed(f.Item.Id)) { + _ownAnswered = true; Warn?.Invoke($"{f.Item.FullName}: the server wouldn't let you wield it (a skill, level or slot requirement?)."); Finish(now); return true; diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Views/BarSettingsView.cs b/Plugins/RynthCore.Plugin.RynthDefective/Views/BarSettingsView.cs index f291f80..575534a 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Views/BarSettingsView.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Views/BarSettingsView.cs @@ -28,6 +28,13 @@ internal sealed class BarSettingsView public Action Tell = _ => { }; /// Opens the weapon picker (/rdef weapons). public Action ShowWeapons = () => { }; + /// Adds an extra Shortcuts bar (it opens once the engine hosts it; the plugin says so in chat). + public Action AddBar = () => { }; + /// Removes extra bar N and forgets its slots. + public Action RemoveBar = _ => { }; + + /// The extra bar whose Remove was pressed: it asks once more (0 = none). + private int _confirmRemove; public BarSettingsView(DefSession session) => _s = session; @@ -81,6 +88,9 @@ internal sealed class BarSettingsView } w.SliderInt("Slot picture size", "set.button", st.ButtonSize, DefSettings.ButtonMin, DefSettings.ButtonMax, v => { st.ButtonSize = v; Changed(); }); w.Tooltip("Ctrl+wheel over the bar's title makes the whole bar bigger or smaller."); + ClearBusyBox(w, st, Changed); + + MoreBars(w, Changed); w.SeparatorText("Weapons"); w.SmallButton("Weapon picker...", "set.weapons", () => ShowWeapons()); @@ -97,6 +107,56 @@ internal sealed class BarSettingsView + "/rdef qty, /rdef split, /rdef give, /rdef buy, /rdef help."); } + /// + /// The extra Shortcuts bars (2026-11-04): add one, and for each: shown, how many slots, remove (asked + /// once more when it holds something). Only where the engine has the Shortcuts bar (they are its kind + /// of window). + /// + private void MoreBars(UiWindow w, Action changed) + { + if (WindowShown(BarTitle) == null) return; + w.SeparatorText("More shortcut bars"); + w.TextWrapped($"Up to {ExtraBar.Max} bars of their own, anywhere on screen. Fill them as the Shortcuts bar: drag items from your pack " + + "onto a slot, or right-click it for the selected item or one of your spells. Their slots are clicked; they have no keys."); + foreach (ExtraBar bar in _s.Data.ExtraBars) + { + int n = bar.Number; + WindowBox(w, bar.Title, $"Shortcuts bar {n}", $"set.xbar.{n}.shown", $"Shows or hides Shortcuts bar {n} (/rdef bars show {n})."); + if (WindowShown(bar.Title) == null) w.TextDisabled($"Shortcuts bar {n}: opening..."); + w.SliderInt($"Bar {n} slots", $"set.xbar.{n}.slots", bar.SlotCount, ExtraBar.SlotsMin, ExtraBar.SlotsMax, v => { bar.SlotCount = v; changed(); }); + w.Tooltip($"How many slots Shortcuts bar {n} shows. Fewer hides the last ones; their items stay (/rdef bars slots {n} )."); + if (_confirmRemove == n) + { + int filled = bar.Filled; + w.TextColored(SlotText.Waiting, filled > 0 + ? $"Remove Shortcuts bar {n}? {filled} of its slots hold an item or a spell: they are forgotten (the items stay in your pack)." + : $"Remove Shortcuts bar {n}?"); + w.SmallButton("Remove it", $"set.xbar.{n}.yes", () => { _confirmRemove = 0; RemoveBar(n); }); + w.SameLine(); + w.SmallButton("Keep it", $"set.xbar.{n}.no", () => _confirmRemove = 0); + } + else w.SmallButton($"Remove bar {n}...", $"set.xbar.{n}.remove", () => _confirmRemove = n); + } + if (_s.Data.ExtraBars.Count < ExtraBar.Max) + { + w.SmallButton("Add a shortcut bar", "set.xbar.add", () => AddBar()); + w.Tooltip($"Another bar of {ExtraBar.DefaultSlots} slots in a window of its own (/rdef bars add). It opens in a moment: drag its title to move it."); + } + else w.TextDisabled($"{ExtraBar.Max} extra bars: as many as there can be."); + } + + /// "Shortcuts clear a stuck busy state" (DefSettings.ClearStuckBusy): here and on the script-window bar's settings. + internal static void ClearBusyBox(UiWindow w, DefSettings st, Action changed) + { + w.Checkbox("Shortcuts clear a stuck busy state", "set.clearbusy", st.ClearStuckBusy, v => { st.ClearStuckBusy = v; changed(); }); + w.Tooltip("On: a slot pressed while only the client's busy count holds it (after a death or a login the count can stay up with\n" + + "nothing happening; nothing of RynthDefective's or RynthAi's in flight, no animation, no 'You're too busy' from the server\n" + + "just now) resets the count as /ra clearbusy does, then the item is used. Once per press, logged.\n" + + "Off (the default): such a count holds a press for up to 4 s, then is ignored. Off because a reset also wipes actions the\n" + + "server hasn't answered that RynthDefective can't see (a click in the game's own windows, its toolbar keys, another\n" + + "plugin's), and their late answers then take the count below zero. Kept for this character. Also: /rdef shortcuts clearbusy on|off."); + } + private void WindowBox(UiWindow w, string title, string label, string id, string tip) { bool? shown = WindowShown(title); diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Views/SettingsPanel.cs b/Plugins/RynthCore.Plugin.RynthDefective/Views/SettingsPanel.cs index 050f01d..08f1e92 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Views/SettingsPanel.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Views/SettingsPanel.cs @@ -41,6 +41,7 @@ internal sealed class SettingsPanel w.Checkbox("Show counts and keys under the slots", "set.counts", st.ShowCounts, v => { st.ShowCounts = v; Changed(true); }); w.Checkbox("Allow weapon swaps while RynthAi's macro runs", "set.swap", st.SwapWhileBotRuns, v => { st.SwapWhileBotRuns = v; Changed(false); }); w.Tooltip("Off (the default): a weapon, wand or shield is not wielded while the RynthAi macro runs - it picks the weapon itself and would swap back. Kits, potions and other items always work."); + BarSettingsView.ClearBusyBox(w, st, () => Changed(false)); w.SeparatorText("About"); w.TextWrapped(Credit); diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Views/SlotText.cs b/Plugins/RynthCore.Plugin.RynthDefective/Views/SlotText.cs index 8f5d90c..0f2393e 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Views/SlotText.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Views/SlotText.cs @@ -56,7 +56,8 @@ internal static class SlotText return sb.Length == 0 ? "?" : sb.ToString(); } - public static string Tooltip(int number, ItemRef? item, SlotStatus s, UseMode mode, string? key) + /// The slot can have a key (an extra Shortcuts bar's can't: clicks only). + public static string Tooltip(int number, ItemRef? item, SlotStatus s, UseMode mode, string? key, bool keys = true) { if (item == null) return $"Slot {number}: empty. Click to set it up."; var sb = new StringBuilder(); @@ -69,12 +70,12 @@ internal static class SlotText { ItemKind kind = ItemKinds.Classify(s.Item); UseAction action = UseModes.ActionFor(mode, kind); - sb.Append("\nClick or press the key: ").Append(UseModes.Describe(action).Replace("used", "use it").Replace("wielded", "wield it")); + sb.Append(keys ? "\nClick or press the key: " : "\nClick: ").Append(UseModes.Describe(action).Replace("used", "use it").Replace("wielded", "wield it")); if (s.Item.MaxUses > 0) sb.Append("\n").Append(s.Uses).Append(" uses left"); if (s.Count > 1 || s.Item.MaxStack > 1) sb.Append(s.Item.MaxUses > 0 ? ", " : "\n").Append(s.Count).Append(" carried"); if (s.Item.Wielded) sb.Append("\nIn your hands now."); } - sb.Append(key != null ? "\nKey: " + key : "\nNo key yet (Edit slots)."); + if (keys) sb.Append(key != null ? "\nKey: " + key : "\nNo key yet (Edit slots)."); return sb.ToString(); } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/AreaFilter.cs b/Plugins/RynthCore.Plugin.RynthNav/AreaFilter.cs new file mode 100644 index 0000000..3e93bc5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/AreaFilter.cs @@ -0,0 +1,44 @@ +using System; +using DotRecast.Core.Numerics; +using DotRecast.Detour; + +namespace RynthNav.Routing; + +/// +/// Another filter (the portal one, AvoidFilter), minus every polygon whose middle lies in ground to +/// keep off (: a building's outline, BuildingOutlines), so the route maker's legs go +/// round buildings rather than through their rooms. The start's and the goal's polygons are always +/// allowed. TilePathFinder plans with it first and without it when there is no way round. Only the +/// middle: leaving out every polygon with a corner inside an outline (tried 2026-10-30) also left out +/// big open-ground polygons that reach under a roof's eaves (an outline is the whole model's hull), and +/// the real loops by Holtburg walked further for it and no less inside buildings; by the middle, the +/// loop in town kept every leg outside (0 yd inside, 51 yd without it) and a shorter lap. One worker +/// only (it keeps the last start and goal). +/// +internal sealed class AreaFilter : IDtQueryFilter +{ + private readonly IDtQueryFilter _inner; + public Func? Inside; + public long AllowA, AllowB; + + public AreaFilter(IDtQueryFilter inner) { _inner = inner; } + + public bool PassFilter(long refs, DtMeshTile tile, DtPoly poly) + { + if (!_inner.PassFilter(refs, tile, poly)) return false; + if (Inside == null || refs == AllowA || refs == AllowB || poly.vertCount == 0) return true; + float[] v = tile.data.verts; + double x = 0, y = 0; + for (int i = 0; i < poly.vertCount; i++) + { + int k = poly.verts[i] * 3; + x += v[k]; + y += v[k + 2]; + } + return !Inside(x / poly.vertCount, y / poly.vertCount); + } + + public float GetCost(RcVec3f pa, RcVec3f pb, long prevRef, DtMeshTile prevTile, DtPoly prevPoly, + long curRef, DtMeshTile curTile, DtPoly curPoly, long nextRef, DtMeshTile nextTile, DtPoly nextPoly) + => _inner.GetCost(pa, pb, prevRef, prevTile, prevPoly, curRef, curTile, curPoly, nextRef, nextTile, nextPoly); +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/BuildingOutlines.cs b/Plugins/RynthCore.Plugin.RynthNav/BuildingOutlines.cs new file mode 100644 index 0000000..fdebe13 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/BuildingOutlines.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// The ground outlines of Dereth's buildings, from NavData\worldmap.vec (RynthNav.Baker +/// --map-vectors; the engine's World Map draws the same file): each building's convex outline, in +/// world units. A building's cells are walkable on the landscape navmesh (the baker includes their +/// floors), so the route maker keeps a hunting loop's points out of these outlines, and its legs off +/// their floors where there is another way. Read once (on a worker), then never changed: any thread +/// may ask. Host-free: the route tests read a made-up file. +/// +/// File (little-endian): "RVEC", u32 version (1), u32 building count, u32 road segment count; per +/// building a u8 corner count, then that many (f32 x, f32 y) in map cells (24 yards; x east, y north, +/// from the map's south-west corner); the road segments follow (not read here). +/// +internal sealed class BuildingOutlines +{ + public const string FileName = "worldmap.vec"; + private const double CellUnits = 24.0; + /// The widest margin is asked for: buildings are filed under every landblock this near. + public const double MaxMargin = 12.0; + + private readonly double[][] _xs, _ys; + private readonly double[] _minX, _minY, _maxX, _maxY; + private readonly Dictionary> _byLandblock = new(); + + public int Count => _xs.Length; + + private BuildingOutlines(List<(double X, double Y)[]> polys) + { + int n = polys.Count; + _xs = new double[n][]; _ys = new double[n][]; + _minX = new double[n]; _minY = new double[n]; _maxX = new double[n]; _maxY = new double[n]; + for (int i = 0; i < n; i++) + { + var p = polys[i]; + _xs[i] = new double[p.Length]; _ys[i] = new double[p.Length]; + double x0 = double.MaxValue, y0 = double.MaxValue, x1 = double.MinValue, y1 = double.MinValue; + for (int k = 0; k < p.Length; k++) + { + _xs[i][k] = p[k].X; _ys[i][k] = p[k].Y; + x0 = Math.Min(x0, p[k].X); y0 = Math.Min(y0, p[k].Y); x1 = Math.Max(x1, p[k].X); y1 = Math.Max(y1, p[k].Y); + } + _minX[i] = x0; _minY[i] = y0; _maxX[i] = x1; _maxY[i] = y1; + int lx0 = Lb(x0 - MaxMargin), lx1 = Lb(x1 + MaxMargin), ly0 = Lb(y0 - MaxMargin), ly1 = Lb(y1 + MaxMargin); + for (int x = lx0; x <= lx1; x++) + for (int y = ly0; y <= ly1; y++) + { + uint lb = (uint)((x << 8) | y); + if (!_byLandblock.TryGetValue(lb, out List? list)) _byLandblock[lb] = list = new List(); + list.Add(i); + } + } + } + + private static int Lb(double world) => (int)Math.Clamp(Math.Floor(world / 192.0), 0, 255); + + /// Outlines given in world units (the tests). + public static BuildingOutlines FromPolygons(IEnumerable<(double X, double Y)[]> polys) + { + var list = new List<(double X, double Y)[]>(); + foreach (var p in polys) if (p.Length >= 3) list.Add(p); + return new BuildingOutlines(list); + } + + /// The file at ; null when it isn't there or isn't one (the caller says so). + public static BuildingOutlines? Load(string path) + { + try + { + if (!File.Exists(path)) return null; + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + return Read(fs); + } + catch { return null; } + } + + /// Reads the buildings of a worldmap.vec stream. Throws InvalidDataException on a file that isn't one. + public static BuildingOutlines Read(Stream s) + { + using var r = new BinaryReader(s, System.Text.Encoding.ASCII, leaveOpen: true); + if (r.ReadUInt32() != 0x4345_5652u) throw new InvalidDataException("not a vector file"); // "RVEC" + if (r.ReadUInt32() != 1u) throw new InvalidDataException("a newer vector file version"); + uint buildings = r.ReadUInt32(); + r.ReadUInt32(); // road segments: not needed + if (buildings > 200_000) throw new InvalidDataException("too many buildings"); + var polys = new List<(double X, double Y)[]>((int)buildings); + for (uint b = 0; b < buildings; b++) + { + int n = r.ReadByte(); + var p = new (double X, double Y)[n]; + for (int k = 0; k < n; k++) + { + float x = r.ReadSingle(), y = r.ReadSingle(); + p[k] = (x * CellUnits, y * CellUnits); + } + bool finite = true; + foreach (var (x, y) in p) finite &= double.IsFinite(x) && double.IsFinite(y); + if (n >= 3 && finite) polys.Add(p); + } + return new BuildingOutlines(polys); + } + + /// + /// The building whose outline holds (x, y), or comes within yards of it + /// (at most ); -1 when none does. + /// + public int Inside(double x, double y, double margin = 0) + { + margin = Math.Clamp(margin, 0, MaxMargin); + if (x < 0 || y < 0) return -1; + uint lb = (uint)((Lb(x) << 8) | Lb(y)); + if (!_byLandblock.TryGetValue(lb, out List? list)) return -1; + foreach (int i in list) + { + if (x < _minX[i] - margin || x > _maxX[i] + margin || y < _minY[i] - margin || y > _maxY[i] + margin) continue; + if (PointInPolygon(x, y, _xs[i], _ys[i])) return i; + if (margin > 0) + { + double[] xs = _xs[i], ys = _ys[i]; + for (int a = 0, b = xs.Length - 1; a < xs.Length; b = a++) + if (SegmentDistance(x, y, xs[b], ys[b], xs[a], ys[a]) < margin) return i; + } + } + return -1; + } + + private static bool PointInPolygon(double x, double y, double[] xs, double[] ys) + { + bool inside = false; + for (int i = 0, j = xs.Length - 1; i < xs.Length; j = i++) + if ((ys[i] > y) != (ys[j] > y) && x < (xs[j] - xs[i]) * (y - ys[i]) / (ys[j] - ys[i]) + xs[i]) inside = !inside; + return inside; + } + + private static double SegmentDistance(double x, double y, double ax, double ay, double bx, double by) + { + double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy; + double t = l2 < 1e-12 ? 0 : Math.Clamp(((x - ax) * dx + (y - ay) * dy) / l2, 0, 1); + double px = ax + dx * t - x, py = ay + dy * t - y; + return Math.Sqrt(px * px + py * py); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/LoopMaker.cs b/Plugins/RynthCore.Plugin.RynthNav/LoopMaker.cs new file mode 100644 index 0000000..e33127b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/LoopMaker.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// The route maker's walks on the navmesh (/rnav makeloop and makepath, the "RynthNav.Routes" +/// interface), worked out on a worker in a TilePathFinder of its own, never the walker's navmesh. +/// +/// A hunting loop round a centre (): +/// 1. the ground at the centre; +/// 2. per point, a direction round the circle (north first, clockwise); in it, the first spot (out +/// at the radius, then nearer, then a little to either side) that is walkable ground, out of every +/// building's outline (+ ), at least +/// from every portal, from the +/// navmesh's edge, apart from the points already chosen, and reached from the centre by a walk that +/// never enters a portal's circle and isn't the long way round. A direction with no such spot is +/// dropped, with the reason; +/// 3. the points in walking order (RouteShape.OrderLoop: round the centre, no two legs crossing); +/// 4. each point joined to the next, the last back to the first, by a walk that keeps out of every +/// portal's circle (strict: there is no fallback through one), pushed off walls by the wall +/// clearance, and round buildings where there is a way. A leg that can't be walked, or only far +/// the long way round, drops its far point and the next point is tried; fewer than three left is +/// a failure; +/// 5. the legs as a circular nav route (RouteShape.Assemble). +/// A path through given points (): each point onto the ground within +/// , each leg walked (the route graph for long ones), any leg that can't be is a +/// failure naming it; loop, line or once. +/// Host-free (Detour only): the graph tests make loops and paths on baked floors and on the real map. +/// +internal static class LoopMaker +{ + /// A makepath point must have walkable ground within this many yards. + public const double SnapUnits = 12.0; + + internal sealed class LoopOptions + { + public double Radius; + public int Points; + /// A point at least this far (yards) from any portal: a fight beside one ends in it. + public double PortalKeep = 20.0; + /// A point at least this far outside every building's outline. + public double BuildingMargin = 3.0; + /// A point at least this far from the navmesh's edge (a wall, a drop, water). + public double MinWall = 2.0; + /// Corners pushed this far off walls (RynthNav's "walls" avoid setting; 0 = off). + public double WallClearance; + /// Legs kept off building floors where there's another way (the points always are). + public bool LegsRoundBuildings = true; + public double Spacing = RouteShape.LoopSpacing; + } + + internal sealed class Dropped + { + public double Ns, Ew; + public string Why = ""; + } + + internal sealed class Result + { + public bool Ok; + public string Error = ""; + public WorldPt Centre; + /// The points kept, in walking order (the snapped ground). + public readonly List Points = new(); + public readonly List DroppedPoints = new(); + public readonly List> Legs = new(); + public NavRouteParser? Route; + public double Yards; + /// Things worth saying that didn't stop it ("no building outlines"...). + public readonly List Notes = new(); + public int Asked; + + public Result Fail(string why) { Ok = false; Error = why; Route = null; return this; } + } + + private static string At(WorldPt p) => NavCoords.Fmt(p.Ns, p.Ew); + + /// The nearest of to (x, y), and how far; -1 = none. + private static int NearestPortal(IReadOnlyList portals, double x, double y, out double dist) + { + int best = -1; dist = double.MaxValue; + for (int i = 0; i < portals.Count; i++) + { + double d = Math.Sqrt((portals[i].X - x) * (portals[i].X - x) + (portals[i].Y - y) * (portals[i].Y - y)); + if (d < dist) { dist = d; best = i; } + } + return best; + } + + private static double Length(IReadOnlyList pts) + { + double d = 0; + for (int i = 1; i < pts.Count; i++) d += pts[i - 1].FlatDistance(pts[i]); + return d; + } + + /// A leg this much longer than the straight line is the long way round: its far point goes. + private static bool TooLong(double walked, double straight, double radius) => + walked > Math.Max(2.5 * straight + 40.0, straight + radius); + + /// + /// A hunting loop round (its height NaN when not known) on + /// , keeping out of (null: no outlines) and away + /// from (the Atlas's and the live ones, as circles of their avoid radius). + /// The mesh's options are set here. + /// + public static Result Loop(TilePathFinder mesh, WorldPt centre, LoopOptions o, BuildingOutlines? buildings, + IReadOnlyList portals) + { + var r = new Result { Centre = centre }; + double R = o.Radius; + int n = o.Points > 0 ? o.Points : RouteShape.DefaultPoints(R); + r.Asked = n; + mesh.StrictPortals = true; + mesh.NoGaps = true; + mesh.WallClearance = o.WallClearance; + mesh.AvoidArea = buildings == null || !o.LegsRoundBuildings ? null : (x, y) => buildings.Inside(x, y) >= 0; + if (buildings == null) r.Notes.Add("no building outlines (NavData\\worldmap.vec): points were only kept off walls"); + + if (!mesh.LoadArea(centre.X - R - 30, centre.Y - R - 30, centre.X + R + 30, centre.Y + R + 30)) + return r.Fail($"no navmesh round {At(centre)} (its tiles aren't in NavData)"); + if (!mesh.Snap(centre, 16, out WorldPt c, out _)) + return r.Fail($"no walkable ground within 16 yd of {At(centre)}"); + r.Centre = c; + + // 2. A point per direction. + var chosen = new List(); + double minApart = Math.Max(10.0, R * 0.25); + double sector = 2 * Math.PI / n; + double[] reaches = { 1.0, 0.85, 0.7, 0.55, 0.4 }; + double[] turns = { 0, 0.3, -0.3 }; + for (int k = 0; k < n; k++) + { + string why = ""; + int whyRank = -1; + void Reason(int rank, string text) { if (rank > whyRank) { whyRank = rank; why = text; } } + bool found = false; + foreach (double f in reaches) + { + foreach (double turn in turns) + { + double a = k * sector + turn * sector; + var want = new WorldPt(c.X + Math.Sin(a) * R * f, c.Y + Math.Cos(a) * R * f, c.H); + if (!mesh.Snap(want, 6, out WorldPt g, out long poly)) { Reason(0, "no walkable ground there (water, a cliff, a building's wall)"); continue; } + if (buildings != null && buildings.Inside(g.X, g.Y, o.BuildingMargin) >= 0) { Reason(1, "in a building"); continue; } + int pi = NearestPortal(portals, g.X, g.Y, out double pd); + if (pi >= 0 && pd < o.PortalKeep) { Reason(2, $"{pd:F0} yd from the portal {(portals[pi].Name.Length > 0 ? portals[pi].Name : "there")}"); continue; } + if (mesh.WallDistance(g, poly, o.MinWall) < o.MinWall) { Reason(1, "against a wall or a drop"); continue; } + bool crowded = false; + foreach (WorldPt p in chosen) crowded |= p.FlatDistance(g) < minApart; + if (crowded) { Reason(1, "too near another point"); continue; } + List? walk = mesh.Leg(c, g, out string note); + if (walk == null) { Reason(3, "not reachable from the centre" + (note.Length > 0 ? $" ({note})" : "")); continue; } + double len = Length(walk); + if (len > 4 * R + 60) { Reason(3, $"only reachable the long way round ({len:F0} yd from the centre)"); continue; } + chosen.Add(g); + found = true; + break; + } + if (found) break; + } + if (!found) + { + double a0 = k * sector; + var spot = new WorldPt(c.X + Math.Sin(a0) * R, c.Y + Math.Cos(a0) * R, double.NaN); + r.DroppedPoints.Add(new Dropped { Ns = spot.Ns, Ew = spot.Ew, Why = why.Length > 0 ? why : "no ground there" }); + } + } + if (chosen.Count < RouteLimits.MinLoopPoints) + return r.Fail($"only {chosen.Count} of {n} points could be placed round {At(c)} within {R:F0} yd" + + (r.DroppedPoints.Count > 0 ? $" ({r.DroppedPoints[0].Why})" : "") + "; try another centre or radius"); + + // 3. Walking order. + int[] order = RouteShape.OrderLoop(chosen, c); + var pts = new List(order.Length); + foreach (int i in order) pts.Add(chosen[i]); + + // 4. Join them. + var legs = new List>(); + int at = 0; + while (at < pts.Count) + { + if (pts.Count < RouteLimits.MinLoopPoints) + return r.Fail($"only {pts.Count} points could be joined into a loop round {At(c)}" + + (r.DroppedPoints.Count > 0 ? $" ({r.DroppedPoints[^1].Why})" : "")); + int next = (at + 1) % pts.Count; + List? leg = mesh.Leg(pts[at], pts[next], out string note); + double straight = pts[at].FlatDistance(pts[next]); + string why = leg == null ? (note.Length > 0 ? note : "no walk to it") + : TooLong(Length(leg), straight, R) ? $"the walk to it is {Length(leg):F0} yd, the long way round" : ""; + if (why.Length == 0) { legs.Add(leg!); at++; continue; } + // Drop the far point; the closing leg (back to the first) drops the last one instead. + int drop = next == 0 ? at : next; + r.DroppedPoints.Add(new Dropped { Ns = pts[drop].Ns, Ew = pts[drop].Ew, Why = why }); + pts.RemoveAt(drop); + if (drop == at && legs.Count > 0) { legs.RemoveAt(legs.Count - 1); at--; } + } + + // 5. The route. + r.Points.AddRange(pts); + r.Legs.AddRange(legs); + r.Route = RouteShape.Assemble(legs, NavRouteType.Circular, o.Spacing, out r.Yards); + r.Ok = r.Route.Points.Count >= 2; + if (!r.Ok) r.Error = "the joined legs came to nothing"; + return r; + } + + /// + /// A route through in order (: a circular route also + /// walks from the last back to the first), on with its options as set by the + /// caller; each leg must be walkable, or it fails saying which. A point inside one of + /// ' circles is refused (walking there would take the portal). + /// + public static Result Path(TilePathFinder mesh, IReadOnlyList given, NavRouteType type, double spacing, + IReadOnlyList portals) + { + var r = new Result { Centre = given.Count > 0 ? given[0] : default, Asked = given.Count }; + mesh.NoGaps = true; + var ground = new List(given.Count); + for (int i = 0; i < given.Count; i++) + { + WorldPt p = given[i]; + if (!mesh.LoadArea(p.X - SnapUnits - 2, p.Y - SnapUnits - 2, p.X + SnapUnits + 2, p.Y + SnapUnits + 2) + || !mesh.Snap(p, SnapUnits, out WorldPt g, out _)) + return r.Fail($"point {i + 1} ({At(p)}) has no walkable ground within {SnapUnits:F0} yd (no navmesh there, water, or inside a wall)"); + int pi = NearestPortal(portals, g.X, g.Y, out double pd); + if (pi >= 0 && pd < portals[pi].R) + return r.Fail($"point {i + 1} ({At(p)}) is {pd:F1} yd from the portal {(portals[pi].Name.Length > 0 ? portals[pi].Name : "there")}: walking there would take it"); + ground.Add(g); + } + int legs = type == NavRouteType.Circular ? ground.Count : ground.Count - 1; + for (int i = 0; i < legs; i++) + { + int j = (i + 1) % ground.Count; + List? leg = mesh.Walk(ground[i], ground[j], false, out string note); + if (leg == null || leg.Count < 2) + return r.Fail($"leg {i + 1} (point {i + 1} {At(ground[i])} to point {j + 1} {At(ground[j])}) can't be walked: {(note.Length > 0 ? note : "no path on the navmesh")}"); + // The walk ends on the navmesh beside the point; the point (on the ground) is where it goes. + if (leg[0].FlatDistance(ground[i]) > 2.0) leg.Insert(0, ground[i]); + if (leg[^1].FlatDistance(ground[j]) > 2.0) leg.Add(ground[j]); + r.Legs.Add(leg); + } + r.Points.AddRange(ground); + r.Route = RouteShape.Assemble(r.Legs, type, spacing, out r.Yards); + r.Ok = r.Route.Points.Count >= 2; + if (!r.Ok) r.Error = "the joined legs came to nothing"; + return r; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs index e200b17..bdc3e20 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs @@ -23,6 +23,8 @@ public static unsafe class PluginExports try { string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; + // "RynthNav.Routes" v1 (2026-10-30): the route maker's JSON jobs (RoutesInterface.cs). + if (iface == RynthCore.Plugin.Shared.RynthNavRoutesApiV1.InterfaceName) return RoutesInterface.Query(iface, version); return PathInterface.Query(iface, version); } catch @@ -44,6 +46,8 @@ public static unsafe class PluginExports catch (Exception ex) { LogShutdownError(plugin, "Runtime.Shutdown", ex); } try { PathInterface.Release(); } catch (Exception ex) { LogShutdownError(plugin, "PathInterface.Release", ex); } + try { RoutesInterface.Release(); } + catch (Exception ex) { LogShutdownError(plugin, "RoutesInterface.Release", ex); } } private static void LogShutdownError(RynthNavPlugin? plugin, string step, Exception ex) diff --git a/Plugins/RynthCore.Plugin.RynthNav/RouteInfo.cs b/Plugins/RynthCore.Plugin.RynthNav/RouteInfo.cs new file mode 100644 index 0000000..417d1ad --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RouteInfo.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// What a saved nav route is (/rnav routeinfo, the "RynthNav.Routes" info op): its type, its points +/// by kind, how far it walks, the box it covers on the map and its centre, where it starts and how +/// far that is from the player, the landblocks it crosses, whether it is a dungeon route, and the +/// portals, recalls and commands a trip uses. Read with RynthAi's own reader (NavRouteParser). +/// +/// yards the walking stretches: from each point to the next (a circular route also from its last +/// point back to its first), except after a Portal or Recall step (a teleport) and across a +/// jump longer than (a teleport the file doesn't say, a +/// command recall) +/// landblocks every landblock a point is in, and those a walking stretch crosses (sampled every 24 yd) +/// dungeon more than half the walked-to points are in dungeon landblocks (the caller says which +/// landblocks are dungeons: the Atlas's, and those with a dungeon navmesh and no places on +/// the map); coordinates are all a nav file has, so a cellar under the landscape reads as +/// the landscape +/// Host-free: the route tests describe made-up and real files. +/// +internal sealed class RouteInfo +{ + /// Consecutive points farther apart than this (yards) are a teleport, not a walk. + public const double TeleportGapUnits = 600.0; + /// A walking stretch is sampled this often for the landblocks it crosses. + private const double SampleUnits = 24.0; + + public string Name = "", File = "", Type = "", Warning = "", FollowTarget = ""; + public int Points, Waypoints, Portals, Recalls, Chats, Pauses, Others; + public double Yards; + public bool HasBox; + public double MinNs, MaxNs, MinEw, MaxEw; + public double CentreNs => (MinNs + MaxNs) / 2; + public double CentreEw => (MinEw + MaxEw) / 2; + public bool HasStart; + public double StartNs, StartEw; + /// From the player to the start, yards; NaN when the player isn't on the map. + public double StartYards = double.NaN; + /// The walked-to point nearest the player (RynthAi starts a circular or linear route there), -1 = none. + public int NearestIndex = -1; + public double NearestNs, NearestEw, NearestYards = double.NaN; + public readonly List Landblocks = new(); + public readonly List DungeonLandblocks = new(); + public bool Dungeon; + public readonly List PortalNames = new(), RecallNames = new(), ChatCommands = new(); + + public static string TypeName(NavRouteType t) => t switch + { + NavRouteType.Circular => "circular", + NavRouteType.Linear => "linear", + NavRouteType.Follow => "follow", + NavRouteType.Once => "once", + _ => "unknown", + }; + + /// A step after which the character is somewhere else (no walk to the next point). + private static bool Teleports(NavPointType t) => t is NavPointType.PortalNPC or NavPointType.Recall; + + private static uint LandblockOf(double ns, double ew) + { + double x = NavCoords.WorldX(ew), y = NavCoords.WorldY(ns); + int lx = (int)Math.Floor(x / 192.0), ly = (int)Math.Floor(y / 192.0); + return lx is >= 0 and <= 255 && ly is >= 0 and <= 255 ? (uint)((lx << 8) | ly) : uint.MaxValue; + } + + /// + /// Describes . says whether a landblock is a + /// dungeon (null: none is); the player's map position when ; + /// names a recall's spell (null: "spell N"). + /// + public static RouteInfo Describe(NavRouteParser route, string name, string file, Func? isDungeon, + bool hasPlayer, double playerNs, double playerEw, Func? spellName) + { + var info = new RouteInfo { Name = name, File = file, Type = TypeName(route.RouteType), Warning = route.LoadWarning ?? "" }; + if (route.RouteType == NavRouteType.Follow && route.Points.Count == 0) info.FollowTarget = route.FollowTargetName; + List pts = route.Points; + info.Points = pts.Count; + var lbs = new SortedSet(); + int walkedTo = 0, inDungeon = 0; + var dungeonCache = new Dictionary(); + bool IsDun(uint lb) + { + if (isDungeon == null || lb == uint.MaxValue) return false; + if (!dungeonCache.TryGetValue(lb, out bool d)) dungeonCache[lb] = d = isDungeon(lb); + return d; + } + void AddLb(double ns, double ew) { uint lb = LandblockOf(ns, ew); if (lb != uint.MaxValue) lbs.Add(lb); } + + for (int i = 0; i < pts.Count; i++) + { + NavPoint p = pts[i]; + switch (p.Type) + { + case NavPointType.Point: case NavPointType.Checkpoint: case NavPointType.Jump: info.Waypoints++; break; + case NavPointType.PortalNPC: + info.Portals++; + if (p.TargetName.Length > 0 && !info.PortalNames.Contains(p.TargetName)) info.PortalNames.Add(p.TargetName); + break; + case NavPointType.Recall: + info.Recalls++; + string rn = spellName?.Invoke(p.SpellId) ?? ""; + rn = rn.Length > 0 ? rn : "spell " + p.SpellId.ToString(CultureInfo.InvariantCulture); + if (!info.RecallNames.Contains(rn)) info.RecallNames.Add(rn); + break; + case NavPointType.Chat: + info.Chats++; + if (p.ChatCommand.Length > 0 && !info.ChatCommands.Contains(p.ChatCommand)) info.ChatCommands.Add(p.ChatCommand); + break; + case NavPointType.Pause: info.Pauses++; break; + default: info.Others++; break; + } + if (!double.IsFinite(p.NS) || !double.IsFinite(p.EW)) continue; + if (!info.HasBox) { info.HasBox = true; info.MinNs = info.MaxNs = p.NS; info.MinEw = info.MaxEw = p.EW; } + info.MinNs = Math.Min(info.MinNs, p.NS); info.MaxNs = Math.Max(info.MaxNs, p.NS); + info.MinEw = Math.Min(info.MinEw, p.EW); info.MaxEw = Math.Max(info.MaxEw, p.EW); + if (!info.HasStart) { info.HasStart = true; info.StartNs = p.NS; info.StartEw = p.EW; } + AddLb(p.NS, p.EW); + if (NavRouteParser.IsPlainWaypoint(p.Type)) + { + walkedTo++; + uint lb = LandblockOf(p.NS, p.EW); + if (IsDun(lb)) { inDungeon++; if (!info.DungeonLandblocks.Contains(lb)) info.DungeonLandblocks.Add(lb); } + if (hasPlayer) + { + double d = NavCoords.Distance(playerNs, playerEw, p.NS, p.EW); + if (info.NearestIndex < 0 || d < info.NearestYards) { info.NearestIndex = i; info.NearestNs = p.NS; info.NearestEw = p.EW; info.NearestYards = d; } + } + } + } + foreach (var (a, b) in WalkingStretches(route)) + { + double d = NavCoords.Distance(a.NS, a.EW, b.NS, b.EW); + info.Yards += d; + int n = (int)Math.Ceiling(d / SampleUnits); + for (int k = 1; k < n; k++) AddLb(a.NS + (b.NS - a.NS) * k / n, a.EW + (b.EW - a.EW) * k / n); + } + info.Landblocks.AddRange(lbs); + info.DungeonLandblocks.Sort(); + info.Dungeon = walkedTo > 0 && inDungeon * 2 > walkedTo; + if (hasPlayer && info.HasStart && !info.Dungeon) info.StartYards = NavCoords.Distance(playerNs, playerEw, info.StartNs, info.StartEw); + if (info.Dungeon) { info.NearestIndex = -1; info.NearestYards = double.NaN; } // dungeon coordinates aren't the player's map position + return info; + } + + /// The walking length of a route in yards (see the class notes). + public static double Length(NavRouteParser route) + { + double total = 0; + foreach (var (a, b) in WalkingStretches(route)) total += NavCoords.Distance(a.NS, a.EW, b.NS, b.EW); + return total; + } + + /// Each pair of points walked between, in order (a circular route's closing pair last). + private static IEnumerable<(NavPoint A, NavPoint B)> WalkingStretches(NavRouteParser route) + { + List pts = route.Points; + int n = pts.Count; + int pairs = route.RouteType == NavRouteType.Circular && n > 1 ? n : n - 1; + for (int i = 0; i < pairs; i++) + { + NavPoint a = pts[i], b = pts[(i + 1) % n]; + if (Teleports(a.Type)) continue; + if (!double.IsFinite(a.NS) || !double.IsFinite(a.EW) || !double.IsFinite(b.NS) || !double.IsFinite(b.EW)) continue; + if (NavCoords.Distance(a.NS, a.EW, b.NS, b.EW) > TeleportGapUnits) continue; + yield return (a, b); + } + } + + // ── Out ────────────────────────────────────────────────────────────── + + /// The info op's result (Shared/RynthNavRoutesApi.cs has the fields). + public void WriteJson(Utf8JsonWriter w) + { + w.WriteStartObject(); + w.WriteString("name", Name); + w.WriteString("file", File); + w.WriteString("type", Type); + if (FollowTarget.Length > 0) w.WriteString("follows", FollowTarget); + w.WriteNumber("points", Points); + w.WriteStartObject("counts"); + w.WriteNumber("waypoints", Waypoints); w.WriteNumber("portals", Portals); w.WriteNumber("recalls", Recalls); + w.WriteNumber("chats", Chats); w.WriteNumber("pauses", Pauses); w.WriteNumber("other", Others); + w.WriteEndObject(); + RouteJson.Num(w, "yards", Yards, 0); + if (HasBox) + { + w.WriteStartObject("box"); + RouteJson.Num(w, "minNs", MinNs, 4); RouteJson.Num(w, "maxNs", MaxNs, 4); + RouteJson.Num(w, "minEw", MinEw, 4); RouteJson.Num(w, "maxEw", MaxEw, 4); + w.WriteEndObject(); + RouteJson.Place(w, "centre", CentreNs, CentreEw); + } + else { w.WriteNull("box"); w.WriteNull("centre"); } + if (HasStart) + { + w.WriteStartObject("start"); + RouteJson.Num(w, "ns", StartNs, 4); RouteJson.Num(w, "ew", StartEw, 4); RouteJson.Num(w, "yards", StartYards, 0); + w.WriteEndObject(); + } + else w.WriteNull("start"); + if (NearestIndex >= 0) + { + w.WriteStartObject("nearest"); + w.WriteNumber("index", NearestIndex); + RouteJson.Num(w, "ns", NearestNs, 4); RouteJson.Num(w, "ew", NearestEw, 4); RouteJson.Num(w, "yards", NearestYards, 0); + w.WriteEndObject(); + } + else w.WriteNull("nearest"); + w.WriteStartArray("landblocks"); + foreach (uint lb in Landblocks) w.WriteStringValue(lb.ToString("X4", CultureInfo.InvariantCulture)); + w.WriteEndArray(); + w.WriteBoolean("dungeon", Dungeon); + w.WriteStartArray("dungeonLandblocks"); + foreach (uint lb in DungeonLandblocks) w.WriteStringValue(lb.ToString("X4", CultureInfo.InvariantCulture)); + w.WriteEndArray(); + RouteJson.Strings(w, "portals", PortalNames); + RouteJson.Strings(w, "recalls", RecallNames); + RouteJson.Strings(w, "chats", ChatCommands); + if (Warning.Length > 0) w.WriteString("warning", Warning); + w.WriteEndObject(); + } + + /// /rnav routeinfo's lines. + public List ChatLines() + { + var lines = new List(); + string kinds = $"{Waypoints} waypoint(s)" + + (Portals > 0 ? $", {Portals} portal(s)" : "") + (Recalls > 0 ? $", {Recalls} recall(s)" : "") + + (Chats > 0 ? $", {Chats} command(s)" : "") + (Pauses > 0 ? $", {Pauses} pause(s)" : "") + (Others > 0 ? $", {Others} other" : ""); + lines.Add(FollowTarget.Length > 0 + ? $"routeinfo {Name}: follow, follows {FollowTarget}" + : $"routeinfo {Name}: {Type}, {Points} point(s) ({kinds}), {NavCoords.FmtDistance(Yards)} of walking{(Type == "circular" ? " a lap" : "")}"); + if (HasBox) + lines.Add($" covers {NavCoords.FmtOne(MinNs, 'N', 'S')} to {NavCoords.FmtOne(MaxNs, 'N', 'S')}, {NavCoords.FmtOne(MinEw, 'E', 'W')} to {NavCoords.FmtOne(MaxEw, 'E', 'W')}; centre {NavCoords.Fmt(CentreNs, CentreEw)}"); + if (HasStart) + lines.Add($" starts at {NavCoords.Fmt(StartNs, StartEw)}" + + (double.IsNaN(StartYards) ? "" : $", {NavCoords.FmtDistance(StartYards)} from you") + + (NearestIndex > 0 && !double.IsNaN(NearestYards) && (Type is "circular" or "linear") ? $"; nearest waypoint #{NearestIndex + 1}, {NavCoords.FmtDistance(NearestYards)} away" : "")); + if (Landblocks.Count > 0) + { + var hex = new List(); + for (int i = 0; i < Landblocks.Count && i < 12; i++) hex.Add(Landblocks[i].ToString("X4", CultureInfo.InvariantCulture)); + lines.Add($" {Landblocks.Count} landblock(s): {string.Join(" ", hex)}{(Landblocks.Count > 12 ? $" (+{Landblocks.Count - 12} more)" : "")}"); + } + if (Dungeon) lines.Add($" a dungeon route ({string.Join(" ", DungeonLandblocks.ConvertAll(l => l.ToString("X4", CultureInfo.InvariantCulture)))})"); + else if (DungeonLandblocks.Count > 0) lines.Add($" partly in a dungeon ({string.Join(" ", DungeonLandblocks.ConvertAll(l => l.ToString("X4", CultureInfo.InvariantCulture)))})"); + if (PortalNames.Count > 0) lines.Add($" portals: {string.Join(", ", PortalNames)}"); + if (RecallNames.Count > 0) lines.Add($" recalls: {string.Join(", ", RecallNames)}"); + if (ChatCommands.Count > 0) lines.Add($" commands: {string.Join(", ", ChatCommands)}"); + if (Warning.Length > 0) lines.Add(" " + Warning); + return lines; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RouteJobs.cs b/Plugins/RynthCore.Plugin.RynthNav/RouteJobs.cs new file mode 100644 index 0000000..bb00699 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RouteJobs.cs @@ -0,0 +1,224 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Plugin.RynthNav; + +/// A route maker job's state, as Poll reports it. +internal enum RouteJobState { Queued, Working, Done, Failed } + +/// +/// One request to the route maker (a /rnav command or the "RynthNav.Routes" interface's Request): what +/// was asked, where it is (queued, working, done, failed), a line saying so, and the result as JSON. +/// The job table changes it; everyone else reads it through the table. +/// +internal sealed class RouteJob +{ + public int Id; + public RouteRequest Request = new(); + public RouteJobState State; + public string Detail = ""; + /// The op's result (JSON), "null" until there is one. + public string ResultJson = "null"; + public long CreatedMs, StartedMs, EndedMs; + /// The go op: how many gotos had ended when its walk started (the tick's bookkeeping). + public int Seq; + public bool Finished => State is RouteJobState.Done or RouteJobState.Failed; +} + +/// +/// The route maker's jobs: the last of them, oldest dropped first once +/// finished. A new job is refused while every one kept is still queued or working. Ids go up from +/// the first one given (the plugin starts them from the clock, so a reload doesn't reuse a caller's +/// old ids); an id not kept any more is unknown. Locked: the interface's Request and Poll and the +/// tick may all come at once. Host-free: the route tests drive it. +/// +internal sealed class RouteJobTable +{ + public const int Capacity = 32; + + private readonly object _lock = new(); + private readonly List _jobs = new(); + private int _nextId; + + public RouteJobTable(int firstId) { _nextId = Math.Max(1, firstId); } + + public int Count { get { lock (_lock) return _jobs.Count; } } + + /// A new queued job for ; null (and why) when all the room is taken by unfinished jobs. + public RouteJob? Add(RouteRequest request, long nowMs, out string error) + { + error = ""; + lock (_lock) + { + if (_jobs.Count >= Capacity) + { + int old = _jobs.FindIndex(j => j.Finished); + if (old < 0) { error = $"{Capacity} jobs are already waiting or working: poll them, then ask again"; return null; } + _jobs.RemoveAt(old); + } + var job = new RouteJob { Id = _nextId, Request = request, State = RouteJobState.Queued, Detail = "queued", CreatedMs = nowMs }; + _nextId = _nextId == int.MaxValue ? 1 : _nextId + 1; + _jobs.Add(job); + return job; + } + } + + public RouteJob? Get(int id) + { + lock (_lock) return _jobs.Find(j => j.Id == id); + } + + /// The queued jobs, oldest first. + public List Queued() + { + lock (_lock) return _jobs.FindAll(j => j.State == RouteJobState.Queued); + } + + /// The working jobs, oldest first. + public List Working() + { + lock (_lock) return _jobs.FindAll(j => j.State == RouteJobState.Working); + } + + public void Start(RouteJob job, string detail, long nowMs) + { + lock (_lock) + { + if (job.Finished) return; + job.State = RouteJobState.Working; + job.Detail = detail; + job.StartedMs = nowMs; + } + } + + /// A working job's line (a walk's distance left); a result to show while it works. + public void Update(RouteJob job, string detail, string? resultJson = null) + { + lock (_lock) + { + if (job.Finished) return; + job.Detail = detail; + if (resultJson != null) job.ResultJson = resultJson; + } + } + + /// The job is over: done () or failed, with its line and result. A finished job stays as it is. + public void Finish(RouteJob job, bool ok, string detail, string? resultJson, long nowMs) + { + lock (_lock) + { + if (job.Finished) return; + job.State = ok ? RouteJobState.Done : RouteJobState.Failed; + job.Detail = detail; + if (resultJson != null) job.ResultJson = resultJson; + job.EndedMs = nowMs; + } + } + + /// + /// How a go job's walk ended, from the goto's last line: "arrived" (FinishGoto's "arrived", a dungeon's + /// "arrived inside X" / "went through X") and "stopped" (a stop: the stop op, /rnav stop, the panel) + /// are done (true); anything else ("stopped: no progress...", "stopped: logged out") failed. + /// + public static bool GoOutcome(string status, out string outcome) + { + if (status.StartsWith("arrived", StringComparison.Ordinal) || status.StartsWith("went through", StringComparison.Ordinal)) { outcome = "arrived"; return true; } + if (status == "stopped") { outcome = "stopped"; return true; } + outcome = "failed"; + return false; + } + + public static string StateName(RouteJobState s) => s switch + { + RouteJobState.Queued => "queued", + RouteJobState.Working => "working", + RouteJobState.Done => "done", + _ => "failed", + }; + + /// Poll's answer: {id, op, state, detail, result}; for an id not kept, {id, state: "unknown", error}. + public string PollJson(int id, out bool known) + { + lock (_lock) + { + RouteJob? j = _jobs.Find(x => x.Id == id); + known = j != null; + if (j == null) + return RouteJson.Write(w => + { + w.WriteStartObject(); + w.WriteNumber("id", id); + w.WriteString("state", "unknown"); + w.WriteString("error", $"no job {id}: only the last {Capacity} are kept, and a RynthNav reload forgets them"); + w.WriteEndObject(); + }); + return JobJson(j); + } + } + + /// Request's answer for a job just queued (the same fields as Poll). + public string Accepted(RouteJob job) + { + lock (_lock) return JobJson(job); + } + + private static string JobJson(RouteJob j) => RouteJson.Write(w => + { + w.WriteStartObject(); + w.WriteNumber("id", j.Id); + w.WriteString("op", RouteRequest.OpName(j.Request.Op)); + w.WriteString("state", StateName(j.State)); + w.WriteString("detail", j.Detail); + w.WritePropertyName("result"); + w.WriteRawValue(j.ResultJson, skipInputValidation: false); + w.WriteEndObject(); + }); +} + +/// Small helpers for writing the route maker's JSON (System.Text.Json's writer: no reflection, AOT-safe). +internal static class RouteJson +{ + /// One JSON value written by , as a string. + public static string Write(Action body) + { + var buf = new ArrayBufferWriter(512); + using (var w = new Utf8JsonWriter(buf)) + body(w); + return Encoding.UTF8.GetString(buf.WrittenSpan); + } + + /// {"error": why, "usage": usage}: a refused request. + public static string Error(string why, string usage) => Write(w => + { + w.WriteStartObject(); + w.WriteString("error", why); + if (usage.Length > 0) w.WriteString("usage", usage); + w.WriteEndObject(); + }); + + /// A number rounded to , or null when it isn't one (the writer refuses NaN). + public static void Num(Utf8JsonWriter w, string name, double v, int digits) + { + if (double.IsFinite(v)) w.WriteNumber(name, Math.Round(v, digits)); + else w.WriteNull(name); + } + + /// "name": {"ns": n, "ew": e} (4 decimals: 0.02 yd). + public static void Place(Utf8JsonWriter w, string name, double ns, double ew) + { + w.WriteStartObject(name); + Num(w, "ns", ns, 4); + Num(w, "ew", ew, 4); + w.WriteEndObject(); + } + + public static void Strings(Utf8JsonWriter w, string name, IEnumerable values) + { + w.WriteStartArray(name); + foreach (string s in values) w.WriteStringValue(s); + w.WriteEndArray(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RouteRequest.cs b/Plugins/RynthCore.Plugin.RynthNav/RouteRequest.cs new file mode 100644 index 0000000..c3938ae --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RouteRequest.cs @@ -0,0 +1,555 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthNav; + +/// What the route maker can be asked (chat or the "RynthNav.Routes" interface). +internal enum RouteOp { Plan, MakeRoute, MakeLoop, MakePath, Info, Atlas, Go, Stop, Where } + +/// The route maker's limits: a request outside them is refused, saying which and why. +internal static class RouteLimits +{ + /// A loop's radius, yards: under 20 it's a camp spot, over 250 its legs get long and it stops being readable. + public const double MinRadius = 20, MaxRadius = 250; + public const int MinLoopPoints = 3, MaxLoopPoints = 16; + public const int MinPathPoints = 2, MaxPathPoints = 32; + /// One makepath leg, straight-line yards (about 50 map degrees). + public const double MaxLegYards = 12000; + public const int DefaultAtlas = 10, MaxAtlas = 50; + /// A request's JSON, characters. + public const int MaxJson = 16384; + /// Map coordinates beyond this (degrees, either way) are off Dereth. + public const double MapLimit = 102.0; + public const int MaxTextLength = 200; +} + +/// +/// One route maker request, from a /rnav command () or the interface's JSON +/// (), checked against and the nav file name rules +/// (NavRouteExport.FileName). Both end up here, so the chat commands and the interface run the same +/// thing (RynthNavPlugin.RouteMaker.cs). Host-free: the route tests drive it. +/// +internal sealed class RouteRequest +{ + public RouteOp Op; + /// makeroute, makeloop, makepath, info: the nav file's name (without .nav). + public string Name = ""; + public bool Overwrite; + /// plan, makeroute, go: a place name or coordinates, as /rnav go takes them. + public string To = ""; + /// plan, makeroute: use portals and recalls (null: the "portals" switch). + public bool? Portals; + /// plan, makeroute: show the trip in the panel and on the ground, as /rnav route does (chat: always). + public bool Show; + /// makeloop: round the player (else round AtNs, AtEw). + public bool Here = true; + public double AtNs, AtEw; + public double Radius; + /// makeloop: how many points (0 = RouteShape.DefaultPoints of the radius). + public int Points; + public NavRouteType PathType = NavRouteType.Once; + /// makepath: the points, in order. + public readonly List<(double Ns, double Ew)> Path = new(); + public string Search = ""; + public int Max = RouteLimits.DefaultAtlas; + /// Typed in chat: the answer goes to chat too. + public bool FromChat; + + /// The op's name in the JSON ("plan", "makeroute", ...). + public static string OpName(RouteOp op) => op switch + { + RouteOp.Plan => "plan", + RouteOp.MakeRoute => "makeroute", + RouteOp.MakeLoop => "makeloop", + RouteOp.MakePath => "makepath", + RouteOp.Info => "info", + RouteOp.Atlas => "atlas", + RouteOp.Go => "go", + RouteOp.Stop => "stop", + _ => "where", + }; + + /// The /rnav word for the op (what a chat reply starts with). + public static string CommandName(RouteOp op) => op == RouteOp.Info ? "routeinfo" : OpName(op); + + public string Command => CommandName(Op); + + /// The usage line said with a refusal: the /rnav form for chat, the JSON form for the interface. + public static string Usage(RouteOp op, bool chat) => chat ? op switch + { + RouteOp.MakeRoute => "/rnav makeroute to [overwrite]", + RouteOp.MakeLoop => $"/rnav makeloop [at |here] radius [points <{RouteLimits.MinLoopPoints}-{RouteLimits.MaxLoopPoints}>] [overwrite]", + RouteOp.MakePath => "/rnav makepath [loop|line|once] ; ; ... [overwrite]", + RouteOp.Info => "/rnav routeinfo ", + _ => "/rnav help", + } : op switch + { + RouteOp.Plan => "{\"op\":\"plan\",\"to\":\"\"|{\"ns\":n,\"ew\":e},\"portals\":true|false}", + RouteOp.MakeRoute => "{\"op\":\"makeroute\",\"name\":\"\",\"to\":\"\"|{\"ns\":n,\"ew\":e},\"overwrite\":false}", + RouteOp.MakeLoop => $"{{\"op\":\"makeloop\",\"name\":\"\",\"at\":\"here\"|{{\"ns\":n,\"ew\":e}},\"radius\":{RouteLimits.MinRadius:F0}-{RouteLimits.MaxRadius:F0},\"points\":{RouteLimits.MinLoopPoints}-{RouteLimits.MaxLoopPoints},\"overwrite\":false}}", + RouteOp.MakePath => "{\"op\":\"makepath\",\"name\":\"\",\"type\":\"loop|line|once\",\"points\":[{\"ns\":n,\"ew\":e},...],\"overwrite\":false}", + RouteOp.Info => "{\"op\":\"info\",\"name\":\"\"}", + RouteOp.Atlas => $"{{\"op\":\"atlas\",\"search\":\"\",\"max\":1-{RouteLimits.MaxAtlas}}}", + RouteOp.Go => "{\"op\":\"go\",\"to\":\"\"|{\"ns\":n,\"ew\":e}}", + RouteOp.Stop => "{\"op\":\"stop\"}", + _ => "{\"op\":\"where\"}", + }; + + /// Coordinates as text /rnav go reads back exactly ("42.1234N, 33.5E"). + public static string CoordText(double ns, double ew) + { + var ci = CultureInfo.InvariantCulture; + return Math.Abs(ns).ToString("0.#####", ci) + (ns >= 0 ? "N" : "S") + ", " + Math.Abs(ew).ToString("0.#####", ci) + (ew >= 0 ? "E" : "W"); + } + + private static bool OnMap(double ns, double ew) => + double.IsFinite(ns) && double.IsFinite(ew) && Math.Abs(ns) <= RouteLimits.MapLimit && Math.Abs(ew) <= RouteLimits.MapLimit; + + // ── From a /rnav command ───────────────────────────────────────────── + + /// + /// /rnav makeroute, makeloop, makepath or routeinfo (, lower case) with + /// the rest of the line. Null with (no usage: the caller adds it). + /// + public static RouteRequest? FromCommand(string command, string rest, out string error) + { + error = ""; + string text = (rest ?? "").Trim(); + var r = new RouteRequest { FromChat = true, Show = true }; + switch (command) + { + case "makeroute": r.Op = RouteOp.MakeRoute; break; + case "makeloop": r.Op = RouteOp.MakeLoop; break; + case "makepath": r.Op = RouteOp.MakePath; break; + case "routeinfo": r.Op = RouteOp.Info; break; + default: error = $"'{command}' isn't a route maker command"; return null; + } + if (text.Length == 0) { error = "give the route a name"; return null; } + if (text.Length > RouteLimits.MaxJson) { error = "that's too long"; return null; } + + // A name in quotes may hold anything a file name can ("Hunt at the lake"). + string? quoted = null; + if (text[0] == '"') + { + int end = text.IndexOf('"', 1); + if (end < 0) { error = "the name's closing quote is missing"; return null; } + quoted = text.Substring(1, end - 1); + text = text.Substring(end + 1).Trim(); + } + if (r.Op != RouteOp.Info && EndsWithWord(text, "overwrite")) { r.Overwrite = true; text = text[..^9].TrimEnd(); } + + switch (r.Op) + { + case RouteOp.Info: + if (!SetName(r, quoted ?? text, out error)) return null; + if (quoted != null && text.Length > 0) { error = $"'{text}' after the name: routeinfo takes only a name"; return null; } + return r; + + case RouteOp.MakeRoute: + { + string where; + if (quoted != null) + { + if (!StartsWithWord(text, "to")) { error = "say where: to "; return null; } + where = text.Substring(2).Trim(); + if (!SetName(r, quoted, out error)) return null; + } + else + { + // The first " to " ends the name: place names hold it more often ("Portal to Cragstone"). + int at = text.IndexOf(" to ", StringComparison.OrdinalIgnoreCase); + if (at <= 0) { error = "say where: to "; return null; } + if (!SetName(r, text[..at], out error)) return null; + where = text[(at + 4)..].Trim(); + } + if (where.Length == 0) { error = "say where: to "; return null; } + if (where.Length > RouteLimits.MaxTextLength) { error = "the place is too long"; return null; } + if (NavCoords.TryParseLoc(where, out double tns, out double tew) && !OnMap(tns, tew)) + { error = $"{where} is off the map"; return null; } + r.To = where; + return r; + } + + case RouteOp.MakeLoop: + { + string[] t = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + int optAt = -1; + string firstError = ""; + for (int k = quoted != null ? 0 : 1; k < t.Length; k++) + { + if (!IsLoopWord(t[k])) continue; + var trial = new RouteRequest(); + if (TryLoopOptions(t, k, trial, out string why)) { optAt = k; break; } + if (firstError.Length == 0) firstError = why; + } + if (quoted == null && optAt < 0) + { + error = firstError.Length > 0 ? firstError : "give a name and the radius"; + return null; + } + if (quoted != null && optAt != 0) + { + error = t.Length == 0 ? "give the radius" : firstError.Length > 0 ? firstError : $"'{t[0]}' isn't one of at, here, radius, points, overwrite"; + return null; + } + if (!SetName(r, quoted ?? string.Join(' ', t, 0, optAt), out error)) return null; + TryLoopOptions(t, optAt, r, out _); + return CheckLoop(r, out error) ? r : null; + } + + default: // makepath + { + string[] segs = text.Split(';'); + string[] t = segs[0].Split(' ', StringSplitOptions.RemoveEmptyEntries); + int coordAt = -1; + for (int k = quoted != null ? 0 : 1; k < t.Length && coordAt < 0; k++) + if (NavCoords.TrySplitCoordsAndName(string.Join(' ', t, k, t.Length - k), out _, out _, out string left) && left.Length == 0) + coordAt = k; + if (coordAt < 0) { error = "give a name, then the points: ; ; ..."; return null; } + int nameEnd = coordAt; + if (nameEnd >= 1 && TryPathType(t[nameEnd - 1], out NavRouteType type) && (quoted != null || nameEnd >= 2)) + { + r.PathType = type; + nameEnd--; + } + if (quoted != null && nameEnd != 0) { error = $"'{t[0]}' after the name isn't loop, line, once or coordinates"; return null; } + if (!SetName(r, quoted ?? string.Join(' ', t, 0, nameEnd), out error)) return null; + for (int s = 0; s < segs.Length; s++) + { + string seg = s == 0 ? string.Join(' ', t, coordAt, t.Length - coordAt) : segs[s].Trim(); + if (seg.Length == 0) continue; + if (!NavCoords.TrySplitCoordsAndName(seg, out double ns, out double ew, out string extra) || extra.Length > 0) + { error = $"point {r.Path.Count + 1}: can't read '{seg}' as coordinates (e.g. 42.1N, 33.6E)"; return null; } + r.Path.Add((ns, ew)); + } + return CheckPath(r, out error) ? r : null; + } + } + } + + private static bool EndsWithWord(string text, string word) => + text.Equals(word, StringComparison.OrdinalIgnoreCase) + || (text.Length > word.Length && text.EndsWith(word, StringComparison.OrdinalIgnoreCase) && text[^(word.Length + 1)] == ' '); + + private static bool StartsWithWord(string text, string word) => + text.Equals(word, StringComparison.OrdinalIgnoreCase) + || (text.Length > word.Length && text.StartsWith(word, StringComparison.OrdinalIgnoreCase) && text[word.Length] == ' '); + + private static bool IsLoopWord(string w) => + w.Equals("at", StringComparison.OrdinalIgnoreCase) || w.Equals("here", StringComparison.OrdinalIgnoreCase) + || w.Equals("radius", StringComparison.OrdinalIgnoreCase) || w.Equals("points", StringComparison.OrdinalIgnoreCase) + || w.Equals("overwrite", StringComparison.OrdinalIgnoreCase); + + /// makeloop's options from token on: at <coords> | here, radius <yd>, points <n>. + private static bool TryLoopOptions(string[] t, int from, RouteRequest r, out string error) + { + error = ""; + bool radius = false, centre = false; + for (int i = from; i < t.Length; i++) + { + string w = t[i].ToLowerInvariant(); + switch (w) + { + case "here": + if (centre) { error = "say the centre once: at or here"; return false; } + r.Here = true; centre = true; + break; + case "overwrite": + r.Overwrite = true; + break; + case "radius": + if (i + 1 >= t.Length || !double.TryParse(t[i + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out r.Radius)) + { error = "radius needs a number of yards"; return false; } + radius = true; i++; + break; + case "points": + if (i + 1 >= t.Length || !int.TryParse(t[i + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out r.Points)) + { error = "points needs a whole number"; return false; } + i++; + break; + case "at": + { + if (centre) { error = "say the centre once: at or here"; return false; } + int j = i + 1; + while (j < t.Length && !IsLoopWord(t[j])) j++; + string coords = string.Join(' ', t, i + 1, j - i - 1); + if (!NavCoords.TrySplitCoordsAndName(coords, out r.AtNs, out r.AtEw, out string extra) || extra.Length > 0) + { error = $"at needs coordinates (e.g. at 42.1N, 33.6E), not '{coords}'"; return false; } + r.Here = false; centre = true; + i = j - 1; + break; + } + default: + error = $"'{t[i]}' isn't one of at, here, radius, points, overwrite"; + return false; + } + } + if (!radius) { error = "give the radius: radius "; return false; } + return true; + } + + private static bool TryPathType(string w, out NavRouteType type) + { + switch (w.ToLowerInvariant()) + { + case "loop": case "circular": type = NavRouteType.Circular; return true; + case "line": case "linear": type = NavRouteType.Linear; return true; + case "once": type = NavRouteType.Once; return true; + default: type = NavRouteType.Once; return false; + } + } + + private static bool SetName(RouteRequest r, string typed, out string error) + { + r.Name = NavRouteExport.FileName(typed, out error); + return r.Name.Length > 0; + } + + private static bool CheckLoop(RouteRequest r, out string error) + { + error = ""; + if (!double.IsFinite(r.Radius) || r.Radius < RouteLimits.MinRadius || r.Radius > RouteLimits.MaxRadius) + { error = $"radius {r.Radius.ToString("0.#", CultureInfo.InvariantCulture)} is out of range ({RouteLimits.MinRadius:F0}-{RouteLimits.MaxRadius:F0} yards)"; return false; } + if (r.Points != 0 && (r.Points < RouteLimits.MinLoopPoints || r.Points > RouteLimits.MaxLoopPoints)) + { error = $"points {r.Points} is out of range ({RouteLimits.MinLoopPoints}-{RouteLimits.MaxLoopPoints})"; return false; } + if (!r.Here && !OnMap(r.AtNs, r.AtEw)) { error = $"{CoordText(r.AtNs, r.AtEw)} is off the map"; return false; } + return true; + } + + private static bool CheckPath(RouteRequest r, out string error) + { + error = ""; + if (r.Path.Count < RouteLimits.MinPathPoints) { error = $"give at least {RouteLimits.MinPathPoints} points, separated by ;"; return false; } + if (r.Path.Count > RouteLimits.MaxPathPoints) { error = $"{r.Path.Count} points is too many (at most {RouteLimits.MaxPathPoints})"; return false; } + for (int i = 0; i < r.Path.Count; i++) + if (!OnMap(r.Path[i].Ns, r.Path[i].Ew)) { error = $"point {i + 1} ({CoordText(r.Path[i].Ns, r.Path[i].Ew)}) is off the map"; return false; } + for (int i = 1; i < r.Path.Count; i++) + { + double d = NavCoords.Distance(r.Path[i - 1].Ns, r.Path[i - 1].Ew, r.Path[i].Ns, r.Path[i].Ew); + if (d > RouteLimits.MaxLegYards) { error = $"leg {i} is {NavCoords.FmtDistance(d)} long (at most {NavCoords.FmtDistance(RouteLimits.MaxLegYards)} a leg)"; return false; } + } + return true; + } + + // ── From the interface's JSON ──────────────────────────────────────── + + /// A request from the "RynthNav.Routes" interface (Shared/RynthNavRoutesApi.cs has the format). Null with . + public static RouteRequest? FromJson(string? json, out string error) + { + error = ""; + if (string.IsNullOrWhiteSpace(json)) { error = "the request is empty"; return null; } + if (json.Length > RouteLimits.MaxJson) { error = $"the request is {json.Length} characters (at most {RouteLimits.MaxJson})"; return null; } + JsonDocument doc; + try { doc = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 8 }); } + catch (JsonException ex) { error = "not JSON: " + ex.Message; return null; } + using (doc) + { + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) { error = "the request must be a JSON object"; return null; } + if (!Str(root, "op", true, out string op, out error)) return null; + var r = new RouteRequest(); + if (!TryOp(op, out r.Op)) { error = $"unknown op '{op}' ({OpList})"; return null; } + bool ok = r.Op switch + { + RouteOp.Plan => ToField(root, r, out error) && OptBool(root, "portals", ref r.Portals, out error) && Bool(root, "show", ref r.Show, out error), + RouteOp.Go => ToField(root, r, out error), + RouteOp.MakeRoute => NameField(root, r, out error) && ToField(root, r, out error) && OptBool(root, "portals", ref r.Portals, out error) + && Bool(root, "overwrite", ref r.Overwrite, out error) && Bool(root, "show", ref r.Show, out error), + RouteOp.MakeLoop => NameField(root, r, out error) && At(root, r, out error) && Num(root, "radius", true, ref r.Radius, out error) + && Int(root, "points", ref r.Points, out error) && Bool(root, "overwrite", ref r.Overwrite, out error) && CheckLoop(r, out error), + RouteOp.MakePath => NameField(root, r, out error) && PathTypeOf(root, r, out error) && PathPoints(root, r, out error) + && Bool(root, "overwrite", ref r.Overwrite, out error) && CheckPath(r, out error), + RouteOp.Info => NameField(root, r, out error), + RouteOp.Atlas => SearchField(root, r, out error), + _ => true, + }; + return ok ? r : null; + } + } + + private const string OpList = "plan, makeroute, makeloop, makepath, info, atlas, go, stop, where"; + + private static bool TryOp(string text, out RouteOp op) + { + switch (text.Trim().ToLowerInvariant()) + { + case "plan": op = RouteOp.Plan; return true; + case "makeroute": op = RouteOp.MakeRoute; return true; + case "makeloop": op = RouteOp.MakeLoop; return true; + case "makepath": op = RouteOp.MakePath; return true; + case "info": case "routeinfo": op = RouteOp.Info; return true; + case "atlas": op = RouteOp.Atlas; return true; + case "go": op = RouteOp.Go; return true; + case "stop": op = RouteOp.Stop; return true; + case "where": op = RouteOp.Where; return true; + default: op = RouteOp.Where; return false; + } + } + + /// The usage to give with a refused request: its op's JSON form when the op was readable, else the list of ops. + public static string UsageFor(string? json) + { + try + { + using JsonDocument doc = JsonDocument.Parse(json ?? "", new JsonDocumentOptions { MaxDepth = 8 }); + if (doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty("op", out JsonElement v) + && v.ValueKind == JsonValueKind.String && TryOp(v.GetString() ?? "", out RouteOp op)) + return Usage(op, chat: false); + } + catch (JsonException) { } + return $"{{\"op\": one of {OpList}, ...}} (Plugins/Shared/RynthNavRoutesApi.cs has each op's fields)"; + } + + private static bool Str(JsonElement o, string name, bool required, out string value, out string error) + { + value = ""; error = ""; + if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind == JsonValueKind.Null) + { + if (required) error = $"\"{name}\" is missing"; + return !required; + } + if (v.ValueKind != JsonValueKind.String) { error = $"\"{name}\" must be a string"; return false; } + value = v.GetString() ?? ""; + if (value.Length > RouteLimits.MaxTextLength) { error = $"\"{name}\" is too long (at most {RouteLimits.MaxTextLength} characters)"; return false; } + return true; + } + + private static bool Bool(JsonElement o, string name, ref bool value, out string error) + { + bool? b = value; + if (!OptBool(o, name, ref b, out error)) return false; + value = b ?? value; + return true; + } + + private static bool OptBool(JsonElement o, string name, ref bool? value, out string error) + { + error = ""; + if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind == JsonValueKind.Null) return true; + if (v.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) { error = $"\"{name}\" must be true or false"; return false; } + value = v.ValueKind == JsonValueKind.True; + return true; + } + + private static bool Num(JsonElement o, string name, bool required, ref double value, out string error) + { + error = ""; + if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind == JsonValueKind.Null) + { + if (required) error = $"\"{name}\" is missing"; + return !required; + } + if (v.ValueKind != JsonValueKind.Number || !v.TryGetDouble(out double d) || !double.IsFinite(d)) { error = $"\"{name}\" must be a number"; return false; } + value = d; + return true; + } + + private static bool Int(JsonElement o, string name, ref int value, out string error) + { + error = ""; + if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind == JsonValueKind.Null) return true; + if (v.ValueKind != JsonValueKind.Number || !v.TryGetInt32(out int i)) { error = $"\"{name}\" must be a whole number"; return false; } + value = i; + return true; + } + + /// {"ns": n, "ew": e} as map coordinates on Dereth. + private static bool Coords(JsonElement v, string what, out double ns, out double ew, out string error) + { + ns = ew = 0; error = ""; + if (v.ValueKind != JsonValueKind.Object + || !v.TryGetProperty("ns", out JsonElement n) || n.ValueKind != JsonValueKind.Number || !n.TryGetDouble(out ns) + || !v.TryGetProperty("ew", out JsonElement e) || e.ValueKind != JsonValueKind.Number || !e.TryGetDouble(out ew)) + { error = $"{what} must be {{\"ns\": number, \"ew\": number}} (north and east positive)"; return false; } + if (!OnMap(ns, ew)) { error = $"{what} ({CoordText(ns, ew)}) is off the map"; return false; } + return true; + } + + private static bool NameField(JsonElement o, RouteRequest r, out string error) + { + if (!Str(o, "name", true, out string name, out error)) return false; + return SetName(r, name, out error); + } + + private static bool ToField(JsonElement o, RouteRequest r, out string error) + { + error = ""; + if (!o.TryGetProperty("to", out JsonElement v) || v.ValueKind == JsonValueKind.Null) { error = "\"to\" is missing (a place name or {\"ns\", \"ew\"})"; return false; } + if (v.ValueKind == JsonValueKind.Object) + { + if (!Coords(v, "\"to\"", out double ns, out double ew, out error)) return false; + r.To = CoordText(ns, ew); + return true; + } + if (!Str(o, "to", true, out string to, out error)) { error = "\"to\" must be a place name or {\"ns\", \"ew\"}"; return false; } + to = to.Trim(); + if (to.Length == 0) { error = "\"to\" is empty"; return false; } + if (NavCoords.TryParseLoc(to, out double tns, out double tew) && !OnMap(tns, tew)) { error = $"\"to\" ({to}) is off the map"; return false; } + r.To = to; + return true; + } + + private static bool At(JsonElement o, RouteRequest r, out string error) + { + error = ""; + r.Here = true; + if (!o.TryGetProperty("at", out JsonElement v) || v.ValueKind == JsonValueKind.Null) return true; + if (v.ValueKind == JsonValueKind.String) + { + string s = (v.GetString() ?? "").Trim(); + if (s.Equals("here", StringComparison.OrdinalIgnoreCase)) return true; + if (!NavCoords.TrySplitCoordsAndName(s, out r.AtNs, out r.AtEw, out string extra) || extra.Length > 0) + { error = "\"at\" must be \"here\", coordinates or {\"ns\", \"ew\"}"; return false; } + r.Here = false; + return true; + } + if (!Coords(v, "\"at\"", out r.AtNs, out r.AtEw, out error)) return false; + r.Here = false; + return true; + } + + private static bool PathTypeOf(JsonElement o, RouteRequest r, out string error) + { + if (!Str(o, "type", false, out string type, out error)) return false; + if (type.Length == 0) { r.PathType = NavRouteType.Once; return true; } + if (TryPathType(type.Trim(), out r.PathType)) return true; + error = $"\"type\" '{type}' isn't loop, line or once"; + return false; + } + + private static bool PathPoints(JsonElement o, RouteRequest r, out string error) + { + error = ""; + if (!o.TryGetProperty("points", out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) + { error = "\"points\" must be an array of {\"ns\", \"ew\"} (or coordinate strings)"; return false; } + int i = 0; + foreach (JsonElement p in arr.EnumerateArray()) + { + i++; + if (i > RouteLimits.MaxPathPoints) { error = $"too many points (at most {RouteLimits.MaxPathPoints})"; return false; } + double ns, ew; + if (p.ValueKind == JsonValueKind.String) + { + string s = p.GetString() ?? ""; + if (!NavCoords.TrySplitCoordsAndName(s, out ns, out ew, out string extra) || extra.Length > 0) + { error = $"point {i}: can't read '{s}' as coordinates"; return false; } + } + else if (!Coords(p, $"point {i}", out ns, out ew, out error)) return false; + r.Path.Add((ns, ew)); + } + return true; + } + + private static bool SearchField(JsonElement o, RouteRequest r, out string error) + { + if (!Str(o, "search", true, out r.Search, out error)) return false; + r.Search = r.Search.Trim(); + if (r.Search.Length == 0) { error = "\"search\" is empty"; return false; } + if (!Int(o, "max", ref r.Max, out error)) return false; + if (r.Max < 1 || r.Max > RouteLimits.MaxAtlas) { error = $"\"max\" must be 1 to {RouteLimits.MaxAtlas}"; return false; } + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RouteShape.cs b/Plugins/RynthCore.Plugin.RynthNav/RouteShape.cs new file mode 100644 index 0000000..a976bcb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RouteShape.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// The route maker's geometry that needs no navmesh (RynthNavPlugin.RouteMaker.cs, LoopMaker.cs): +/// how many points a loop of a radius gets, the order a loop's points are walked in (round the +/// centre, then untangled so no two legs cross), and the joined legs as a RynthAi nav route (thinned, +/// heights as nav Z, a circular route not repeating its first point). Host-free and Detour-free: +/// the route tests drive it. +/// +internal static class RouteShape +{ + /// A loop's legs get a point at least this often (yards), so RynthAi's nav follows the ground. + public const double LoopSpacing = 30.0; + + /// A loop's point count when none is asked for: about one every 45 yd of its circle, 4 to 12. + public static int DefaultPoints(double radius) => + Math.Clamp((int)Math.Round(2 * Math.PI * radius / 45.0), 4, 12); + + /// Compass bearing (0 = north, clockwise) from to , 0..360. + public static double Bearing(WorldPt c, WorldPt p) + { + double b = Math.Atan2(p.X - c.X, p.Y - c.Y) * 180.0 / Math.PI; + return b < 0 ? b + 360.0 : b; + } + + /// + /// The order to walk a loop's points in: clockwise round from the first + /// point north of it, then untangled (2-opt: two legs that cross are uncrossed by walking the + /// stretch between them the other way) until no two straight legs cross. Indexes into + /// . + /// + public static int[] OrderLoop(IReadOnlyList pts, WorldPt centre) + { + int n = pts.Count; + var order = new List(n); + for (int i = 0; i < n; i++) order.Add(i); + order.Sort((a, b) => + { + int c = Bearing(centre, pts[a]).CompareTo(Bearing(centre, pts[b])); + return c != 0 ? c : pts[a].FlatDistance(centre).CompareTo(pts[b].FlatDistance(centre)); + }); + if (n < 4) return order.ToArray(); + int first = order[0]; + for (int pass = 0; pass < n * n; pass++) + { + bool changed = false; + for (int i = 0; i < n && !changed; i++) + for (int j = i + 2; j < n && !changed; j++) + { + if (i == 0 && j == n - 1) continue; // the two legs meet at order[0] + WorldPt a = pts[order[i]], b = pts[order[i + 1]], c = pts[order[j]], d = pts[order[(j + 1) % n]]; + if (!SegmentsCross(a, b, c, d)) continue; + order.Reverse(i + 1, j - i); + changed = true; + } + if (!changed) break; + } + int at = order.IndexOf(first); + var o = new int[n]; + for (int k = 0; k < n; k++) o[k] = order[(at + k) % n]; + return o; + } + + /// How many pairs of straight legs of the path cross (: the last point joins the first). + public static int Crossings(IReadOnlyList pts, bool closed) + { + int n = pts.Count, legs = closed ? n : n - 1, count = 0; + for (int i = 0; i < legs; i++) + for (int j = i + 1; j < legs; j++) + { + if (j == i + 1 || (closed && i == 0 && j == n - 1)) continue; // neighbours share a point + if (SegmentsCross(pts[i], pts[(i + 1) % n], pts[j], pts[(j + 1) % n])) count++; + } + return count; + } + + /// True when the segments a-b and c-d cross (touching at an end doesn't count). + public static bool SegmentsCross(WorldPt a, WorldPt b, WorldPt c, WorldPt d) + { + double d1 = Cross(c, d, a), d2 = Cross(c, d, b), d3 = Cross(a, b, c), d4 = Cross(a, b, d); + return ((d1 > 1e-9 && d2 < -1e-9) || (d1 < -1e-9 && d2 > 1e-9)) && ((d3 > 1e-9 && d4 < -1e-9) || (d3 < -1e-9 && d4 > 1e-9)); + } + + private static double Cross(WorldPt o, WorldPt a, WorldPt b) => (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X); + + /// + /// The joined legs as a nav route of : leg k runs from point k to point k+1 + /// (first and last points included), each thinned (corners that matter, a point at least every + /// yd). A circular route's last leg ends where the first starts, so that + /// point isn't written twice (RynthAi walks from the last point back to the first). + /// is the walk, a circular route's closing leg included. + /// + public static NavRouteParser Assemble(IReadOnlyList> legs, NavRouteType type, double spacing, out double yards) + { + var route = new NavRouteParser { RouteType = type }; + yards = 0; + var pts = new List(); + foreach (IReadOnlyList leg in legs) + { + if (leg.Count == 0) continue; + List thin = TripPathBuilder.Thin(leg, TripPathBuilder.ThinTolerance, spacing); + for (int i = 1; i < thin.Count; i++) yards += thin[i - 1].FlatDistance(thin[i]); + for (int i = pts.Count == 0 ? 0 : 1; i < thin.Count; i++) pts.Add(thin[i]); + } + if (type == NavRouteType.Circular && pts.Count > 2 && pts[^1].FlatDistance(pts[0]) < TripPathBuilder.DuplicateUnits * 4) + pts.RemoveAt(pts.Count - 1); + double lastH = 0; + foreach (WorldPt p in pts) + { + if (!double.IsNaN(p.H)) lastH = p.H; + route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = p.Ns, EW = p.Ew, Z = lastH / 240.0 }); + } + return route; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RoutesInterface.cs b/Plugins/RynthCore.Plugin.RynthNav/RoutesInterface.cs new file mode 100644 index 0000000..5cb3be5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RoutesInterface.cs @@ -0,0 +1,93 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// RynthNav's side of the "RynthNav.Routes" interface (Shared/RynthNavRoutesApi.cs): the table +/// RynthPluginQueryInterface hands out and the two functions behind it, which queue a route maker job +/// and report one (RynthNavPlugin.RouteMaker.cs). They run on the plugin pump thread and act on the +/// current plugin instance. frees the table and the last string at +/// RynthPluginShutdown; callers resolve the table again every tick. +/// +internal static unsafe class RoutesInterface +{ + private static RynthNavRoutesApiV1* _table; + private static IntPtr _out; // the last string handed back (valid until the next call) + + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthNavRoutesApiV1.InterfaceName || version == 0 || version > RynthNavRoutesApiV1.InterfaceVersion) return IntPtr.Zero; + if (PluginExports.Runtime.Plugin == null) return IntPtr.Zero; + if (_table == null) + { + var t = (RynthNavRoutesApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthNavRoutesApiV1)); + t->Version = RynthNavRoutesApiV1.InterfaceVersion; + t->StructSize = (uint)sizeof(RynthNavRoutesApiV1); + t->Request = &Request; + t->Poll = &Poll; + _table = t; + } + return (IntPtr)_table; + } + + /// Frees the table and the last string (plugin shutdown). + public static void Release() + { + var t = _table; + _table = null; + if (t != null) NativeMemory.Free(t); + IntPtr o = _out; + _out = IntPtr.Zero; + if (o != IntPtr.Zero) Marshal.FreeCoTaskMem(o); + } + + private static void Out(byte** dst, string value) + { + if (dst == null) return; + IntPtr fresh = Marshal.StringToCoTaskMemUTF8(value); + IntPtr old = _out; + _out = fresh; + if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old); + *dst = (byte*)fresh; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Request(byte* json, byte** reply) + { + try + { + if (reply != null) *reply = null; + RynthNavPlugin? p = PluginExports.Runtime.Plugin; + if (p == null) { Out(reply, "{\"error\":\"RynthNav isn't running\"}"); return 0; } + string text = json == null ? "" : Marshal.PtrToStringUTF8((IntPtr)json) ?? ""; + string answer = p.RoutesRequest(text, out int id); + Out(reply, answer); + return id; + } + catch + { + return 0; + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Poll(int id, byte** json) + { + try + { + if (json != null) *json = null; + RynthNavPlugin? p = PluginExports.Runtime.Plugin; + if (p == null) { Out(json, "{\"id\":" + id + ",\"state\":\"unknown\",\"error\":\"RynthNav isn't running\"}"); return 0; } + string answer = p.RoutesPoll(id, out bool known); + Out(json, answer); + return known ? 1 : 0; + } + catch + { + return 0; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj b/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj index f5d997f..ced7000 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj @@ -40,6 +40,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs index 8febb0b..8e1b88e 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs @@ -100,23 +100,35 @@ public sealed partial class RynthNavPlugin // ── The trip ───────────────────────────────────────────────────────── - /// A new plan (Route) or goto (Go): its trip, shown, its path worked out. Tick thread. - private void SetTrip(List? steps, string goal, double goalNs, double goalEw, List? recalls, - string enterName, bool live) + /// + /// A new plan (Route) or goto (Go): its trip, shown, its path worked out ( + /// false: the caller works it out, the route maker's makeroute). Tick thread. + /// + private PlannedTrip SetTrip(List? steps, string goal, double goalNs, double goalEw, List? recalls, + string enterName, bool live, bool buildPath = true) { - var tr = new List(); - if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds)); - _trip = new PlannedTrip(++_tripSeq, steps ?? new List(), goal, goalNs, goalEw, - IsOnMap(_cellId), new WorldPt(_wx, _wy, _wz), _cellId, tr, - enterName.Length > 0 ? _enterPortal : "", enterName, live); + PlannedTrip trip = NewTrip(steps, goal, goalNs, goalEw, recalls, enterName, live); + _trip = trip; _tripPath = null; _tripShown = true; _markNext = -1; _markStep = -2; _markLb = CurrentLandblock; _saveConflict = ""; _saveDefault = NavRouteExport.SafeName("To " + goal); - if (_markersOn) StartPathBuild(); + if (_markersOn && buildPath) StartPathBuild(); _markerStatus = "working out the path…"; + return trip; + } + + /// A trip planned from where you stand, frozen (not shown). Tick thread. + private PlannedTrip NewTrip(List? steps, string goal, double goalNs, double goalEw, List? recalls, + string enterName, bool live) + { + var tr = new List(); + if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds)); + return new PlannedTrip(++_tripSeq, steps ?? new List(), goal, goalNs, goalEw, + IsOnMap(_cellId), new WorldPt(_wx, _wy, _wz), _cellId, tr, + enterName.Length > 0 ? _enterPortal : "", enterName, live); } /// Takes the markers off the ground (the trip stays for "save as nav route"). Tick thread. diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.RouteMaker.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.RouteMaker.cs new file mode 100644 index 0000000..f606b77 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.RouteMaker.cs @@ -0,0 +1,718 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +// The route maker (2026-10-30): RynthAi nav routes made on demand, on real walkable paths, for the +// player and for another plugin (the "RynthNav.Routes" interface, Shared/RynthNavRoutesApi.cs, which +// has the JSON). One implementation for both: a /rnav command and an interface Request each become a +// RouteRequest and then a job in the same table, run here. +// /rnav makeroute to [overwrite] = route, then saveroute, as one job +// /rnav makeloop [at |here] radius [points ] [overwrite] a hunting loop (LoopMaker) +// /rnav makepath [loop|line|once] ; ; ... [overwrite] a nav through points +// /rnav routeinfo what a saved nav is (RouteInfo) +// and for the interface also plan, atlas, go, stop and where. +// +// Threads, as the trip path for the markers and "save as nav route" (RynthNavPlugin.Markers.cs): the +// tick plans (TravelPlan, the recalls, the switches, the pose) and freezes what a worker needs; the +// worker works the walks out in a TilePathFinder of its own (never the walker's navmesh), writes the +// file (NavRouteExport.Save: a temp file, then moved in) and hands a RouteWork back; the tick takes it +// on a later tick and finishes the job (and answers in chat when it was typed). One worker at a time; +// atlas, where, stop and go are quick and run on the tick as soon as they come. The interface's +// Request and Poll come on the plugin pump thread, the tick's own; the job table is locked anyway. +// Names follow saveroute's rules (NavRouteExport.FileName), into the same folder (RynthAi's +// NavProfiles), and a file that's there is never replaced unless asked. RynthAi re-lists NavProfiles +// when the folder changes (every 3 s, LegacyDashboardRenderer.TickNavFolder), and /ra nav list and +// /ra nav load list it again, so a new route shows without a restart. +public sealed partial class RynthNavPlugin +{ + private const long RouteWorkTimeoutMs = 180000; // a worker job still going after this has failed (its late result is dropped) + private const double LoopLivePortalUnits = 300.0; // live portals this far past a loop's radius are kept away from too + + private RouteJobTable? _routeJobs; + private RouteJobTable RouteJobs => _routeJobs ??= new RouteJobTable(FirstJobId()); + // The one worker job (tick thread). + private RouteJob? _workJob; + private Task? _workTask; + private long _workStartMs; + private bool _workTimedOut; + // Building outlines (NavData\worldmap.vec), read by the first loop's worker. + private BuildingOutlines? _buildings; + private bool _buildingsTried; + // The goto a go job started (tick thread): its job, and how the last goto ended (FinishGoto). + private int _goJobId; + private string _gotoEndStatus = ""; + private int _gotoEndSeq; + private readonly Dictionary _goInfo = new(); + + /// Job ids start from the clock (seconds since boot), so a RynthNav reload doesn't hand a caller's old ids to new jobs. + private static int FirstJobId() => (int)(Environment.TickCount64 / 1000 % 2_000_000) * 1000 + 1; + + /// What a worker hands back to the tick. + private sealed class RouteWork + { + public bool Ok; + public string Detail = ""; + public string Json = "null"; + /// The chat answer (a job typed in chat): the first line is the result. + public readonly List Lines = new(); + public readonly List Log = new(); + /// A plan's or makeroute's trip and its path (the markers show it when it's still the trip shown). + public PlannedTrip? Trip; + public TripPath? Path; + /// A loop's worker read the building outlines: kept for the next one. + public bool BuildingsRead; + public BuildingOutlines? Buildings; + } + + private sealed class GoInfo + { + public string Name = "", Enter = ""; + public double Ns, Ew; + public int Steps, Teleports; + } + + private static bool IsWorkerOp(RouteOp op) => op is RouteOp.Plan or RouteOp.MakeRoute or RouteOp.MakeLoop or RouteOp.MakePath or RouteOp.Info; + + // ── In: chat and the interface ─────────────────────────────────────── + + /// /rnav makeroute | makeloop | makepath | routeinfo: queued; the answer comes when the job is done. Tick thread. + private void CmdRouteMaker(string cmd, string rest) + { + RouteOp op = cmd switch { "makeroute" => RouteOp.MakeRoute, "makeloop" => RouteOp.MakeLoop, "makepath" => RouteOp.MakePath, _ => RouteOp.Info }; + RouteRequest? req = RouteRequest.FromCommand(cmd, rest, out string error); + if (req == null) { SayFail($"{cmd}: {error} — {RouteRequest.Usage(op, chat: true)}"); return; } + RouteJob? job = RouteJobs.Add(req, NowMs, out error); + if (job == null) { SayFail($"{cmd}: {error}"); return; } + Host.Log($"[RynthNav] job {job.Id} {cmd} queued (chat)"); + // It starts on this tick unless another route is being worked out: then say it waits. + if (_workTask != null) Say($"{cmd}: queued; another route is being worked out first ({RouteJobs.Queued().Count} waiting)"); + } + + /// "RynthNav.Routes" Request: a job id (and its JSON), or 0 and {error, usage}. Plugin pump thread. + internal string RoutesRequest(string json, out int id) + { + id = 0; + RouteRequest? req = RouteRequest.FromJson(json, out string error); + if (req == null) + { + Host.Log($"[RynthNav] routes request refused: {error}"); + return RouteJson.Error(error, RouteRequest.UsageFor(json)); + } + RouteJob? job = RouteJobs.Add(req, NowMs, out error); + if (job == null) return RouteJson.Error(error, ""); + id = job.Id; + Host.Log($"[RynthNav] job {job.Id} {RouteRequest.OpName(req.Op)} queued (interface)"); + return RouteJobs.Accepted(job); + } + + /// "RynthNav.Routes" Poll. Any thread. + internal string RoutesPoll(int id, out bool known) => RouteJobs.PollJson(id, out known); + + // ── The tick ───────────────────────────────────────────────────────── + + private void TickRouteJobs() + { + if (_routeJobs == null) return; + long now = NowMs; + TakeRouteWork(now); + foreach (RouteJob j in _routeJobs.Working()) + if (j.Request.Op == RouteOp.Go) TickGoJob(j, now); + foreach (RouteJob j in _routeJobs.Queued()) + { + if (!IsWorkerOp(j.Request.Op)) { RunNow(j, now); continue; } + if (_workTask == null) StartWork(j, now); + } + } + + /// A job is over: the table, the log, and the chat when it was typed. + private void EndJob(RouteJob j, bool ok, string detail, string? json, long now, IReadOnlyList? lines = null) + { + RouteJobs.Finish(j, ok, detail, json, now); + Host.Log($"[RynthNav] job {j.Id} {RouteRequest.OpName(j.Request.Op)}: {(ok ? "done" : "failed")}: {detail} ({now - j.CreatedMs} ms)"); + if (!j.Request.FromChat) return; + string cmd = j.Request.Command; + if (lines != null && lines.Count > 0) + { + if (ok) Say(lines[0]); else SayFail($"{lines[0]} — {RouteRequest.Usage(j.Request.Op, chat: true)}"); + for (int i = 1; i < lines.Count; i++) Say(lines[i]); + } + else if (ok) Say($"{cmd}: {detail}"); + else SayFail($"{cmd}: {detail} — {RouteRequest.Usage(j.Request.Op, chat: true)}"); + } + + private void FailJob(RouteJob j, string why, long now) => EndJob(j, false, why, RouteJson.Error(why, ""), now); + + private void TakeRouteWork(long now) + { + if (_workTask == null || _workJob == null) return; + if (!_workTask.IsCompleted) + { + if (!_workTimedOut && now - _workStartMs > RouteWorkTimeoutMs) + { + _workTimedOut = true; + FailJob(_workJob, $"still working after {RouteWorkTimeoutMs / 1000} s: given up (a late result is dropped)", now); + } + return; + } + Task task = _workTask; + RouteJob job = _workJob; + bool late = _workTimedOut; + _workTask = null; _workJob = null; _workTimedOut = false; + RouteWork w; + if (task.IsFaulted) + { + string why = task.Exception?.GetBaseException().Message ?? "unknown"; + w = new RouteWork { Ok = false, Detail = "failed: " + why, Json = RouteJson.Error("failed: " + why, "") }; + w.Lines.Add($"{job.Request.Command}: failed ({why}); see the log"); + } + else w = task.Result; + foreach (string line in w.Log) Host.Log(line); + if (w.BuildingsRead) + { + _buildings = w.Buildings; _buildingsTried = true; + Host.Log(w.Buildings != null ? $"[RynthNav] building outlines: {w.Buildings.Count} from {BuildingOutlines.FileName}" + : $"[RynthNav] building outlines: no {BuildingOutlines.FileName} in {NavDataDir}"); + } + // A plan's path is the shown trip's too (makeroute typed in chat shows it): the markers draw it. + if (w.Trip != null && w.Path != null && ReferenceEquals(_trip, w.Trip) && (_tripPath == null || _tripPath.TripId != w.Trip.Id)) + { + _tripPath = w.Path; + int points = 0; + foreach (WorldPt[]? p in w.Path.Walks) points += p?.Length ?? 0; + _markerStatus = $"{points} waypoints"; + OnPathReady(_trip, w.Path); + } + if (late) return; + EndJob(job, w.Ok, w.Detail, w.Json, now, w.Lines); + } + + // ── Quick ops (the tick) ───────────────────────────────────────────── + + private void RunNow(RouteJob j, long now) + { + RouteRequest q = j.Request; + switch (q.Op) + { + case RouteOp.Atlas: + { + Atlas atlas = _atlas; + if (atlas.Locations.Count == 0) { FailJob(j, "the Atlas isn't loaded (" + _atlasStatus + ")", now); return; } + bool hasPos = PlayerMapPos(out double pns, out double pew); + List hits = atlas.Search(q.Search, null, q.Max); + string json = RouteJson.Write(w => + { + w.WriteStartObject(); + w.WriteString("search", q.Search); + w.WriteNumber("count", hits.Count); + w.WriteStartArray("places"); + foreach (AtlasLocation l in hits) + { + w.WriteStartObject(); + w.WriteString("name", l.Name); + w.WriteString("kind", l.Type); + w.WriteBoolean("onMap", l.OnMap); + RouteJson.Num(w, "ns", l.OnMap ? l.Ns : double.NaN, 4); + RouteJson.Num(w, "ew", l.OnMap ? l.Ew : double.NaN, 4); + RouteJson.Num(w, "yards", l.OnMap && hasPos ? NavCoords.Distance(pns, pew, l.Ns, l.Ew) : double.NaN, 0); + if (!l.OnMap) w.WriteString("where", l.Desc.Length > 0 ? l.Desc : "in a dungeon"); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + }); + EndJob(j, true, hits.Count == 0 ? $"no place matches \"{q.Search}\"" : $"{hits.Count} place(s)", json, now); + return; + } + case RouteOp.Where: + { + if (!_hasPose) { FailJob(j, "no player position yet", now); return; } + bool onMap = PlayerMapPos(out double ns, out double ew); + double nearYd = double.NaN; + AtlasLocation? near = onMap ? NearestPlace(ns, ew, out nearYd) : null; + bool dungeon = InDungeon(_cellId), indoors = (_cellId & 0xFFFF) >= 0x100; + string json = RouteJson.Write(w => + { + w.WriteStartObject(); + w.WriteBoolean("onMap", onMap); + RouteJson.Num(w, "ns", onMap ? ns : double.NaN, 4); + RouteJson.Num(w, "ew", onMap ? ew : double.NaN, 4); + w.WriteString("landblock", CurrentLandblock.ToString("X4", CultureInfo.InvariantCulture)); + w.WriteString("cell", _cellId.ToString("X8", CultureInfo.InvariantCulture)); + w.WriteBoolean("indoors", indoors); + w.WriteBoolean("dungeon", dungeon); + w.WriteBoolean("walking", _gotoActive); + if (near != null) + { + w.WriteStartObject("nearest"); + w.WriteString("name", near.Name); + w.WriteString("kind", near.Type); + RouteJson.Num(w, "ns", near.Ns, 4); + RouteJson.Num(w, "ew", near.Ew, 4); + RouteJson.Num(w, "yards", nearYd, 0); + w.WriteEndObject(); + } + else w.WriteNull("nearest"); + w.WriteEndObject(); + }); + string at = onMap ? NavCoords.Fmt(ns, ew) : dungeon ? "in a dungeon" : "off the map"; + EndJob(j, true, $"{at}, landblock 0x{CurrentLandblock:X4}{(near != null ? $", {NavCoords.FmtDistance(nearYd)} from {near.Name}" : "")}", json, now); + return; + } + case RouteOp.Stop: + { + bool was = _gotoActive; + DoMove(5); // as /rnav stop: the walk ends on the next tick + EndJob(j, true, was ? "stopping the walk" : "nothing was walking", + RouteJson.Write(w => { w.WriteStartObject(); w.WriteBoolean("wasWalking", was); w.WriteEndObject(); }), now); + return; + } + case RouteOp.Go: + StartGoJob(j, now); + return; + } + } + + /// The Atlas place on the map nearest (ns, ew), and how far. + private AtlasLocation? NearestPlace(double ns, double ew, out double yards) + { + AtlasLocation? best = null; + yards = double.MaxValue; + foreach (AtlasLocation l in _atlas.Locations) + { + if (!l.OnMap) continue; + double d = NavCoords.Distance(ns, ew, l.Ns, l.Ew); + if (d < yards) { yards = d; best = l; } + } + return best; + } + + // ── go: walk there as /rnav go does, and follow the walk to its end ── + + private void StartGoJob(RouteJob j, long now) + { + if (!_hasPose) { FailJob(j, "no player position yet", now); return; } + if (!ResolveGo(j.Request.To, out string name, out string type, out double ns, out double ew, out string enter, out string enterType, out string error)) + { + EndJob(j, false, error, GoJson(null, false, "failed", error), now); + return; + } + _store.Touch(new SavedPlace { Name = name, Type = type, Ns = ns, Ew = ew }); + _goNote = ""; + StartWalk(name, type, ns, ew, enter, enterType); // says "walking to ..." in chat, or why it can't + if (!_gotoActive) + { + string why = _goNote.Length > 0 ? _goNote : "the walk didn't start"; + EndJob(j, false, why, GoJson(null, false, "failed", why), now); + return; + } + _goJobId = j.Id; + j.Seq = _gotoEndSeq; + int teleports = 0; + if (_route != null) foreach (RouteStep s in _route) if (s.UsePortal || s.UseRecall || s.IsHub) teleports++; + var info = new GoInfo { Name = enter.Length > 0 ? enter : name, Enter = enter, Ns = ns, Ew = ew, Steps = _route?.Count ?? 1, Teleports = teleports }; + _goInfo[j.Id] = info; + string line; lock (_gate) line = _goLine; + RouteJobs.Start(j, line.Length > 0 ? line : $"walking to {info.Name}", now); + RouteJobs.Update(j, j.Detail, GoJson(info, true, "walking", "")); + } + + private void TickGoJob(RouteJob j, long now) + { + _goInfo.TryGetValue(j.Id, out GoInfo? info); + if (_goJobId != j.Id) + { + EndGo(j, info, true, "stopped", "stopped: another goto took over", now); + return; + } + if (_gotoActive) + { + string line; lock (_gate) line = _goLine; + if (line.Length > 0 && line != j.Detail) RouteJobs.Update(j, line); + return; + } + string status = _gotoEndSeq != j.Seq ? _gotoEndStatus + : !_hasPose ? "stopped: logged out" + : _goNote.Length > 0 ? _goNote : "stopped: the walk ended"; + _goJobId = 0; + bool ok = RouteJobTable.GoOutcome(status, out string outcome); + EndGo(j, info, ok, outcome, status, now); + } + + private void EndGo(RouteJob j, GoInfo? info, bool ok, string outcome, string status, long now) + { + _goInfo.Remove(j.Id); + EndJob(j, ok, status, GoJson(info, true, outcome, status), now); + } + + private static string GoJson(GoInfo? info, bool started, string outcome, string reason) => RouteJson.Write(w => + { + w.WriteStartObject(); + w.WriteBoolean("started", started); + if (info != null) + { + w.WriteStartObject("to"); + w.WriteString("name", info.Name); + RouteJson.Num(w, "ns", info.Ns, 4); + RouteJson.Num(w, "ew", info.Ew, 4); + w.WriteEndObject(); + if (info.Enter.Length > 0) w.WriteString("enter", info.Enter); else w.WriteNull("enter"); + w.WriteNumber("steps", info.Steps); + w.WriteNumber("teleports", info.Teleports); + } + w.WriteString("outcome", outcome); + if (reason.Length > 0) w.WriteString("reason", reason); + w.WriteEndObject(); + }); + + // ── Worker ops: what the tick freezes, then the worker ────────────── + + private void StartWork(RouteJob j, long now) + { + RouteRequest q = j.Request; + Func? work = q.Op switch + { + RouteOp.Plan or RouteOp.MakeRoute => PrepareTrip(j, now), + RouteOp.MakeLoop => PrepareLoop(j, now), + RouteOp.MakePath => PreparePath(j, now), + _ => PrepareInfo(j), + }; + if (work == null) return; // refused on the tick (already finished) + _workJob = j; + _workStartMs = now; + _workTimedOut = false; + _workTask = Task.Run(work); + } + + /// A make op's name that is taken, unless overwrite was asked: refused before any work. + private bool NameTaken(RouteJob j, long now) + { + RouteRequest q = j.Request; + if (q.Overwrite || !File.Exists(Path.Combine(NavProfilesDir, q.Name + ".nav"))) return false; + FailJob(j, $"{q.Name}.nav is already in RynthAi's NavProfiles; ask again with overwrite to replace it", now); + return true; + } + + /// The portal objects the client sees within of (x, y), as avoid circles. Tick thread. + private List LivePortalsNear(double x, double y, double range) + { + var list = new List(); + if (!Host.HasGetLiveObjectIds) return list; + foreach (uint id in Host.GetLiveObjectIds()) + { + if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; + if (!Host.TryGetObjectPosition(id, out uint cell, out float ox, out float oy, out _) || cell == 0 || (cell & 0xFFFF) >= 0x100) continue; + double wx = ((cell >> 24) & 0xFF) * 192.0 + ox, wy = ((cell >> 16) & 0xFF) * 192.0 + oy; + if (Math.Abs(wx - x) > range || Math.Abs(wy - y) > range) continue; + Host.TryGetObjectName(id, out string name); + list.Add(new PortalAvoid.Spot(wx, wy, PortalAvoid.LiveRadius, name ?? "")); + } + return list; + } + + // plan, makeroute: plan on the tick (as /rnav route), the trip's path and the file on the worker. + private Func? PrepareTrip(RouteJob j, long now) + { + RouteRequest q = j.Request; + if (q.Op == RouteOp.MakeRoute && NameTaken(j, now)) return null; + if (!_hasPose) { FailJob(j, "no player position yet", now); return null; } + if (!ResolveTarget(q.To, out string name, out _, out double ns, out double ew, out string error)) { FailJob(j, error, now); return null; } + TravelPlan.Result plan = PlanRoute(name, ns, ew, out List recalls, q.Portals); + if (plan.Refusal.Length > 0) { FailJob(j, $"no way to {name}: {plan.Refusal}", now); return null; } + bool portalsOn = q.Portals ?? _portalsEnabled; + PlannedTrip trip; + if (q.Show || q.FromChat) + { + // As /rnav route: the panel shows the plan and the markers its path (worked out below, once). + _shownRoute = plan.Steps ?? new List { new(ns, ew, false, false, "walk") }; + _shownRouteFor = name; _shownRouteEst = plan.Est; _shownRouteLive = false; _routeVersion++; + trip = SetTrip(plan.Steps, name, ns, ew, recalls, "", live: false, buildPath: false); + } + else trip = NewTrip(plan.Steps, name, ns, ew, recalls, "", live: false); + if (q.FromChat) Say($"{q.Command}: working out the walk to {name}…"); + RouteJobs.Start(j, $"working out the walk to {name}", now); + + NavGraph? g = UsableGraph(); + IReadOnlyList portals = AtlasPortalSpots(); + TownNet? net = _townNet; + string dir = NavDataDir, folder = NavProfilesDir; + int teleports = plan.Teleports; + return () => TripWork(q, trip, g, portals, net, dir, folder, teleports, portalsOn); + } + + private static RouteWork TripWork(RouteRequest q, PlannedTrip trip, NavGraph? g, IReadOnlyList portals, + TownNet? net, string dir, string folder, int teleports, bool portalsOn) + { + var o = new RouteWork { Trip = trip }; + long t0 = Environment.TickCount64; + var finder = new TilePathFinder(dir, g, portals); + TripPath path = TripPathBuilder.Build(trip, (WorldPt a, WorldPt b, bool intoPortal, out string note) => finder.Walk(a, b, intoPortal, out note), net); + o.Path = path; + o.Log.Add($"[RynthNav] job: the walk to {trip.Goal}: {trip.Count} step(s), {finder.TilesRead} tile(s) read, {Environment.TickCount64 - t0} ms"); + foreach (string n in path.Notes) o.Log.Add($"[RynthNav] job: trip path: {n}"); + TripSummary sum = TripSummary.Of(trip, path); + + if (q.Op == RouteOp.Plan) + { + o.Ok = true; + o.Detail = $"to {trip.Goal}: {sum.Steps.Count} step(s), {NavCoords.FmtDistance(sum.Yards)} walking, {sum.Teleports} teleport(s), about {sum.Minutes:F1} min"; + o.Json = RouteJson.Write(w => + { + w.WriteStartObject(); + w.WriteStartObject("to"); + w.WriteString("name", trip.Goal); + RouteJson.Num(w, "ns", trip.GoalNs, 4); + RouteJson.Num(w, "ew", trip.GoalEw, 4); + w.WriteEndObject(); + w.WriteBoolean("portals", portalsOn); + sum.WriteFields(w); + RouteJson.Strings(w, "notes", path.Notes); + w.WriteEndObject(); + }); + return o; + } + + // makeroute: as saveroute (RynthNavPlugin.SaveRoute.cs). + NavRouteExport.Result r = NavRouteExport.Convert(trip, path, net); + if (r.Route.Points.Count == 0) + return Failed(o, q, $"nothing to save: {(r.StopReason.Length > 0 ? r.StopReason : "the trip has no steps")}"); + if (!SaveNav(o, q, folder, r.Route, out string file)) return o; + double yards = RouteInfo.Length(r.Route); + o.Ok = true; + o.Detail = $"saved {q.Name}.nav: {r.Route.Points.Count} steps, {NavCoords.FmtDistance(yards)} walking"; + string line = $"{q.Command}: saved {q.Name}.nav to {folder}: {r.Route.Points.Count} steps ({r.Waypoints} waypoints" + + (r.Portals > 0 ? $", {r.Portals} portal(s)" : "") + (r.Recalls + r.Chats > 0 ? $", {r.Recalls + r.Chats} recall(s)" : "") + + $"). RynthAi: pick it in Nav, or /ra nav load {q.Name}."; + if (r.StoppedAt >= 0) line += $" It stops short of {trip.Goal}: {r.StopReason}."; + if (path.Notes.Count > 0) line += $" Check it: {path.Notes[0]}{(path.Notes.Count > 1 ? $" (+{path.Notes.Count - 1} more in the log)" : "")}."; + o.Lines.Add(line); + o.Log.Add($"[RynthNav] {line} ({file})"); + o.Json = MakeJson(q, file, r.Route, yards, null, w => + { + w.WriteStartObject("to"); + w.WriteString("name", trip.Goal); + RouteJson.Num(w, "ns", trip.GoalNs, 4); + RouteJson.Num(w, "ew", trip.GoalEw, 4); + w.WriteEndObject(); + w.WriteNumber("waypoints", r.Waypoints); + w.WriteNumber("portals", r.Portals); + w.WriteNumber("recalls", r.Recalls + r.Chats); + w.WriteNumber("teleports", teleports); + if (r.StoppedAt >= 0) w.WriteString("stoppedShort", r.StopReason); else w.WriteNull("stoppedShort"); + }, path.Notes); + return o; + } + + // makeloop: the centre and the portals on the tick, the loop and the file on the worker. + private Func? PrepareLoop(RouteJob j, long now) + { + RouteRequest q = j.Request; + if (NameTaken(j, now)) return null; + WorldPt centre; + if (q.Here) + { + if (!_hasPose) { FailJob(j, "no player position yet", now); return null; } + if (InDungeon(_cellId) || !IsOnMap(_cellId)) { FailJob(j, "you're in a dungeon: loops are made on the landscape (give at )", now); return null; } + centre = new WorldPt(_wx, _wy, _wz); + } + else centre = WorldPt.FromMap(q.AtNs, q.AtEw, double.NaN); + if (centre.Landblock == uint.MaxValue) { FailJob(j, $"{NavCoords.Fmt(centre.Ns, centre.Ew)} is off the map", now); return null; } + if (!File.Exists(Path.Combine(NavDataDir, $"nav_{centre.Landblock:X4}.tile"))) + { FailJob(j, $"no navmesh at {NavCoords.Fmt(centre.Ns, centre.Ew)} (landblock 0x{centre.Landblock:X4} has no tile in {NavDataDir})", now); return null; } + + IReadOnlyList atlasPortals = AtlasPortalSpots(); + List live = _hasPose ? LivePortalsNear(centre.X, centre.Y, q.Radius + LoopLivePortalUnits) : new List(); + int points = q.Points > 0 ? q.Points : RouteShape.DefaultPoints(q.Radius); + var opt = new LoopMaker.LoopOptions { Radius = q.Radius, Points = points, WallClearance = _avoidWalls ? _wallClearance : 0 }; + if (q.FromChat) Say($"{q.Command}: choosing {points} points round {NavCoords.Fmt(centre.Ns, centre.Ew)} within {q.Radius:F0} yd…"); + RouteJobs.Start(j, $"choosing {points} points round {NavCoords.Fmt(centre.Ns, centre.Ew)}", now); + string dir = NavDataDir, folder = NavProfilesDir; + bool tried = _buildingsTried; + BuildingOutlines? buildings = _buildings; + return () => LoopWork(q, centre, opt, atlasPortals, live, dir, folder, tried, buildings); + } + + private static RouteWork LoopWork(RouteRequest q, WorldPt centre, LoopMaker.LoopOptions opt, IReadOnlyList atlasPortals, + List live, string dir, string folder, bool buildingsTried, BuildingOutlines? buildings) + { + var o = new RouteWork(); + if (!buildingsTried) + { + buildings = BuildingOutlines.Load(Path.Combine(dir, BuildingOutlines.FileName)); + o.BuildingsRead = true; o.Buildings = buildings; + } + long t0 = Environment.TickCount64; + var all = new List(live); + all.AddRange(atlasPortals); + var finder = new TilePathFinder(dir, null, atlasPortals, live); + LoopMaker.Result r = LoopMaker.Loop(finder, centre, opt, buildings, all); + o.Log.Add($"[RynthNav] job: loop round {NavCoords.Fmt(centre.Ns, centre.Ew)}, {opt.Radius:F0} yd: {(r.Ok ? $"{r.Points.Count} of {r.Asked} points, {r.Yards:F0} yd" : r.Error)}; " + + $"{finder.TilesRead} tile(s) read, {Environment.TickCount64 - t0} ms"); + foreach (LoopMaker.Dropped d in r.DroppedPoints) o.Log.Add($"[RynthNav] job: loop point at {NavCoords.Fmt(d.Ns, d.Ew)} dropped: {d.Why}"); + if (!r.Ok || r.Route == null) { Failed(o, q, r.Error); o.Json = MakeJson(q, "", null, 0, r.DroppedPoints, null, r.Notes, r.Error); return o; } + if (!SaveNav(o, q, folder, r.Route, out string file)) return o; + o.Ok = true; + o.Detail = $"saved {q.Name}.nav: {r.Points.Count} points, {NavCoords.FmtDistance(r.Yards)} a lap" + + (r.DroppedPoints.Count > 0 ? $", {r.DroppedPoints.Count} dropped" : ""); + string line = $"{q.Command}: saved {q.Name}.nav (circular): {r.Points.Count} points round {NavCoords.Fmt(r.Centre.Ns, r.Centre.Ew)}, " + + $"radius {opt.Radius:F0} yd, {NavCoords.FmtDistance(r.Yards)} a lap, {r.Route.Points.Count} waypoints" + + (r.DroppedPoints.Count > 0 ? $"; {r.DroppedPoints.Count} point(s) dropped ({r.DroppedPoints[0].Why}{(r.DroppedPoints.Count > 1 ? ", ..." : "")})" : "") + + $". RynthAi: /ra nav load {q.Name}."; + o.Lines.Add(line); + foreach (string n in r.Notes) o.Lines.Add($" {q.Command}: {n}"); + o.Log.Add($"[RynthNav] {line} ({file})"); + o.Json = MakeJson(q, file, r.Route, r.Yards, r.DroppedPoints, w => + { + RouteJson.Place(w, "centre", r.Centre.Ns, r.Centre.Ew); + RouteJson.Num(w, "radius", opt.Radius, 1); + w.WriteNumber("loopPoints", r.Points.Count); + w.WriteNumber("asked", r.Asked); + }, r.Notes); + return o; + } + + // makepath: the points and the portals on the tick, the legs and the file on the worker. + private Func? PreparePath(RouteJob j, long now) + { + RouteRequest q = j.Request; + if (NameTaken(j, now)) return null; + var pts = new List(q.Path.Count); + double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; + foreach (var (ns, ew) in q.Path) + { + WorldPt p = WorldPt.FromMap(ns, ew, double.NaN); + pts.Add(p); + minX = Math.Min(minX, p.X); minY = Math.Min(minY, p.Y); maxX = Math.Max(maxX, p.X); maxY = Math.Max(maxY, p.Y); + } + IReadOnlyList atlasPortals = _avoidPortals ? AtlasPortalSpots() : Array.Empty(); + var live = new List(); + if (_avoidPortals && _hasPose) + foreach (PortalAvoid.Spot s in LivePortalsNear((minX + maxX) / 2, (minY + maxY) / 2, Math.Max(maxX - minX, maxY - minY) / 2 + AvoidNearUnits)) + live.Add(s); + bool strict = _avoidPortals; + double wall = _avoidWalls ? _wallClearance : 0; + NavGraph? g = UsableGraph(); + if (q.FromChat) Say($"{q.Command}: walking out {q.Path.Count} points…"); + RouteJobs.Start(j, $"working out {q.Path.Count} points", now); + string dir = NavDataDir, folder = NavProfilesDir; + return () => PathWork(q, pts, g, atlasPortals, live, strict, wall, dir, folder); + } + + private static RouteWork PathWork(RouteRequest q, List pts, NavGraph? g, IReadOnlyList atlasPortals, + List live, bool strict, double wall, string dir, string folder) + { + var o = new RouteWork(); + long t0 = Environment.TickCount64; + var finder = new TilePathFinder(dir, g, atlasPortals, live) { StrictPortals = strict, WallClearance = wall }; + var all = new List(live); + all.AddRange(atlasPortals); + LoopMaker.Result r = LoopMaker.Path(finder, pts, q.PathType, TripPathBuilder.MaxSpacing / 2, all); + o.Log.Add($"[RynthNav] job: path through {pts.Count} points ({RouteInfo.TypeName(q.PathType)}): {(r.Ok ? $"{r.Legs.Count} leg(s), {r.Yards:F0} yd" : r.Error)}; " + + $"{finder.TilesRead} tile(s) read, {Environment.TickCount64 - t0} ms"); + if (!r.Ok || r.Route == null) { Failed(o, q, r.Error); return o; } + if (!SaveNav(o, q, folder, r.Route, out string file)) return o; + o.Ok = true; + string type = RouteInfo.TypeName(q.PathType); + o.Detail = $"saved {q.Name}.nav: {pts.Count} points, {r.Legs.Count} leg(s), {NavCoords.FmtDistance(r.Yards)}"; + string line = $"{q.Command}: saved {q.Name}.nav ({type}): {pts.Count} points, {r.Legs.Count} leg(s), {NavCoords.FmtDistance(r.Yards)}" + + $"{(q.PathType == NavRouteType.Circular ? " a lap" : "")}, {r.Route.Points.Count} waypoints. RynthAi: /ra nav load {q.Name}."; + o.Lines.Add(line); + o.Log.Add($"[RynthNav] {line} ({file})"); + o.Json = MakeJson(q, file, r.Route, r.Yards, r.DroppedPoints, w => + { + w.WriteNumber("given", pts.Count); + w.WriteNumber("legs", r.Legs.Count); + }, r.Notes); + return o; + } + + // info: the file on the worker; what a landblock is (dungeon or not) and the spell names from the tick. + private Func? PrepareInfo(RouteJob j) + { + RouteRequest q = j.Request; + bool hasPlayer = PlayerMapPos(out double pns, out double pew); + HashSet dungeons = _dungeonLandblocks, map = _mapLandblocks; + var spells = new Dictionary + { + [RecallPlanner.LifestoneRecall] = "Lifestone Recall", [RecallPlanner.PortalRecall] = "Portal Recall", + [RecallPlanner.PrimaryPortalTieRecall] = "Primary Portal Tie Recall", [RecallPlanner.SecondaryPortalTieRecall] = "Secondary Portal Tie Recall", + }; + foreach (AtlasRecall r in _atlas.Recalls) spells.TryAdd(r.SpellId, r.Name); + string dir = NavDataDir, folder = NavProfilesDir; + RouteJobs.Start(j, $"reading {q.Name}.nav", NowMs); + return () => InfoWork(q, folder, dir, hasPlayer, pns, pew, dungeons, map, spells); + } + + private static RouteWork InfoWork(RouteRequest q, string folder, string dir, bool hasPlayer, double pns, double pew, + HashSet dungeons, HashSet map, Dictionary spells) + { + var o = new RouteWork(); + string file = Path.Combine(folder, q.Name + ".nav"); + if (!File.Exists(file)) return Failed(o, q, $"no route called {q.Name} in RynthAi's NavProfiles ({folder})"); + NavRouteParser route = NavRouteParser.Load(file); + bool IsDungeon(uint lb) => dungeons.Contains(lb) || (!map.Contains(lb) && File.Exists(Path.Combine(dir, DungeonTileFile.FileName(lb)))); + RouteInfo info = RouteInfo.Describe(route, q.Name, file, IsDungeon, hasPlayer, pns, pew, id => spells.TryGetValue(id, out string? n) ? n : null); + if (info.Points == 0 && info.FollowTarget.Length == 0) + return Failed(o, q, $"{q.Name}.nav has no points{(info.Warning.Length > 0 ? $" ({info.Warning})" : "")}"); + o.Ok = true; + o.Detail = $"{info.Type}, {info.Points} point(s), {NavCoords.FmtDistance(info.Yards)}{(info.Dungeon ? ", a dungeon route" : "")}"; + o.Lines.AddRange(info.ChatLines()); + o.Json = RouteJson.Write(info.WriteJson); + return o; + } + + // ── Shared by the workers ──────────────────────────────────────────── + + private static RouteWork Failed(RouteWork o, RouteRequest q, string why) + { + o.Ok = false; + o.Detail = why; + o.Json = RouteJson.Error(why, ""); + o.Lines.Clear(); + o.Lines.Add($"{q.Command}: {why}"); + return o; + } + + /// Writes the route (never over a file there, unless asked); false with the job failed when it can't. + private static bool SaveNav(RouteWork o, RouteRequest q, string folder, NavRouteParser route, out string file) + { + if (NavRouteExport.Save(folder, q.Name, route, q.Overwrite, out file, out bool exists, out string error)) return true; + Failed(o, q, exists ? $"{q.Name}.nav is already in RynthAi's NavProfiles; ask again with overwrite to replace it" + : $"couldn't write {q.Name}.nav: {error}"); + return false; + } + + /// The make ops' result: file, name, type, points, yards, dropped points, notes, and the op's own fields. + private static string MakeJson(RouteRequest q, string file, NavRouteParser? route, double yards, List? dropped, + Action? extra, IReadOnlyList notes, string error = "") => RouteJson.Write(w => + { + w.WriteStartObject(); + if (error.Length > 0) w.WriteString("error", error); + w.WriteString("name", q.Name); + if (file.Length > 0) w.WriteString("file", file); else w.WriteNull("file"); + w.WriteString("type", route != null ? RouteInfo.TypeName(route.RouteType) : q.Op == RouteOp.MakeLoop ? "circular" : RouteInfo.TypeName(q.PathType)); + w.WriteNumber("points", route?.Points.Count ?? 0); + RouteJson.Num(w, "yards", yards, 0); + w.WriteNumber("dropped", dropped?.Count ?? 0); + w.WriteStartArray("droppedPoints"); + if (dropped != null) + foreach (LoopMaker.Dropped d in dropped) + { + w.WriteStartObject(); + RouteJson.Num(w, "ns", d.Ns, 4); + RouteJson.Num(w, "ew", d.Ew, 4); + w.WriteString("why", d.Why); + w.WriteEndObject(); + } + w.WriteEndArray(); + extra?.Invoke(w); + RouteJson.Strings(w, "notes", notes); + w.WriteEndObject(); + }); +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs index 7a84561..80663a4 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs @@ -1021,7 +1021,11 @@ public sealed partial class RynthNavPlugin "/rnav avoid — show; avoid portals on|off| | walls on|off| | corners \n" + "/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" + "/rnav mesh on|off | floor on|off | walls on|off | radius | triangles — draw the navmesh: green floor, red walls\n" + - "/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)"; + "/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)\n" + + "/rnav makeroute to [overwrite] — plan a trip and save it as a nav route in one go, no walking\n" + + "/rnav makeloop [at |here] radius [points ] [overwrite] — a hunting loop (circular nav) on walkable ground\n" + + "/rnav makepath [loop|line|once] ; ; ... [overwrite] — a nav through those points, each leg walked\n" + + "/rnav routeinfo — what a saved nav route is: type, points, yards, where, portals"; /// One /rnav command. Tick thread. private void RunCommand(string raw, bool fromPanel) @@ -1073,6 +1077,12 @@ public sealed partial class RynthNavPlugin case "markers": CmdMarkers(rest); break; case "mesh": CmdMesh(rest); break; case "saveroute": CmdSaveRoute(rest); break; + case "makeroute": + case "makeloop": + case "makepath": + case "routeinfo": + CmdRouteMaker(cmd, rest); // RynthNavPlugin.RouteMaker.cs + break; case "arrive": if (NavReplies.TryArrive(rest, out double yd)) { _arrow.ArriveUnits = yd; Say(NavReplies.Arrived(yd)); } else if (rest.Length == 0) Say(NavReplies.ArriveUsage(rest, _arrow.ArriveUnits)); @@ -1115,42 +1125,57 @@ public sealed partial class RynthNavPlugin private void CmdGo(string rest) { - string name, type; double ns, ew; + if (!ResolveGo(rest, out string name, out string type, out double ns, out double ew, out string enter, out string enterType, out string error)) + { + Note(error); + return; + } + StartGoto(name, type, ns, ew, enter, enterType); // StartWalk says "walking to ..." (or why it can't) + } + + /// + /// Where /rnav go (and the route maker's go op) walks to: a place or coordinates, the arrow's target + /// when nothing is given, and for a dungeon (or a portal) its entrance portal, walked into. False with + /// the line to say. Tick thread. + /// + private bool ResolveGo(string rest, out string name, out string type, out double ns, out double ew, + out string enter, out string enterType, out string error) + { + enter = ""; enterType = ""; error = ""; AtlasLocation? place; if (rest.Length == 0) { + name = ""; type = ""; ns = 0; ew = 0; ArrowStep? fin = _arrow.Final; - if (fin == null || !fin.OnMap) { Note("go where? /rnav go (or set the arrow first)"); return; } + if (fin == null || !fin.OnMap) { error = "go where? /rnav go (or set the arrow first)"; return false; } name = fin.Name; type = fin.Type; ns = fin.Ns; ew = fin.Ew; place = null; foreach (var l in _atlas.Locations) if (l.OnMap && l.Name == fin.Name && l.Type == fin.Type && NavCoords.Distance(l.Ns, l.Ew, ns, ew) < 3) { place = l; break; } } - else if (!ResolveTarget(rest, out name, out type, out ns, out ew, out string error)) + else if (!ResolveTarget(rest, out name, out type, out ns, out ew, out error)) { // A dungeon or portal the Atlas knows, but with no map position: say why, don't guess. foreach (var l in _atlas.Search(rest, null, 5)) if (!l.OnMap && Entrance.IsEntrance(l)) { Entrance.PortalFor(_atlas, l, false, 0, 0, out string offWhy); - if (offWhy.Length > 0) { Note("goto: " + offWhy); return; } + if (offWhy.Length > 0) { error = "goto: " + offWhy; return false; } } - Note(error); - return; + return false; } else place = _resolvedPlace; // A dungeon (or a portal): walk INTO its entrance portal and wait for the teleport. - string enter = "", enterType = ""; if (place != null && Entrance.IsEntrance(place)) { bool hasPos = PlayerMapPos(out double pns, out double pew); AtlasLocation? portal = Entrance.PortalFor(_atlas, place, hasPos, pns, pew, out string why); - if (portal == null) { Note("goto: " + why); return; } + if (portal == null) { error = "goto: " + why; return false; } ns = portal.Ns; ew = portal.Ew; enter = place.Name; enterType = place.Type; _nextEnterPortal = portal.Name; // the portal object a saved nav route uses (RynthNavPlugin.SaveRoute.cs) } - StartGoto(name, type, ns, ew, enter, enterType); // StartWalk says "walking to ..." (or why it can't) + return true; } private void CmdRoute(string rest) @@ -1293,6 +1318,7 @@ public sealed partial class RynthNavPlugin /// Starts walking to a place: the arrow points along the same route. private void StartGoto(string name, string type, double ns, double ew, string enter = "", string enterType = "") { + _goJobId = 0; // a goto of its own: no route maker go job's any more (RynthNavPlugin.RouteMaker.cs) _store.Touch(new SavedPlace { Name = name, Type = type, Ns = ns, Ew = ew }); lock (_reqGate) { _reqGotoNamed = (name, type, ns, ew, enter, enterType); } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs index ecc3444..36cb320 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs @@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthNav; public sealed partial class RynthNavPlugin : RynthPluginBase { internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNav"); - internal const string PluginVersion = "0.6.7"; + internal const string PluginVersion = "0.6.8"; // 0.6.8: the route maker (makeroute, makeloop, makepath, routeinfo, "RynthNav.Routes") internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion); /// Lets PluginExports log through this plugin's host (the base Log is protected). @@ -147,7 +147,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase LoadAvoidSettings(); LoadMarkerSettings(); LoadMeshSettings(); - Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})"); + Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas + route maker). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})"); InitTravel(); LoadGraph(); LoadTownNet(); @@ -213,6 +213,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase TickMarkers(); TickMeshView(); UpdateGoLine(); + TickRouteJobs(); FlushChat(); } @@ -426,6 +427,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase if (walk) { + _goJobId = 0; // a goto of its own: no route maker go job's any more StartWalk(given.Length > 0 ? given : NavCoords.Fmt(tns, tew), "", tns, tew); return; } @@ -850,6 +852,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase ResetBlocked(); AutoRun.Stop(); lock (_gate) _status = status; + _gotoEndStatus = status; _gotoEndSeq++; // a route maker go job reads how it ended (RynthNavPlugin.RouteMaker.cs) Host.Log($"[RynthNav] goto: {status}"); Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}"); _goNote = status == "arrived" && _gotoName.Length > 0 ? $"arrived at {_gotoName}" : status; @@ -949,19 +952,21 @@ public sealed partial class RynthNavPlugin : RynthPluginBase /// /// Plans a trip from where you stand (TravelPlan: the switches, a dungeon start, the land) and /// logs what it considered. Steps null = walk straight there; a refusal = there's no way, and why. - /// Tick thread. + /// : use portals and recalls or not this once (null: the switch; the + /// route maker's plan op). Tick thread. /// - private TravelPlan.Result PlanRoute(string name, double goalNs, double goalEw, out List recalls) + private TravelPlan.Result PlanRoute(string name, double goalNs, double goalEw, out List recalls, bool? portals = null) { + bool portalsOn = portals ?? _portalsEnabled; double startNs = NavCoords.NsFromWorld(_wy), startEw = NavCoords.EwFromWorld(_wx); bool startOnMap = IsOnMap(_cellId); var recallNotes = new List(); recalls = _charKey.Length == 0 ? new List() : RecallPlanner.Build(_atlas, _known, _memory, _charKey, recallNotes); if (_charKey.Length == 0) recallNotes.Add("not logged in yet"); var hubNotes = new List(); - HubLinks? hub = _portalsEnabled ? CurrentHubLinks(hubNotes) : null; + HubLinks? hub = portalsOn ? CurrentHubLinks(hubNotes) : null; if (hub != null && _preferAphus && _recallsEnabled) hub = ViaAphus(hub, recalls, hubNotes); - if (_portalsEnabled) EnsurePortalsLoaded(); + if (portalsOn) EnsurePortalsLoaded(); // Walks that can't be done over land (another landmass) are left out, so an island or the // far side of water is only reached by a portal, a recall or the Town Network. NavGraph? g = UsableGraph(); @@ -970,12 +975,12 @@ public sealed partial class RynthNavPlugin : RynthPluginBase NavGraph.LandblockAt(NavCoords.WorldX(bew), NavCoords.WorldY(bns))) != false; bool? land = startOnMap && g != null ? g.SameLand(CurrentLandblock, NavGraph.LandblockAt(NavCoords.WorldX(goalEw), NavCoords.WorldY(goalNs))) : null; - TravelPlan.Result r = TravelPlan.Plan(_portalsEnabled ? _portals : null, RecallPlanner.Links(recalls), hub, - _portalsEnabled, _recallsEnabled, startOnMap, startNs, startEw, goalNs, goalEw, canWalk, land, name); + TravelPlan.Result r = TravelPlan.Plan(portalsOn ? _portals : null, RecallPlanner.Links(recalls), hub, + portalsOn, _recallsEnabled, startOnMap, startNs, startEw, goalNs, goalEw, canWalk, land, name); - Host.Log($"[RynthNav] plan {name}: {r.Basis}; {(_portalsEnabled ? $"{_portals?.Count ?? 0} portals" : "no portals")}, " + Host.Log($"[RynthNav] plan {name}: {r.Basis}; {(portalsOn ? $"{_portals?.Count ?? 0} portals" : "no portals")}, " + $"{recalls.Count} recall(s) ready" + (recalls.Count > 0 ? " (" + string.Join(", ", recalls.ConvertAll(o => o.Name)) + ")" : "") - + $", Town Network {(hub == null ? (_portalsEnabled ? "not loaded" : "unused") : $"{hub.Entries.Count} entries / {hub.Exits.Count} exits")}" + + $", Town Network {(hub == null ? (portalsOn ? "not loaded" : "unused") : $"{hub.Entries.Count} entries / {hub.Exits.Count} exits")}" + $", land check {(canWalk == null ? "off (no route graph)" : "on")}" + (startOnMap ? "" : $" (in landblock 0x{CurrentLandblock:X4})")); foreach (string n in recallNotes) Host.Log($"[RynthNav] plan: recall left out: {n}"); diff --git a/Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs b/Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs index 55c000e..17fad8b 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs @@ -16,6 +16,13 @@ namespace RynthNav.Routing; /// except the leg's own. Its own navmesh, filled from the tile files a few tiles at a time, so it /// runs on a worker and never touches the walker's (tick-thread) navmesh. One instance per worker. /// Without a route graph only short legs (a few landblocks) are planned; longer ones get none. +/// +/// The route maker (LoopMaker, RynthNavPlugin.RouteMaker.cs) sets the stricter options: no way +/// through a portal's circle at all (), no straight line over a navmesh gap +/// (), corners pushed off walls (, RynthNav's own walks +/// do this as they go), building floors left out where there's another way (); +/// and it asks this navmesh for ground (, , ). +/// With none of them set it plans exactly as it always has. /// internal sealed class TilePathFinder { @@ -27,27 +34,41 @@ internal sealed class TilePathFinder private readonly string _dir; private readonly NavGraph? _graph; - private readonly IReadOnlyList _portals; + private readonly IReadOnlyList _portals, _live; private readonly DtNavMesh _nav; private DtNavMeshQuery _query; private readonly HashSet _loaded = new(), _bad = new(); private readonly PortalAvoid _avoid = new(); private readonly AvoidFilter _filter; + private readonly AreaFilter _area; private readonly DtQueryDefaultFilter _plain = new(); + private string _pieceNote = ""; /// Tile files read so far (for the log). public int TilesRead { get; private set; } - public TilePathFinder(string navDataDir, NavGraph? graph, IReadOnlyList? portals) + /// Never through a portal's circle: no plan through one when there's no way round, and a bent path that still crosses one is refused. + public bool StrictPortals { get; set; } + /// A stretch the navmesh can't plan fails the walk, instead of becoming a straight line. + public bool NoGaps { get; set; } + /// Each corner pushed this far out from the wall it turns round, where the ground is walkable (0 = not). + public double WallClearance { get; set; } + /// Ground kept off where there is another way (east, north: true = keep off); null = none. + public Func? AvoidArea { get; set; } + + public TilePathFinder(string navDataDir, NavGraph? graph, IReadOnlyList? portals, + IReadOnlyList? livePortals = null) { _dir = navDataDir; _graph = graph; _portals = portals ?? Array.Empty(); + _live = livePortals ?? Array.Empty(); _nav = new DtNavMesh(); var p = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = MaxTiles, maxPolys = 1 << 16 }; _nav.Init(p, 6); _query = new DtNavMeshQuery(_nav); _filter = new AvoidFilter(_avoid); + _area = new AreaFilter(_filter); } /// @@ -88,6 +109,12 @@ internal sealed class TilePathFinder { bool last = k + 2 == anchors.Count; List? piece = Piece(anchors[k], anchors[k + 1], last && ownPortal ? anchors[k + 1] : null); + if (piece == null && NoGaps) + { + note = $"no navmesh path from {NavCoords.Fmt(anchors[k].Ns, anchors[k].Ew)} to {NavCoords.Fmt(anchors[k + 1].Ns, anchors[k + 1].Ew)}" + + (_pieceNote.Length > 0 ? ": " + _pieceNote : ""); + return null; + } if (piece == null) { gaps++; piece = new List { anchors[k], anchors[k + 1] }; } for (int i = 1; i < piece.Count; i++) path.Add(piece[i]); } @@ -129,35 +156,51 @@ internal sealed class TilePathFinder return (Math.Abs(ax - bx) + 1) * (Math.Abs(ay - by) + 1); } - /// The Detour path a→b (both ends' tiles and those between loaded); null when there's none. + /// The Detour path a→b (both ends' tiles and those between loaded); null when there's none (_pieceNote: why). private List? Piece(WorldPt a, WorldPt b, WorldPt? own) { - if (!LoadBox(a, b)) return null; + _pieceNote = ""; + if (!LoadBox(a, b)) { _pieceNote = "no navmesh tiles there"; return null; } var half = new RcVec3f(8, 600, 8); var pa = new RcVec3f((float)a.X, double.IsNaN(a.H) ? 0f : (float)a.H, (float)a.Y); var pb = new RcVec3f((float)b.X, double.IsNaN(b.H) ? 0f : (float)b.H, (float)b.Y); _query.FindNearestPoly(pa, half, _plain, out long sRef, out RcVec3f sPt, out _); _query.FindNearestPoly(pb, half, _plain, out long gRef, out RcVec3f gPt, out _); - if (sRef == 0 || gRef == 0) return null; + if (sRef == 0 || gRef == 0) { _pieceNote = $"no walkable ground at its {(sRef == 0 ? "start" : "end")}"; return null; } // Portals near this piece, except the leg's own. var near = new List(); + var nearLive = new List(); double minX = Math.Min(a.X, b.X) - AvoidNearUnits, maxX = Math.Max(a.X, b.X) + AvoidNearUnits; double minY = Math.Min(a.Y, b.Y) - AvoidNearUnits, maxY = Math.Max(a.Y, b.Y) + AvoidNearUnits; foreach (PortalAvoid.Spot sp in _portals) if (sp.X >= minX && sp.X <= maxX && sp.Y >= minY && sp.Y <= maxY) near.Add(sp); - if (own is WorldPt ownAt) _avoid.Set(Array.Empty(), near, ownAt.X, ownAt.Y, OwnPortalUnits); - else _avoid.Set(Array.Empty(), near); + foreach (PortalAvoid.Spot sp in _live) + if (sp.X >= minX && sp.X <= maxX && sp.Y >= minY && sp.Y <= maxY) nearLive.Add(sp); + if (own is WorldPt ownAt) _avoid.Set(nearLive, near, ownAt.X, ownAt.Y, OwnPortalUnits); + else _avoid.Set(nearLive, near); _filter.AllowA = sRef; _filter.AllowB = gRef; Span polys = new long[1024]; - _query.FindPath(sRef, gRef, sPt, gPt, _filter, polys, out int pc, 1024); + int pc = 0; + if (AvoidArea != null) + { + // Off the floors kept off (buildings) when there's a way; else as without. + _area.Inside = AvoidArea; _area.AllowA = sRef; _area.AllowB = gRef; + _query.FindPath(sRef, gRef, sPt, gPt, _area, polys, out pc, 1024); + if (pc == 0 || polys[pc - 1] != gRef) pc = 0; + } + if (pc == 0) _query.FindPath(sRef, gRef, sPt, gPt, _filter, polys, out pc, 1024); if ((pc == 0 || polys[pc - 1] != gRef) && _avoid.Count > 0) + { _query.FindPath(sRef, gRef, sPt, gPt, _plain, polys, out pc, 1024); - if (pc == 0 || polys[pc - 1] != gRef) return null; + // Strict: a way that only goes through a portal's circle is no way (and that is why). + if (StrictPortals && pc > 0 && polys[pc - 1] == gRef) { _pieceNote = "no way round " + PortalsNamed(_avoid.Spots); return null; } + } + if (pc == 0 || polys[pc - 1] != gRef) { _pieceNote = "the navmesh doesn't join them (water, a cliff or a wall between)"; return null; } Span sp2 = new DtStraightPath[256]; _query.FindStraightPath(sPt, gPt, polys[..pc], pc, sp2, out int spc, 256, 0); - if (spc < 2) return null; + if (spc < 2) { _pieceNote = "no straight path along the navmesh"; return null; } var corners = new List<(double X, double Y)>(spc); List? heights = new List(spc); @@ -182,6 +225,20 @@ internal sealed class TilePathFinder corners = _avoid.Bend(corners, OnMesh, 12, LegOnMesh); if (corners.Count != before) heights = null; // bend corners: heights filled from the neighbours } + if (WallClearance > 0 && corners.Count > 2) + { + // As RynthNav's own walks (Replan): each corner pushed out along the turn's outside, onto ground. + var pushed = new List<(double X, double Y)>(corners); + PushFromWalls(pushed, heights, pa.Y); + if (!StrictPortals || Crosses(pushed) < 0) corners = pushed; // a push into a portal's circle isn't taken + } + int hit = StrictPortals ? Crosses(corners) : -1; + if (hit >= 0) + { + string name = _avoid.Spots[hit].Name; + _pieceNote = $"it would cross {(name.Length > 0 ? "the portal " + name : "a portal")}"; + return null; + } var o = new List(corners.Count) { a with { H = heights != null ? heights[0] : (double.IsNaN(a.H) ? sPt.Y : a.H) } }; for (int i = 1; i < corners.Count; i++) o.Add(new WorldPt(corners[i].X, corners[i].Y, heights != null ? heights[i] : double.NaN)); @@ -189,6 +246,95 @@ internal sealed class TilePathFinder return o; } + /// "the portal X" / "the portals X and Y" / "3 portals" for a refusal. + private static string PortalsNamed(IReadOnlyList spots) + { + var names = new List(); + foreach (PortalAvoid.Spot s in spots) if (s.Name.Length > 0 && !names.Contains(s.Name)) names.Add(s.Name); + if (names.Count == 0) return spots.Count == 1 ? "a portal" : $"{spots.Count} portals"; + if (names.Count > 2) return $"{spots.Count} portals ({names[0]}, {names[1]}, ...)"; + return names.Count == 1 ? "the portal " + names[0] : $"the portals {names[0]} and {names[1]}"; + } + + /// + /// The first kept-out circle a leg of enters (or its end lies in), or -1. A circle + /// the start is already in doesn't count: that's where the walk begins (the walker steers out of it). + /// + private int Crosses(IReadOnlyList<(double X, double Y)> pts) + { + IReadOnlyList spots = _avoid.Spots; + if (pts.Count == 0) return -1; + for (int k = 0; k < spots.Count; k++) + { + PortalAvoid.Spot s = spots[k]; + if (Math.Sqrt((pts[0].X - s.X) * (pts[0].X - s.X) + (pts[0].Y - s.Y) * (pts[0].Y - s.Y)) < s.R) continue; + for (int i = 1; i < pts.Count; i++) + if (PortalAvoid.SegmentDistance(s.X, s.Y, pts[i - 1].X, pts[i - 1].Y, pts[i].X, pts[i].Y) < s.R - 0.05) return k; + } + return -1; + } + + /// + /// Walls: each corner the path turns round sits on the mesh's edge; push it + /// out along the turn's outside bisector where the ground is walkable (inside a polygon, not merely + /// near one), as the walker's Replan does. The ends never move. + /// + private void PushFromWalls(List<(double X, double Y)> wps, List? heights, float startH) + { + for (int i = 1; i < wps.Count - 1; i++) + { + var (px, py) = wps[i]; var (ax, ay) = wps[i - 1]; var (bx, by) = wps[i + 1]; + double ux = ax - px, uy = ay - py, ul = Math.Sqrt(ux * ux + uy * uy); + double vx = bx - px, vy = by - py, vl = Math.Sqrt(vx * vx + vy * vy); + if (ul < 0.5 || vl < 0.5) continue; + double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy); + if (ol < 0.05) continue; // straight on: no corner to clear + double nx = px + ox / ol * WallClearance, ny = py + oy / ol * WallClearance; + float h = heights != null && i < heights.Count ? (float)heights[i] : startH; + _query.FindNearestPoly(new RcVec3f((float)nx, h, (float)ny), new RcVec3f(0.3f, 24, 0.3f), _plain, out long rr, out RcVec3f rp, out _); + if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) wps[i] = (nx, ny); + } + } + + // ── Ground for the route maker (LoopMaker) ─────────────────────────── + + /// Loads the tiles under the box (world units); false when it's more than this navmesh holds at once, or there are none. + public bool LoadArea(double minX, double minY, double maxX, double maxY) => + LoadBox(new WorldPt(minX, minY, double.NaN), new WorldPt(maxX, maxY, double.NaN)); + + /// + /// Walkable ground within yards (across) of , the nearest + /// to its height (NaN: to height 0, so the lowest floor); its tiles must be loaded. False when none. + /// + public bool Snap(WorldPt p, double reach, out WorldPt ground, out long poly) + { + ground = p; + var at = new RcVec3f((float)p.X, double.IsNaN(p.H) ? 0f : (float)p.H, (float)p.Y); + _query.FindNearestPoly(at, new RcVec3f((float)reach, 600, (float)reach), _plain, out poly, out RcVec3f pt, out _); + if (poly == 0) return false; + ground = new WorldPt(pt.X, pt.Z, pt.Y); + if (ground.FlatDistance(p) > reach) { poly = 0; return false; } // the search box's corner: farther than asked + return true; + } + + /// How far ground found by is from the navmesh's edge (a wall, a drop, water), at most . + public double WallDistance(WorldPt ground, long poly, double max) + { + DtStatus st = _query.FindDistanceToWall(poly, new RcVec3f((float)ground.X, (float)ground.H, (float)ground.Y), (float)max, _plain, out float d, out _, out _); + return st.Failed() ? 0 : Math.Min(d, max); + } + + /// + /// A leg between two points on ground already loaded (no route graph: a loop's legs are short), with + /// the options set; null when there is none, and says why. + /// + public List? Leg(WorldPt from, WorldPt to, out string note) + { + List? piece = Piece(from, to, null); + note = piece == null ? _pieceNote : ""; + return piece; + } + /// Loads the tiles of the box a..b (evicting others when full); false when it's too big or none loads. private bool LoadBox(WorldPt a, WorldPt b) { diff --git a/Plugins/RynthCore.Plugin.RynthNav/TripSummary.cs b/Plugins/RynthCore.Plugin.RynthNav/TripSummary.cs new file mode 100644 index 0000000..8f7ecbb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/TripSummary.cs @@ -0,0 +1,102 @@ +using System.Collections.Generic; +using System.Text.Json; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// A planned trip in figures (the "RynthNav.Routes" plan op): each step as walk, portal, recall or +/// town (the Town Network), with its name, where it is, the yards walked on it (the worked-out path +/// where there is one, else the straight line) and where a teleport lands; the yards in all, the +/// teleports, and a rough time: walking at PortalRoute.RunUnitsPerSecond, PortalRoute's overhead for +/// each teleport, and each recall's cast time. Host-free: the route tests build these. +/// +internal sealed class TripSummary +{ + public sealed class Step + { + public string Kind = "", Name = ""; + public double Ns = double.NaN, Ew = double.NaN, Yards; + public double LandNs = double.NaN, LandEw = double.NaN; + } + + public readonly List Steps = new(); + public double Yards; + public int Teleports; + public double CastSeconds; + + /// Rough minutes for the whole trip (see the class notes). + public double Minutes => + (Yards / PortalRoute.RunUnitsPerSecond + Teleports * PortalRoute.TeleportOverheadUnits / PortalRoute.RunUnitsPerSecond + CastSeconds) / 60.0; + + private static double Length(WorldPt[]? pts) + { + double d = 0; + if (pts != null) for (int i = 1; i < pts.Length; i++) d += pts[i - 1].FlatDistance(pts[i]); + return d; + } + + /// The trip's steps with their yards from (null: straight lines). + public static TripSummary Of(PlannedTrip trip, TripPath? path) + { + var t = new TripSummary(); + bool own = path != null && path.TripId == trip.Id; + for (int i = 0; i < trip.Count; i++) + { + RouteStep s = trip.Steps[i]; + var st = new Step(); + if (!double.IsNaN(s.LandNs)) { st.LandNs = s.LandNs; st.LandEw = s.LandEw; } + if (s.UseRecall) + { + TripRecall? r = trip.RecallOf(i); + st.Kind = "recall"; + st.Name = r?.Name ?? s.Label ?? ""; + if (trip.Point[i] is WorldPt at && (i > 0 || trip.StartOnMap)) { st.Ns = at.Ns; st.Ew = at.Ew; } // a first recall in a dungeon: no map position + t.CastSeconds += r?.CastSeconds ?? 0; + t.Teleports++; + } + else if (s.IsHub) + { + st.Kind = "town"; + st.Name = s.Label ?? ""; + st.Ns = s.LandNs; st.Ew = s.LandEw; + st.Yards = own && i < path!.Hub.Length ? Length(path.Hub[i]) : 0; + t.Teleports++; + } + else + { + st.Kind = s.UsePortal ? "portal" : "walk"; + st.Name = s.UsePortal ? trip.PortalName(i) : i == trip.Count - 1 ? trip.Goal : (s.Label ?? "walk"); + st.Ns = s.Ns; st.Ew = s.Ew; + WorldPt[]? w = own && i < path!.Walks.Length ? path.Walks[i] : null; + st.Yards = w != null ? Length(w) + : trip.WalkFrom[i] is WorldPt f && trip.Point[i] is WorldPt p ? f.FlatDistance(p) : 0; + if (s.UsePortal) t.Teleports++; + } + t.Yards += st.Yards; + t.Steps.Add(st); + } + return t; + } + + /// The steps and totals as the plan op's result fields (inside an object the caller opened). + public void WriteFields(Utf8JsonWriter w) + { + w.WriteStartArray("steps"); + foreach (Step s in Steps) + { + w.WriteStartObject(); + w.WriteString("kind", s.Kind); + w.WriteString("name", s.Name); + RouteJson.Num(w, "ns", s.Ns, 4); + RouteJson.Num(w, "ew", s.Ew, 4); + RouteJson.Num(w, "yards", s.Yards, 0); + if (double.IsFinite(s.LandNs)) RouteJson.Place(w, "land", s.LandNs, s.LandEw); + w.WriteEndObject(); + } + w.WriteEndArray(); + RouteJson.Num(w, "yards", Yards, 0); + w.WriteNumber("teleports", Teleports); + RouteJson.Num(w, "minutes", Minutes, 1); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj index 6ffbdeb..39022d5 100644 --- a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj +++ b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj @@ -29,6 +29,11 @@ + + + + diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index fef99c6..b50b064 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -101,6 +101,7 @@ internal sealed class PacedAction public uint Target; // a cast's target (the held-cast turn faces it) public bool Script; // a cast a script chose (the combat hook): the breaker waits ScriptCastMinBreakMs public bool WieldedAtSend; + public bool OnSelf; // an item used on the character (a kit): the heal grace may go ahead of it public bool ResultSeen; // a cast's result is in (enchantment / chat); the server is in its recoil public bool HealQueued; // the one heal allowed behind that recoil went out public long ModeSeenMs; // when the client first read the requested mode @@ -147,6 +148,13 @@ internal static class ActionPacer public const long NoUseDoneFallbackMs = 600; /// The longest one ask for the player's turn holds RynthAi (RynthAiYieldApiV1.MaxHoldMs). public const long PlayerHoldMaxMs = 3000; + /// + /// The heal grace (2026-11-07): the longest a heal under a heal line waits on a use of an item on + /// the character (a kit) the server hasn't answered, and between the 'too busy' probes. Past it the + /// heal goes (a refusal is an answer too, and the next heal retries). An item on yourself has no + /// server turn to stop; corpse/door uses, casts, wields and the animation gate keep their rules. + /// + public const long HealGraceMs = 2000; private static readonly object Gate = new(); private static PacedAction? _cur; @@ -208,6 +216,7 @@ internal static class ActionPacer _heldTurns = 0; _forcedBreaks = 0; _jumpAt = 0; + _lootJumpAt = 0; _cycleBySpell.Clear(); _lastSeenSeq = int.MinValue; _lastFrameMs = 0; @@ -250,7 +259,8 @@ internal static class ActionPacer /// BEFORE the send. Logs once when it went out over another unanswered action (a player command, /// a meta, or a heal let ahead). /// - public static void Begin(RynthCoreHost host, PacedKind kind, uint id, string label, string who, int seqAtSend, int modeTarget = 0) + public static void Begin(RynthCoreHost host, PacedKind kind, uint id, string label, string who, int seqAtSend, int modeTarget = 0, + bool onSelf = false) { if (!Enabled || kind == PacedKind.None) return; PacedAction? prev = Current(host); @@ -258,6 +268,7 @@ internal static class ActionPacer var a = new PacedAction { Kind = kind, Id = id, Label = label, Who = who, SentMs = now, SeqAtSend = seqAtSend, ModeTarget = modeTarget, + OnSelf = onSelf && kind == PacedKind.ItemUse, }; if (kind == PacedKind.ItemUse) a.WieldedAtSend = IsWieldedByPlayer(host, id); string? over = null; @@ -466,6 +477,9 @@ internal static class ActionPacer { if (!Enabled) { why = ""; return true; } if (PlayerHoldsStart(host, who, out why)) return false; + // A buff, heal, kit or potion in the air is refused by ACE: wait for the landing. Combat checks + // it itself, at the attack, so a stance change is not held; loot and doors never. + if (who == "Buff" && LootJumpAirborne(host, out why)) return false; if (ServerBusyHolds(host, who, attackRepeat, out why, out bool tryAfterBusy, 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). @@ -529,6 +543,15 @@ internal static class ActionPacer lock (Gate) _healsAhead++; return true; } + // The heal grace: an item used on the character (a kit) still unanswered after HealGraceMs. + // A lost or swallowed kit is sent again instead of holding every heal to ItemUseMaxMs. + if (a.OnSelf && age >= HealGraceMs) + { + bool logAhead; + lock (Gate) { _healsAhead++; logAhead = a.LoggedWaits.Add(who + "/heal-grace"); } + if (logAhead) Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms, heal grace {HealGraceMs} ms)"); + return true; + } } why = $"{Describe(a.Kind, a.Label)} sent {age} ms ago by {a.Who} has no answer yet"; @@ -915,8 +938,11 @@ internal static class ActionPacer // 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; + // A waiting heal's probe comes at least every HealGraceMs (the doubling would reach BusyProbeMaxMs). + long probeWait = Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs); + if (heal == HealNeed.Heal) probeWait = Math.Min(probeWait, HealGraceMs); if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None && !healWaiting - && now - Math.Max(_busySince, _lastProbeAt) >= Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs)) + && now - Math.Max(_busySince, _lastProbeAt) >= probeWait) { probe = true; // spent in MayStart once the start passes its other checks (SpendTryAfterBusy) } @@ -1030,6 +1056,76 @@ internal static class ActionPacer lock (Gate) { if (!ReferenceEquals(_stageFor, forAction)) _turnedAt = 0; _stage = stage; _stageAt = now; _stageFor = forAction; } } + /// + /// Landed after a jump at from height : the height + /// is back (looked at from JumpLandMinMs on), or JumpLandMaxMs has passed whatever it says. + /// + private static bool Landed(RynthCoreHost host, long now, long jumpAt, float z0) + { + long air = now - jumpAt; + bool landed = air >= JumpLandMaxMs; + if (!landed && air >= JumpLandMinMs) + { + try { landed = !host.HasGetPlayerPose || (host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _) && Math.Abs(z - z0) < 0.1f); } + catch { landed = true; } + } + return landed; + } + + // Jump-loot (CorpseOpenController): the corpse pickup's tap jump. ACE refuses a cast, a swing, a + // shot, a kit, food or a potion in the air (Player_Magic/Melee/Missile, Healer, Food: IsJumping -> + // YouCantDoThatWhileInTheAir, 0x4EB), so combat and buffs wait until the character has landed + // instead of sending into a certain refusal. Loot does not: ACE takes a pickup and a corpse use in + // the air, so this never holds MayStart("Loot"). The hold is a pure wait, capped at JumpLandMaxMs + // from the jump, so a missed landing cannot stall a heal for longer than that. + private static long _lootJumpAt; // 0 = not in the air after a loot jump + private static float _lootJumpZ; + + /// A loot jump went out (the client took it): the character is in the air from now. + public static void NoteLootJump(RynthCoreHost host) + { + float z = 0; + try { if (host.HasGetPlayerPose) host.TryGetPlayerPose(out _, out _, out _, out z, out _, out _, out _, out _); } catch { } + long now = NowMs(); + lock (Gate) { _lootJumpAt = now; _lootJumpZ = z; } + } + + /// + /// True (with why) while the character is in the air after a loot jump: until the height is back + /// (from JumpLandMinMs) or JumpLandMaxMs at most. Pure wait: nothing is counted, refused or + /// retried. Independent of . + /// + public static bool LootJumpAirborne(RynthCoreHost host, out string why) + { + why = ""; + long jumpAt; float z0; + lock (Gate) { jumpAt = _lootJumpAt; z0 = _lootJumpZ; } + if (jumpAt == 0) return false; + long now = NowMs(); + if (!Landed(host, now, jumpAt, z0)) + { + why = $"in the air after the loot jump ({now - jumpAt} ms)"; + return true; + } + lock (Gate) { if (_lootJumpAt == jumpAt) _lootJumpAt = 0; } + return false; + } + + /// + /// Ms since the last loot jump went out, or -1 when none is noted (never jumped, landed and + /// cleared by , or forgotten). Read it BEFORE LootJumpAirborne + /// when the answer matters: a landing seen there clears the jump. + /// + public static long LootJumpAgeMs() + { + long jumpAt; + lock (Gate) jumpAt = _lootJumpAt; + return jumpAt == 0 ? -1 : NowMs() - jumpAt; + } + + /// No loot jump in the air any more (death, portal space, logout: RynthAiPlugin). + public static void ForgetLootJump() { lock (Gate) _lootJumpAt = 0; } + /// In the air after a breaker jump: hold until landed (height back, or JumpLandMaxMs). private static bool AirborneHolds(RynthCoreHost host, long now, out string why) { @@ -1038,12 +1134,7 @@ internal static class ActionPacer lock (Gate) { jumpAt = _jumpAt; z0 = _jumpZ; } if (jumpAt == 0) return false; long air = now - jumpAt; - bool landed = air >= JumpLandMaxMs; - if (!landed && air >= JumpLandMinMs) - { - try { landed = !host.HasGetPlayerPose || (host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _) && Math.Abs(z - z0) < 0.1f); } - catch { landed = true; } - } + bool landed = Landed(host, now, jumpAt, z0); if (!landed) { why = $"in the air after the stuck-cast jump ({air} ms)"; diff --git a/Plugins/Shared/DerethClock.cs b/Plugins/Shared/DerethClock.cs new file mode 100644 index 0000000..2550fed --- /dev/null +++ b/Plugins/Shared/DerethClock.cs @@ -0,0 +1,106 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/DerethClock.cs +// Dereth's clock: day or night now, the hour's name, and how long until the +// next dawn or dusk in real time (a request 2026-11-01: a small window with +// the real minutes until the next day/night change). Pure: the caller reads +// the raw clock and hands it in, so RynthDefective.Tests checks the math. +// +// The raw clock is the double at 0x008379A8 (acclient's Timer::cur_time, in +// seconds). It is only readable once the player is in world, and a fault +// there is an AccessViolation .NET can't catch: never read it before world +// entry (RynthAi's Meta/ExpressionEngine.cs ReadGameClock has the same rule). +// +// The calendar is RynthAi's meta expressions' (the same file, which matches +// UtilityBelt's DerethTime): 476.25 ticks an hour, 16 hours a day; day is +// hours 4 (Dawnsong) to 11 (Warmtide-and-Half), night 12 (Evensong) to 3 +// (Foredawn-and-Half). A tick is one real second (the clock counts seconds), +// so a Dereth day is 16 x 476.25 = 7620 s = 2 h 7 min of real time: 63.5 +// real minutes of day, then 63.5 of night. +// ============================================================================ + +using System; +using System.Globalization; + +namespace RynthCore.Plugin.Shared; + +/// Dereth's time of day at one reading of the clock. +internal readonly record struct DerethNow( + bool IsDay, + int Hour, // 0-15 + string HourName, // "Dawnsong", "Evensong-and-Half"... + double SecondsToChange) // real seconds until the next dawn (at night) or dusk (by day) +{ + /// What comes next: "Night" by day, "Day" at night. + public string Next => IsDay ? "Night" : "Day"; + + /// The hour the change comes at: Evensong (dusk) or Dawnsong (dawn). + public string NextHourName => DerethClock.HourNames[IsDay ? DerethClock.DuskHour : DerethClock.DawnHour]; +} + +internal static class DerethClock +{ + /// acclient's Timer::cur_time: a double, in seconds. Mapped only once in world. + public const uint ClockAddress = 0x008379A8; + + public const double TicksInHour = 476.25; + public const int HoursInDay = 16; + public const double TicksInDay = TicksInHour * HoursInDay; // 7620 + /// The clock counts seconds: one tick is one real second. + public const double SecondsPerTick = 1.0; + public const int DawnHour = 4, DuskHour = 12; + + // RynthAi's GetGameTicks: the raw clock to Dereth's calendar (UB's DerethTime). Only its + // -210 + 8 hours moves the time of day; the 10 years are whole days. + private const double CalendarOffset = -210 + TicksInHour * 8 + TicksInHour * HoursInDay * 30 * 12 * 10; + + public static readonly string[] HourNames = + { + "Darktide", "Darktide-and-Half", "Foredawn", "Foredawn-and-Half", + "Dawnsong", "Dawnsong-and-Half", "Morntide", "Morntide-and-Half", + "Midsong", "Midsong-and-Half", "Warmtide", "Warmtide-and-Half", + "Evensong", "Evensong-and-Half", "Gloaming", "Gloaming-and-Half", + }; + + /// A reading worth using: a number, past zero (0 before the clock is set). + public static bool IsUsable(double raw) => double.IsFinite(raw) && raw > 0; + + /// Dereth's calendar ticks for the raw clock (RynthAi's getgameticks). + public static double GameTicks(double raw) => raw + CalendarOffset; + + /// Ticks since Darktide began today, 0 to just under . + public static double TicksIntoDay(double raw) + { + double t = GameTicks(raw) % TicksInDay; + return t < 0 ? t + TicksInDay : t; + } + + /// Day or night, the hour, and the real seconds until the next dawn or dusk. + public static DerethNow At(double raw) + { + double into = TicksIntoDay(raw); + int hour = Math.Clamp((int)(into / TicksInHour), 0, HoursInDay - 1); + bool day = hour >= DawnHour && hour < DuskHour; + double dawn = DawnHour * TicksInHour, dusk = DuskHour * TicksInHour; + double ticks = day ? dusk - into + : into < dawn ? dawn - into + : TicksInDay - into + dawn; + return new DerethNow(day, hour, HourNames[hour], ticks * SecondsPerTick); + } + + /// + /// A countdown in real time: "1h 4m" and "23m" (whole minutes, rounded up) from 10 minutes, + /// "4m 10s" under 10 minutes, "45s" under one. Never "0s" before the change: rounded up. + /// + public static string Countdown(double seconds) + { + long s = (long)Math.Ceiling(Math.Max(0, seconds)); + if (s < 60) return s.ToString(CultureInfo.InvariantCulture) + "s"; + if (s < 600) return (s / 60).ToString(CultureInfo.InvariantCulture) + "m " + (s % 60).ToString(CultureInfo.InvariantCulture) + "s"; + long m = (s + 59) / 60; + if (m < 60) return m.ToString(CultureInfo.InvariantCulture) + "m"; + return (m / 60).ToString(CultureInfo.InvariantCulture) + "h " + (m % 60).ToString(CultureInfo.InvariantCulture) + "m"; + } + + /// The window's line: "Night in 23m", "Day in 4m 10s". + public static string Label(DerethNow now, double seconds) => now.Next + " in " + Countdown(seconds); +} diff --git a/Plugins/Shared/RynthAiRoutesApi.cs b/Plugins/Shared/RynthAiRoutesApi.cs new file mode 100644 index 0000000..d443aa0 --- /dev/null +++ b/Plugins/Shared/RynthAiRoutesApi.cs @@ -0,0 +1,221 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthAiRoutesApi.cs +// The "RynthAi.Routes" interface (2026-10-30): another plugin (an AI layer +// that drives characters, a route panel) has RynthAi make dungeon nav routes +// and gets JSON answers. The same work as the chat commands, one +// implementation (RynthAiPlugin.DunRoutes.cs, DungeonRouteMaker.cs): +// /ra dunroute to exit|far|portal | |room [overwrite] +// /ra dunpatrol-save [overwrite] +// /ra dunroute info /ra dunroute where +// Routes are written as VTank .nav files in RynthAi's NavProfiles folder, +// where RynthAi's Nav picker lists them and /ra nav load runs them. +// RynthAi does not load or start a route it saves. The points are the ones +// DungeonPathfinder lays for the patrol and dunnav (centred on doorways, +// straight across rooms). The .nav format (VTank's, unchanged) has no field +// for the doorway flag, so the doorway points are listed beside the routes +// in NavProfiles\.rynthai-routes.json (file, SHA-256, dungeon landblock, +// point count, doorway indexes; DunRouteSidecar.cs). When RynthAi loads an +// unchanged route-maker file in its dungeon it puts the flags back, so the +// route walks doorways as dunnav-patrol does; an edited file runs with the +// ordinary point reach. Other tools ignore the list. +// +// Rules: +// - Append-only: new functions go at the end, and Version goes up. A caller +// checks StructSize before using a field past the ones it knows. +// - Strings are UTF-8, NUL-terminated. The string handed back through a +// byte** belongs to RynthAi and stays valid only until the next call into +// this table: copy it at once. +// - Call only from the plugin pump thread (OnTick and the events it drains), +// never from Render. Resolve the table again every tick (a RynthAi reload +// frees it). Every function returns safely. +// - Threads: the work is not done off the game thread. DungeonPathfinder +// keeps static per-landblock caches (the cell graph, the map geometry) and +// DungeonGeometry a clearance memo, none of them thread-safe, and every +// caller of them (the dungeon patrol, nav recovery detours) runs on the +// plugin pump thread. So Request only checks the JSON and queues the job; +// RynthAi works one job per tick in its own OnTick, on that thread, file +// write included (a route file is a few KB). +// +// ── The two calls ────────────────────────────────────────────────────────── +// Request(json, &answer) -> job id +// Checks the request and queues it. Returns the job id (1 and up) with +// answer = {"id":7,"state":"queued"}; or 0, refused at once, with +// answer = {"error":""} (bad JSON, a wrong field, RynthAi not logged +// in, 32 jobs still unfinished). +// Poll(id, &json) -> 1 known job | 0 no such job +// json = {"id":7,"op":"dunroute","state":"queued","detail":"...","result":null} +// state queued waiting its turn (one job a RynthAi tick) +// working started, waiting on the client (portal space, the +// dungeon data loading); detail says what. It gives up +// after 30 s and fails. +// done result holds the answer (below) +// failed detail says why (the same line chat would show); +// result is null +// detail one line, the one the chat command answers with. +// An id RynthAi doesn't have (never given, dropped, or a RynthAi reload +// since): 0, with json = {"id":7,"state":"unknown","detail":"..."}. +// The last 32 jobs are kept: a new one drops the oldest finished one. Ids +// are never reused while RynthAi stays loaded. +// +// ── Requests (one JSON object; unknown fields and wrong types are refused) ─ +// {"op":"dunroute","name":"Hive exit","to":"exit"} +// {"op":"dunroute","name":"To depths","to":{"portal":"Portal to the Hive Depths"},"overwrite":true} +// {"op":"dunroute","name":"Spot","to":{"x":110.5,"y":-3.25,"z":-24}} +// {"op":"dunroute","name":"Far end","to":"far"} +// {"op":"dunroute","name":"Room 12","to":{"room":12}} +// {"op":"dunpatrol","name":"Hive patrol","overwrite":false} +// {"op":"info","name":"Hive patrol"} +// {"op":"where"} +// op "dunroute" | "dunpatrol" | "info" | "where" (required) +// name the route's name (dunroute, dunpatrol, info): a file name in +// NavProfiles without ".nav" (".nav" on the end is dropped); +// no folders, no \ / : * ? " < > |, no "..", not ending in a dot +// or a space, at most 120 characters, not a name Windows +// reserves (CON, NUL, COM1...) +// to dunroute only (required): +// "exit" the exit portal (picked as below) +// "far" the reachable spot farthest from the +// character on foot +// {"portal":"n"} a portal by name: the exact name (any case), +// else the names containing it; the nearest +// when several match +// {"x":..,"y":..,"z":..} a spot in dungeon coordinates: metres +// in the landblock's own frame, the numbers +// where's x/y/z and /ra navdebug's "local=" show +// {"room":n} a room by its number (where's "room", the +// rooms the dungeon map joins cells into; +// needs the map loaded) +// overwrite dunroute, dunpatrol: true replaces a file of that name; without +// it an existing file is never replaced (the job fails, saying so) +// +// "exit": a dungeon is left by a portal (or a recall). The client is not told +// where a portal goes, so the exit is the first that fits of: a portal whose +// appraised destination (string property 38) is a spot on the landscape +// ("12.3N, 45.6E"); a portal named like an exit (exit, surface, leave, +// outside, out, return); the portal nearest where the character came into +// this dungeon (within 40 m; RynthAi saw it arrive); the only portal known. +// Nothing fits: the job fails and lists the portals known (then ask for one +// by name). A one-way drop or a trap that teleports is the server's and +// can't be seen by the client. +// +// ── Results (state done) ─────────────────────────────────────────────────── +// Positions: "x","y","z" are landblock-local metres, as in the requests; +// "cell"/"id"/"landblock" are hex strings ("028902A5", "7028905D", "0289"). +// "yards" are RynthAi's yards (metres in the world). "leftOut" says what the +// route does not cover or keeps out of; "notes" what a reader should know +// (the map not loaded yet, portals the client hasn't been sent...). +// +// dunroute (a Once route: the character's spot first, the target last; a +// portal target ends with a Portal step that uses the portal): +// {"file":"C:\\Games\\RynthSuite\\RynthAi\\NavProfiles\\Hive exit.nav","name":"Hive exit", +// "type":"once","points":14,"waypoints":13,"yards":96.4,"landblock":"0289", +// "from":{"cell":"028902A5","x":110.0,"y":92.0,"z":-30.0}, +// "to":{"kind":"exit","portal":"Surface Portal","id":"7028905D","cell":"028902BA", +// "x":110.0,"y":-3.78,"z":-24.0,"why":"named like an exit"}, +// "cells":9,"doorways":4,"doorwayPoints":3,"overwrote":false, +// "leftOut":["3 lava/acid cells kept out of"], +// "notes":["2 portals known in this dungeon (the client only knows the ones it has been sent)"]} +// to.kind is "exit" | "portal" | "position" | "room" | "far"; to.portal, +// to.id are there for a portal (null otherwise), to.room for a room. +// points: every point in the file; waypoints: the ones walked to. +// cells: cells the path goes through; doorways: narrow openings it lines +// up on; doorwayPoints: the points flagged for them (recorded in +// .rynthai-routes.json; a problem writing that list is in "notes"). +// +// dunpatrol (the circular patrol /ra dunnav-patrol would walk from here, from +// the waypoint it would start at; one lap): +// {"file":"...\\Hive patrol.nav","name":"Hive patrol","type":"circular","points":355, +// "waypoints":355,"yards":2210.5,"landblock":"0289", +// "from":{"cell":"028902A5","x":110.0,"y":92.0,"z":-30.0},"startCell":"028902A5", +// "cells":524,"reachable":480,"covered":402,"doorwayPoints":120,"overwrote":false, +// "coverage":"coverage whole dungeon, skip dead ends <= 10, lava/acid floors avoided, walls 1.0 m, look into rooms >= 10 m", +// "leftOut":["44 of 524 cells can't be walked to from here (behind drops or lava/acid, or not joined)", +// "78 reachable cells left out by the coverage (whole dungeon, dead ends of up to 10 cells; Settings > Dungeon Patrol)", +// "beyond portal 'Surface Portal': 1 opening(s) closed (a portal fires at a touch)"], +// "notes":["..."]} +// cells: the dungeon's cells; reachable: those walkable from here; +// covered: those the patrol's coverage keeps (Settings > Navigation > +// Dungeon Patrol, as dunnav-patrol). startCell: the cell the lap is laid +// from. doorwayPoints: as for dunroute. The walk out of a hazard or a +// portal's reach that dunnav-patrol puts first (only needed from where +// the character stands) is not saved. +// The patrol is refused where a server's owners asked for it to be off +// (ServerPolicy), exactly as dunnav-patrol is. +// +// info (a saved route described; any .nav in NavProfiles): +// {"file":"...","name":"Hive patrol","type":"circular","points":355,"waypoints":355, +// "steps":{"portal":0,"recall":0,"pause":0,"chat":0,"jump":0,"npc":0,"vendor":0,"checkpoint":0}, +// "yards":2210.5,"landblock":"0289","landblocks":["0289"],"dungeon":true, +// "cells":201,"startCell":"028902A5","endCell":"028902A5", +// "forThisDungeon":"yes","pointsHere":355,"notes":[]} +// landblock: the dungeon its points are in: the character's when they +// are there, else the dungeon (of the landblocks round the ones its +// points fall in) whose cells hold at least half of them, else the +// landblock most points fall in (a landscape route); null with no points. +// landblocks: the 192 m squares its points' coordinates fall in, most +// first (a dungeon's cells can lie outside its own square: Tiny Hive +// 0x0289's are in 0x0288's). dungeon: that landblock is a dungeon (null: +// the dats aren't loaded); cells: distinct cells its points are in (null +// when not a dungeon); startCell/endCell: the first and last point's. +// forThisDungeon: "yes" (every point in the dungeon the character is in, +// as NavigationEngine's area hold judges it), "partly", "no", or +// "unknown" (the character isn't in a dungeon); pointsHere: how many are. +// +// where (where the character is; no file): +// {"inDungeon":true,"landblock":"0289","cell":"028902A5","x":110.0,"y":92.0,"z":-30.0, +// "ns":-0.1,"ew":-99.9,"cells":524,"reachable":480,"map":true,"rooms":120,"room":12, +// "explored":0.35,"hazards":3, +// "arrival":{"cell":"028902A5","x":110.2,"y":91.0,"z":-30.0}, +// "portals":[{"name":"Surface Portal","id":"7028905D","cell":"028902BA","x":110.0, +// "y":-3.78,"z":-24.0,"yards":96.1,"walkYards":101.0, +// "exit":"named like an exit","destination":null}]} +// map: the dungeon map geometry (doorways, floors) is loaded; rooms/room +// need it (null without). explored: the share of the floor the radar has +// painted as visited this visit (null when the radar hasn't drawn this +// dungeon). arrival: where RynthAi saw the character come in (null: +// RynthAi was loaded after). portals: every portal the client knows here, +// nearest first; walkYards along the cell path (null: no walkable way); +// exit: why it would be the exit (null: it wouldn't); destination: its +// appraised destination text, when the client has it. +// Outside a dungeon: {"inDungeon":false,"landblock":..,"cell":..,"x","y","z","ns","ew"}. +// +// ── A caller ─────────────────────────────────────────────────────────────── +// var t = (RynthAiRoutesApiV1*)host.GetPluginInterface("RynthAi", +// RynthAiRoutesApiV1.InterfaceName, RynthAiRoutesApiV1.InterfaceVersion); +// if (t == null || t->Version < 1 || t->StructSize < (uint)sizeof(RynthAiRoutesApiV1)) return; +// byte* answer; +// uint id = t->Request(jsonUtf8, &answer); // 0: refused, answer says why +// ... on later ticks: t->Poll(id, &json) until state is done or failed. +// ============================================================================ + +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.Shared; + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthAiRoutesApiV1 +{ + public const string InterfaceName = "RynthAi.Routes"; + public const uint InterfaceVersion = 1; + + /// Jobs kept: a new one drops the oldest finished one; with this many unfinished, Request refuses. + public const int MaxJobs = 32; + + /// The longest request accepted, in UTF-8 bytes. + public const int MaxRequestBytes = 8192; + + public uint Version; // InterfaceVersion of the table RynthAi filled + public uint StructSize; // sizeof(RynthAiRoutesApiV1) as RynthAi built it + + /// + /// Queues a request (UTF-8 JSON, see the header). Returns the job id (1 and up) with *answer = + /// {"id":N,"state":"queued"}, or 0 when refused at once with *answer = {"error":"..."}. + /// + public delegate* unmanaged[Cdecl] Request; + + /// + /// A job's state: 1 with *json = {"id","op","state","detail","result"}; 0 for an id RynthAi doesn't + /// have, with *json = {"id":N,"state":"unknown","detail":"..."}. + /// + public delegate* unmanaged[Cdecl] Poll; +} diff --git a/Plugins/Shared/RynthNavRoutesApi.cs b/Plugins/Shared/RynthNavRoutesApi.cs new file mode 100644 index 0000000..c42133e --- /dev/null +++ b/Plugins/Shared/RynthNavRoutesApi.cs @@ -0,0 +1,170 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthNavRoutesApi.cs +// The "RynthNav.Routes" interface (2026-10-30): RynthNav's route maker offered +// to other plugins through the host's GetPluginInterface (API v68). Plan trips, +// make RynthAi nav routes that follow real walkable paths (a trip, a hunting +// loop, a path through points), describe a saved one, search the Atlas, walk +// somewhere and stop, and ask where the player is. Everything is JSON: a +// caller sends a request, gets a job id at once, and polls the job until it +// is done or failed. The /rnav makeroute, makeloop, makepath and routeinfo +// commands are the same jobs (RynthNav's RynthNavPlugin.RouteMaker.cs). +// Compiled into RynthNav and into every plugin that calls it (linked source), +// so the layout can't drift. +// +// Rules (same as RynthAi.Script and RynthNav.Path): +// - Append-only: new functions go at the end, and Version goes up. A caller +// checks StructSize before using a field past the ones it knows. +// - Strings are UTF-8, NUL-terminated. A string handed back through a byte** +// belongs to RynthNav and stays valid only until the next call into this +// table: copy it at once. +// - Call only from the plugin pump thread (OnTick and the events it drains). +// Resolve the table again every tick: never keep the pointer across ticks +// (RynthNav can be reloaded or unloaded between them; a reload forgets the +// jobs, and Poll then answers "unknown"). +// - Every function returns safely (no exception crosses the boundary). +// - The work itself runs on a RynthNav worker, never on the caller's thread; +// Request returns at once. Poll once a tick or slower. +// +// ── Calls ─────────────────────────────────────────────────────────────────── +// Request(json, &reply) -> job id > 0, reply = the job as Poll shows it +// ({"id":..,"op":..,"state":"queued","detail":"queued","result":null}); +// -> 0, reply = {"error": why, "usage": the op's JSON form} for a refused request +// (not JSON, over 16384 characters, an unknown op, a missing or wrong field, +// out of range, a bad name, or 32 jobs already queued or working). +// Poll(id, &json) -> 1, json = {"id":n,"op":"makeloop","state":"queued|working|done|failed", +// "detail":"one line saying where it is or why it failed", +// "result": the op's result below (null until there is one; +// {"error": why, ...} for most failed jobs)} +// -> 0, json = {"id":n,"state":"unknown","error":...}: not a job RynthNav keeps +// (only the last 32 are kept; a reload forgets them). +// Job ids are positive and go up; they start from the clock, so a reload doesn't reuse old ones. +// Jobs that work out walks (plan, makeroute, makeloop, makepath, info) run one at a time, in the +// order asked; atlas, where, stop and go run on RynthNav's next tick. +// +// ── Requests ──────────────────────────────────────────────────────────────── +// Every request is a JSON object with "op". Unknown fields are ignored; a known field of the wrong +// type is refused. Coordinates are map coordinates: {"ns": 42.1, "ew": 33.6}, north and east +// positive, at most 102 either way. A place is a name from RynthNav's Atlas ("Holtburg") or +// coordinates as text ("42.1N, 33.6E"), exactly what /rnav go takes. A route "name" is a nav file +// name: no path, no characters a file name can't hold, at most 100 characters, ".nav" optional; it +// goes in RynthAi's NavProfiles folder, and a file already there is only replaced with +// "overwrite": true. +// +// plan {"op":"plan", "to":"Holtburg" | {"ns":42.1,"ew":33.6}, "portals":true|false, "show":false} +// Plans a trip from where the player stands, as /rnav route (portals and recalls when +// "portals" is true; left out = the player's "portals" switch), and works out its walks. +// "show": true also shows it in RynthNav's panel and on the ground. +// result {"to":{"name","ns","ew"}, "portals":true, +// "steps":[{"kind":"walk|portal|recall|town","name":"...","ns":..,"ew":..,"yards":412, +// "land":{"ns","ew"} (portal, recall, town: where it lands)}, ...], +// "yards":3312, "teleports":2, "minutes":6.4, "notes":["step 2: ..."]} +// kind town = through the Town Network to its exit "name". minutes is rough: running at +// 10 yd/s, 36 s for each teleport, and each recall's cast time. +// +// makeroute {"op":"makeroute", "name":"To Holtburg", "to":"Holtburg" | {"ns","ew"}, "portals":true|false, +// "overwrite":false, "show":false} +// plan, then save it as a RynthAi nav route (type once), as /rnav route then /rnav saveroute. +// result {"name","file":"C:\\...\\NavProfiles\\To Holtburg.nav","type":"once","points":47, +// "yards":3290,"dropped":0,"droppedPoints":[],"to":{"name","ns","ew"},"waypoints":44, +// "portals":1,"recalls":1,"teleports":2,"stoppedShort":null | "step 3: why", +// "notes":[...]} +// +// makeloop {"op":"makeloop", "name":"Holtburg loop", "at":"here" | {"ns","ew"} | "42.1N, 33.6E", +// "radius":80, "points":8, "overwrite":false} +// A hunting loop, saved as a circular nav route: "points" walkable spots round the centre +// ("at"; left out = here) within "radius" yards (20 to 250; points 3 to 16, left out = +// about one per 45 yd of the circle), out of buildings, 20 yd or more from any portal, off +// walls, each reachable from the centre; walked in order round the centre with no two legs +// crossing, each leg a real path that never enters a portal's circle, pushed off walls by +// RynthNav's wall clearance, round buildings where it can. Spots that can't be used are +// dropped and listed. +// result {"name","file","type":"circular","points":38,"yards":612,"dropped":1, +// "droppedPoints":[{"ns","ew","why":"not reachable from the centre"}], +// "centre":{"ns","ew"},"radius":80,"loopPoints":7,"asked":8,"notes":[...]} +// points = the nav file's points (waypoints along the legs); loopPoints = the chosen spots. +// +// makepath {"op":"makepath", "name":"Ridge walk", "type":"loop|line|once", +// "points":[{"ns":42.1,"ew":33.6}, "42.3N, 33.9E", ...], "overwrite":false} +// A nav route through the points in that order (2 to 32; type loop = circular, line = +// linear, once; left out = once), each leg a real path (RynthNav's portal and wall avoid +// settings), a loop also back from the last to the first. Fails, naming the leg, when one +// can't be walked; fails naming the point when one has no ground within 12 yd or stands in +// a portal's circle. +// result {"name","file","type":"once","points":31,"yards":450,"dropped":0,"droppedPoints":[], +// "given":3,"legs":2,"notes":[]} +// +// info {"op":"info", "name":"Holtburg loop"} +// What a nav file in NavProfiles is (/rnav routeinfo). +// result {"name","file","type":"circular|linear|once|follow","points":38, +// "counts":{"waypoints","portals","recalls","chats","pauses","other"}, +// "yards":612 (walking; a circular route's lap; not across teleports), +// "box":{"minNs","maxNs","minEw","maxEw"},"centre":{"ns","ew"}, +// "start":{"ns","ew","yards" (from the player, null when not on the map)}, +// "nearest":{"index","ns","ew","yards"} | null (the waypoint nearest the player), +// "landblocks":["A9B4",...],"dungeon":false,"dungeonLandblocks":[], +// "portals":["Portal to ..."],"recalls":["Lifestone Recall"],"chats":["@lifestone"], +// "warning": RynthAi's reader's warning, when it gave one} +// +// atlas {"op":"atlas", "search":"holt", "max":10} +// result {"search","count":3,"places":[{"name":"Holtburg","kind":"Town","onMap":true, +// "ns":42.1,"ew":33.6,"yards":1234 (from the player; null when not on the map)}, +// {"name","kind":"Dungeon","onMap":false,"ns":null,"ew":null,"yards":null,"where":"..."}]} +// max 1 to 50 (left out = 10). +// +// go {"op":"go", "to":"Holtburg" | {"ns","ew"}} +// Walks there as /rnav go does (a dungeon walks into its entrance portal). The job stays +// "working" while it walks (detail: "walking to Holtburg, 1.2k yd left") and ends: +// done with outcome "arrived" (or "stopped" when stopped by stop, /rnav stop, the panel, +// or another goto taking over), failed with the reason (no progress, a portal on the way, +// no route, logged out...). +// result {"started":true,"to":{"name","ns","ew"},"enter":""|null,"steps":3, +// "teleports":2,"outcome":"walking|arrived|stopped|failed","reason":"..."} +// A walk that couldn't start: failed, {"started":false,"outcome":"failed","reason":...}. +// +// stop {"op":"stop"} stops a walk (any, as /rnav stop). result {"wasWalking":true} +// +// where {"op":"where"} +// result {"onMap":true,"ns":42.1,"ew":33.6 (null in a dungeon),"landblock":"A9B4", +// "cell":"A9B40031","indoors":false,"dungeon":false,"walking":false, +// "nearest":{"name","kind","ns","ew","yards"} | null (the nearest Atlas place)} +// +// Ops that need the player (plan, makeroute, go, where, makeloop "here") fail with "no player +// position yet" before login; makeloop "at", makepath, info and atlas don't need one. +// +// ── Example ───────────────────────────────────────────────────────────────── +// var t = (RynthNavRoutesApiV1*)Host.GetPluginInterface("RynthNav", "RynthNav.Routes", 1); +// byte* reply; +// int id = t->Request(utf8("{\"op\":\"makeloop\",\"name\":\"Hunt 1\",\"radius\":80}"), &reply); +// ... a later tick (resolve t again) ... +// byte* json; t->Poll(id, &json); // {"id":..,"op":"makeloop","state":"done","detail":"saved Hunt 1.nav: 8 points, 612 yd a lap","result":{...}} +// ============================================================================ + +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.Shared; + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthNavRoutesApiV1 +{ + public const string PluginName = "RynthNav"; + public const string InterfaceName = "RynthNav.Routes"; + public const uint InterfaceVersion = 1; + + /// How many jobs RynthNav keeps (finished ones are dropped oldest first). + public const int MaxJobs = 32; + + public uint Version; // InterfaceVersion of the table RynthNav filled + public uint StructSize; // sizeof(RynthNavRoutesApiV1) as RynthNav built it + + /// + /// Queues a request (UTF-8 JSON, see the header). Returns its job id (> 0) with *reply = the job's + /// JSON, or 0 with *reply = {"error", "usage"} when the request is refused. + /// + public delegate* unmanaged[Cdecl] Request; + + /// + /// A job's state: 1 with *json = {id, op, state, detail, result}; 0 with *json = {id, state: "unknown", + /// error} for an id RynthNav doesn't keep. + /// + public delegate* unmanaged[Cdecl] Poll; +} diff --git a/Plugins/Shared/RynthServerProfileApi.cs b/Plugins/Shared/RynthServerProfileApi.cs index 61e5dd0..465bb3e 100644 --- a/Plugins/Shared/RynthServerProfileApi.cs +++ b/Plugins/Shared/RynthServerProfileApi.cs @@ -51,8 +51,11 @@ // // (RynthAelrynth; RynthAi keeps learned HP and kills per tier) // "vendorBank": 1, // the server's bank pays a pyreal vendor what the packs are short // // of (absent or 0 = it doesn't: readers count the packs only), -// "vendorBankPyreals": 5000 // and what the bank can add beyond the pyreals the game shows -// } // (absent = not known: the server decides). RynthDefective's buys. +// "vendorBankPyreals": 5000, // and what the bank can add beyond the pyreals the game shows +// // (absent = not known: the server decides). RynthDefective's buys. +// "bankLuminance": 8904758 // the luminance in the server's bank, deposits taken out, for a +// } // server that banks earned luminance where the client can't see +// // it (RynthDreamWeave's /b); rises are luminance earned (Lum/hr). // } // ============================================================================ @@ -103,6 +106,16 @@ public static class RynthServerProfile /// leave the money to the server. /// public const string ValueVendorBankPyreals = "vendorBankPyreals"; + + /// + /// The luminance in this character's bank on the server, as last read, less what the server + /// plugin saw deposited from the character since login (whole luminance, 0 or more), for a + /// server that banks earned luminance where the client can't read it (no bank property). A rise + /// is luminance earned; a drop is spending. Absent: not known (not read yet, or the server has + /// no such bank). The session stats (SessionStatsTracker) count its rises when the client has + /// no bank property of its own. (2026-11-02, RynthDreamWeave's every-minute /b.) + /// + public const string ValueBankLuminance = "bankLuminance"; } [StructLayout(LayoutKind.Sequential)] diff --git a/Plugins/Shared/RynthUi/RynthIcons.cs b/Plugins/Shared/RynthUi/RynthIcons.cs index fdf6ead..3eb43b2 100644 --- a/Plugins/Shared/RynthUi/RynthIcons.cs +++ b/Plugins/Shared/RynthUi/RynthIcons.cs @@ -87,6 +87,7 @@ internal static class RynthIcons public const string MapTrifold = "\uE31A"; public const string Minus = "\uE32A"; public const string Monitor = "\uE32E"; + public const string Moon = "\uE330"; public const string NavigationArrow = "\uEADE"; public const string Package = "\uE390"; public const string Path = "\uE39C"; diff --git a/Plugins/Shared/SessionStats.cs b/Plugins/Shared/SessionStats.cs index 668f8a9..afda239 100644 --- a/Plugins/Shared/SessionStats.cs +++ b/Plugins/Shared/SessionStats.cs @@ -19,6 +19,11 @@ // rises are ignored. "Deposited N luminance" and "Received N // luminance from X" move lum into the bank without earning it: // they are taken out of the next bank rises. +// Server bank a server that banks earned luminance out of the client's +// sight: its server plugin reads the bank (a chat command once +// a minute) and publishes it in its profile ("bankLuminance"); +// SessionStatsTracker passes that in as BankLum when 9005 isn't +// readable, so it counts exactly as ACECustom's bank (2026-11-02). // Pass-up ACECustom never sends the allegiance counters (9013/9014). // A vassal's pass-up lands in the bank silently, while your own // kill and quest lum prints "You've banked N Luminance.", so diff --git a/Plugins/Shared/SessionStatsTracker.cs b/Plugins/Shared/SessionStatsTracker.cs index ca4aa7d..8e253a2 100644 --- a/Plugins/Shared/SessionStatsTracker.cs +++ b/Plugins/Shared/SessionStatsTracker.cs @@ -9,6 +9,17 @@ // Threading: every call except RequestReset and View runs on the pump // thread. RequestReset only sets a flag (any thread); View is an immutable // record swapped in after each poll (any thread). +// +// The bank's luminance where the client has no bank property (2026-11-02): +// a server that keeps earned luminance in its bank out of the client's sight +// has its server plugin read the bank and publish it in its profile +// ("RynthServer.Profile" values, RynthServerProfile.ValueBankLuminance; +// RynthDreamWeave's every-minute /b). Read every few seconds from the active +// server's owner (ServerStateClient) and only while ACECustom's 9005 isn't +// readable, it goes in as that bank's reading: the same baseline (the +// session file's "bank"), so rises are earned luminance and drops aren't. +// Needs, linked into the plugin: ServerStateClient.cs, EngineServerState.cs, +// RynthServerProfileApi.cs. // ============================================================================ using System; using System.Collections.Generic; @@ -40,6 +51,9 @@ internal sealed class SessionStatsTracker private readonly string _saveDirectory; private readonly SessionStats _stats = new(); private readonly List<(uint Id, DateTime Seen)> _pendingCorpses = new(); + private readonly ServerStateClient _server = new(); + private long? _profileBankLum; // the active server profile's bank luminance (null = none) + private long _nextProfileMs; private uint _playerId; private bool _loggedIn; // between OnLoginComplete and OnLogout @@ -66,6 +80,12 @@ internal sealed class SessionStatsTracker /// True while a session is running (pump thread). public bool Active => _active; + /// + /// How often the active server profile's bank luminance is re-read (a server plugin reads its bank + /// once a minute at most). Tests set it lower. + /// + internal long ProfileIntervalMs { get; init; } = 5000; + /// Starts a fresh session on the next tick (any thread). public void RequestReset() => _pendingReset = true; @@ -91,6 +111,9 @@ internal sealed class SessionStatsTracker _loggedIn = false; _active = false; _pendingCorpses.Clear(); + _server.Clear(); + _profileBankLum = null; + _nextProfileMs = 0; _view = SessionStatsView.Empty; _host.Log($"{_tag} Session ended."); } @@ -186,7 +209,7 @@ internal sealed class SessionStatsTracker long nowMs = Environment.TickCount64; if (nowMs < _nextPollMs) return; _nextPollMs = nowMs + PollIntervalMs; - Poll(now); + Poll(now, nowMs); _view = _stats.View(now); // Saved right after a poll, so totals and baselines in the file always match. @@ -197,13 +220,13 @@ internal sealed class SessionStatsTracker } } - private void Poll(DateTime now) + private void Poll(DateTime now, long nowMs) { if (_playerId == 0 || !_host.HasGetObjectQuadProperty) return; _stats.Sample(new SessionSample( Read(Int64TotalExperience), Read(Int64AvailableLuminance), - Read(Int64BankedLuminance), + Read(Int64BankedLuminance) ?? ProfileBankLum(nowMs), Read(Int64LuminanceBanked), Read(Int64LuminanceDrawn), Read(Int64RadianceEarned)), now); @@ -212,6 +235,24 @@ internal sealed class SessionStatsTracker private long? Read(uint stype) => _host.TryGetObjectQuadProperty(_playerId, stype, out long value) ? value : null; + /// + /// The active server profile's bank luminance (RynthServerProfile.ValueBankLuminance), re-read every + /// few seconds and held in between; null while the profile has none (or the engine is older than v86). + /// + private long? ProfileBankLum(long nowMs) + { + if (nowMs < _nextProfileMs) return _profileBankLum; + _nextProfileMs = nowMs + ProfileIntervalMs; + try + { + _server.Poll(_host, nowMs, force: true); // throttled here, not by the client's own 2 s + double v = ServerProfileView.Value(_server.ProfileJson, RynthServerProfile.ValueBankLuminance, double.NaN); + _profileBankLum = v >= 0 && v < long.MaxValue ? (long)v : null; + } + catch { _profileBankLum = null; } + return _profileBankLum; + } + /// /// The player's health from the engine's vitals (the same reading RynthAi's death hold uses), /// then the server's death counter, in the order the server sends them (SessionStats counts diff --git a/README.md b/README.md index 64f6849..daca58d 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,12 @@ A combat and navigation assistant for Asheron's Call, ported from the legacy Nex | `/na raycast` | Show raycast system status | | `/na lostest` | Run line-of-sight test against current target | +### RynthNav + +Walks the character on a navmesh of the landscape, plans trips with portals and recalls, keeps an Atlas of +places, and makes RynthAi nav routes on real walkable paths (`/rnav makeroute`, `makeloop`, `makepath`, +`routeinfo`, and the "RynthNav.Routes" interface for other plugins). See [Docs/RYNTHNAV.md](Docs/RYNTHNAV.md). + --- ## Monster rules diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 41b927d..ea46532 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -58,6 +58,14 @@ internal static unsafe class FakeHost /// engine's EquipmentTracker: item -> EquipMask). answers -1. public static bool EquippedCalls; public static bool EquippedNotReady; + /// Opt-in (set before Create): v93 GetMonsterHealth answering (the + /// engine monster plates' last server reading: id -> ratio, age in ms). + /// non-zero sets the table's Version (e.g. 92: the slot is there but the engine is too old). + /// Calls are counted in . + public static bool PlateHealthCalls; + public static uint PlateHealthVersion; + public static readonly Dictionary PlateHealth = new(); + public static int PlateHealthQueries; public static readonly Dictionary Equipped = new(); /// Item id -> the creature wielding it (GetObjectOwnershipInfo's wielder). Entries here /// also install GetObjectOwnershipInfo; an id in neither map reads as unknown ownership. @@ -130,6 +138,9 @@ internal static unsafe class FakeHost 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 (set before Create): wires NativeAttack and SelectItem; a native attack lands in + /// as ("native", the selected item, height, power). + public static bool NativeAttackCalls; /// Opt-in (set before Create): wires CancelAttack; calls are counted in . public static bool CancelAttackCalls; public static int CancelAttacks; @@ -260,6 +271,8 @@ internal static unsafe class FakeHost public static bool PluginCommandDelivered = true; /// Every SendPluginCommand (plugin, action, value), in order. public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new(); + /// For each entry, how many chat lines were written before it (call order). + public static readonly List PluginCommandChatCounts = new(); /// Opt-in (set before Create): ForceResetBusyCount (counted in ) /// and GetBusyState (answering ). public static bool BusyCalls; @@ -297,6 +310,7 @@ internal static unsafe class FakeHost public static void Reset() { EquippedCalls = false; EquippedNotReady = false; Equipped.Clear(); + PlateHealthCalls = false; PlateHealthVersion = 0; PlateHealth.Clear(); PlateHealthQueries = 0; #if !RYNTHILT_TESTS RynthCore.Plugin.RynthAi.EquippedState.Invalidate(); #endif @@ -310,7 +324,7 @@ internal static unsafe class FakeHost Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatTypes.Clear(); ChatCommands.Clear(); AfterCastSpell = null; - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); CancelAttackCalls = false; CancelAttacks = 0; Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); NativeAttackCalls = false; CancelAttackCalls = false; CancelAttacks = 0; 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; UseObjectAccepts = true; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; @@ -328,7 +342,7 @@ internal static unsafe class FakeHost CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0; SelectedItem = 0; UseOnCalls = false; UsesOn.Clear(); - PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); + PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); PluginCommandChatCounts.Clear(); TradeVendorCalls = false; TradeActions.Clear(); VendorSells.Clear(); VendorBuys.Clear(); CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0; BusyCalls = false; ForceResets = 0; BusyStateValue = 0; @@ -396,9 +410,14 @@ internal static unsafe class FakeHost api.MeleeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl])&MeleeAttack; api.MissileAttackFn = (IntPtr)(delegate* unmanaged[Cdecl])&MissileAttack; } + if (NativeAttackCalls) + { + api.NativeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl])&NativeAttack; + api.SelectItemFn = (IntPtr)(delegate* unmanaged[Cdecl])&SelectItem; + } if (Nav3DCalls) { - api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DClear; + api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DClear; api.Nav3DAddRingFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddRing; api.Nav3DAddLineFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddLine; api.Nav3DAddTriangleFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddTriangle; @@ -541,6 +560,11 @@ internal static unsafe class FakeHost ConfigureApi?.Invoke(ref api); LastApi = api; if (EquippedCalls) api.Version = Math.Max(api.Version, 87u); // v87 GetWieldedItems + if (PlateHealthCalls) + { + api.GetMonsterHealthFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetMonsterHealth; + api.Version = PlateHealthVersion != 0 ? PlateHealthVersion : Math.Max(api.Version, 93u); // v93 + } return new RynthCoreHost(api); } @@ -623,6 +647,7 @@ internal static unsafe class FakeHost private static int SendPluginCommand(IntPtr plugin, IntPtr action, IntPtr value) { PluginCommands.Add((Marshal.PtrToStringAnsi(plugin) ?? "", Marshal.PtrToStringAnsi(action) ?? "", Marshal.PtrToStringAnsi(value) ?? "")); + PluginCommandChatCounts.Add(Chat.Count); return PluginCommandDelivered ? 1 : 0; } @@ -660,6 +685,16 @@ internal static unsafe class FakeHost return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetMonsterHealth(uint id, float* ratio, uint* ageMs) + { + PlateHealthQueries++; + bool ok = PlateHealth.TryGetValue(id, out var h); + if (ratio != null) *ratio = ok ? h.Ratio : -1f; + if (ageMs != null) *ageMs = ok ? h.AgeMs : uint.MaxValue; + return ok ? 1 : 0; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetWieldedItems(uint* ids, uint* locations, int max) { @@ -882,6 +917,10 @@ internal static unsafe class FakeHost [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 NativeAttack(int height, float power) { AttackCalls.Add(("native", SelectedItem, height, power)); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SelectItem(uint id) { SelectedItem = id; 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; } diff --git a/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-clamp.usd b/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-clamp.usd new file mode 100644 index 0000000..f9f76dc --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-clamp.usd @@ -0,0 +1,137 @@ +MyMonsters +21 +MonsterName +AttackPriority +DamageType +WeaponToUse +Imperil +Vuln +Yield +GravityW +Attack +Ring +Broadside +Fester +WeakeningCurse +FesteringCurse +Corruption +DestructiveCurse +Corrosion +Streak +SecondaryVuln +SecondaryEquip +PetDamageType +y +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +2 +s + +i +1 +i +1 +i +-1 +b +False +b +False +b +False +b +False +b +False +b +True +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +i +0 +i +-1 +i +101 +s +Drudge Skulker +i +1 +i +1 +i +-1 +b +False +b +False +b +False +b +False +b +True +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +i +0 +i +-1 +i +101 +s +MinimumRingTargets +i +30 +s +RingDistance +d +0.3 diff --git a/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-mintargets-only.usd b/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-mintargets-only.usd new file mode 100644 index 0000000..3acefdf --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-mintargets-only.usd @@ -0,0 +1,133 @@ +MyMonsters +21 +MonsterName +AttackPriority +DamageType +WeaponToUse +Imperil +Vuln +Yield +GravityW +Attack +Ring +Broadside +Fester +WeakeningCurse +FesteringCurse +Corruption +DestructiveCurse +Corrosion +Streak +SecondaryVuln +SecondaryEquip +PetDamageType +y +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +2 +s + +i +1 +i +1 +i +-1 +b +False +b +False +b +False +b +False +b +False +b +True +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +i +0 +i +-1 +i +101 +s +Drudge Skulker +i +1 +i +1 +i +-1 +b +False +b +False +b +False +b +False +b +True +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +i +0 +i +-1 +i +101 +s +MinimumRingTargets +i +0 diff --git a/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-none.usd b/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-none.usd new file mode 100644 index 0000000..8037b1c --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-none.usd @@ -0,0 +1,141 @@ +MyMonsters +21 +MonsterName +AttackPriority +DamageType +WeaponToUse +Imperil +Vuln +Yield +GravityW +Attack +Ring +Broadside +Fester +WeakeningCurse +FesteringCurse +Corruption +DestructiveCurse +Corrosion +Streak +SecondaryVuln +SecondaryEquip +PetDamageType +y +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +2 +s + +i +1 +i +1 +i +-1 +b +False +b +False +b +False +b +False +b +False +b +True +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +i +0 +i +-1 +i +101 +s +Drudge Skulker +i +1 +i +1 +i +-1 +b +False +b +False +b +False +b +False +b +True +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +i +0 +i +-1 +i +101 +s +EnableLooting +b +False +s +AttackDistance +d +0.3 +s +summonpets +b +False diff --git a/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings.usd b/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings.usd new file mode 100644 index 0000000..c9dc80c --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings.usd @@ -0,0 +1,149 @@ +MyMonsters +21 +MonsterName +AttackPriority +DamageType +WeaponToUse +Imperil +Vuln +Yield +GravityW +Attack +Ring +Broadside +Fester +WeakeningCurse +FesteringCurse +Corruption +DestructiveCurse +Corrosion +Streak +SecondaryVuln +SecondaryEquip +PetDamageType +y +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +n +2 +s + +i +1 +i +1 +i +-1 +b +False +b +False +b +False +b +False +b +False +b +True +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +i +0 +i +-1 +i +101 +s +Drudge Skulker +i +1 +i +1 +i +-1 +b +False +b +False +b +False +b +False +b +True +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +b +False +i +0 +i +-1 +i +101 +s +EnableLooting +b +False +s +AttackDistance +d +0.3 +s +MinimumRingTargets +i +2 +s +RingDistance +d +0.0166666666666667 +s +summonpets +b +False diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 589dd0f..21f7648 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -20,6 +20,9 @@ internal static class Program /// DungeonHazardStore's folder before Main pointed it at the scratch folder. public static string LiveHazardFolder { get; private set; } = ""; + /// DungeonRouteMaker's folder (NavProfiles) before Main pointed it at the scratch folder. + public static string LiveRouteFolder { get; private set; } = ""; + /// CreatureProfileStore's folder before Main pointed it at the scratch folder. public static string LiveCreatureFolder { get; private set; } = ""; @@ -46,6 +49,9 @@ internal static class Program LiveHazardTextureFolder = RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Folder; RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Folder = Path.Combine(TempRoot, "HazardTextures"); RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Reload(); + // Dungeon routes (/ra dunroute, /ra dunpatrol-save, RynthAi.Routes) are saved to C:\Games\RynthSuite\RynthAi\NavProfiles. + LiveRouteFolder = RynthCore.Plugin.RynthAi.DungeonRouteMaker.Folder; + RynthCore.Plugin.RynthAi.DungeonRouteMaker.Folder = Path.Combine(TempRoot, "NavProfiles"); // Appraised creatures are saved to C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json. LiveCreatureFolder = RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder; RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder = Path.Combine(TempRoot, "CreatureData"); @@ -63,6 +69,7 @@ internal static class Program LootWandTests.Register(runner); LootRaresModeTests.Register(runner); LootChatLineTests.Register(runner); + ItemInfoTextColorTests.Register(runner); LootSurveyTests.Register(runner); PropertyDumpTests.Register(runner); T11LootTests.Register(runner); @@ -79,12 +86,14 @@ internal static class Program PatrolSettingsTests.Register(runner); PatrolPocketTests.Register(runner); PatrolPortalTests.Register(runner); + DunRouteTests.Register(runner); BuffTests.Register(runner); SpellCatalogTests.Register(runner); CombatMathTests.Register(runner); WeaponTests.Register(runner); RadarSnapshotTests.Register(runner); AmmoTests.Register(runner); + MissileAmmoSwapTests.Register(runner); VTankYieldTests.Register(runner); OffhandTests.Register(runner); HandSwapTests.Register(runner); @@ -96,10 +105,13 @@ internal static class Program LootRetryTimingTests.Register(runner); LootClaimMismatchTests.Register(runner); BoostNavTests.Register(runner); + NavHeadingTests.Register(runner); LootNothingLineTests.Register(runner); ChestLootTests.Register(runner); ItemToolTests.Register(runner); VanishedItemTests.Register(runner); + KitUsedUpTests.Register(runner); + VitalWandGateTests.Register(runner); OwnCorpseTests.Register(runner); UseRefusalTests.Register(runner); CorpseKillerTests.Register(runner); @@ -107,9 +119,13 @@ internal static class Program MultiTargetTests.Register(runner); CastSafetyTests.Register(runner); HealLatencyTests.Register(runner); + HealGraceTests.Register(runner); + HealHoldTests.Register(runner); BlastTests.Register(runner); ArcWhenClearTests.Register(runner); WallTests.Register(runner); + RingTests.Register(runner); + VtRingImportTests.Register(runner); CombatHookTests.Register(runner); UseAtLoginTests.Register(runner); LearnSpellsTests.Register(runner); @@ -125,13 +141,18 @@ internal static class Program MonsterEditorTests.Register(runner); InstallPathsTests.Register(runner); PetRefillTests.Register(runner); + PetSummonStopsTests.Register(runner); AutoStackTests.Register(runner); AutoVendorSplitTests.Register(runner); AutoVendorZeroRateTests.Register(runner); + AutoVendorZeroPayTests.Register(runner); + AutoVendorFoldersTests.Register(runner); BackAwayTests.Register(runner); ServerPluginForwardTests.Register(runner); IgnoreMonsterTests.Register(runner); WorldCacheTypedTests.Register(runner); + VendorFlagTests.Register(runner); + LootByNameTests.Register(runner); NavOverlayTests.Register(runner); ActionPacingTests.Register(runner); HazardEscapeTests.Register(runner); @@ -145,12 +166,15 @@ internal static class Program CastNoDamageTests.Register(runner); ManaReserveTests.Register(runner); DamageRowsTests.Register(runner); + ShieldFacingTests.Register(runner); NavMapEditTests.Register(runner); LootSpeedTests.Register(runner); MeleeStallTests.Register(runner); + NativeAttackTests.Register(runner); ServerMenuTests.Register(runner); MiniRemoteMoveTests.Register(runner); SessionDeathTests.Register(runner); + SessionBankProfileTests.Register(runner); SectionsTests.Register(runner); ItemsCleanTests.Register(runner); DeathRecallTests.Register(runner); @@ -188,9 +212,13 @@ internal static class Program DifficultyTierTests.Register(runner); TickIsolationTests.Register(runner); ChoresInFightTests.Register(runner); + AetheriaUnboxTests.Register(runner); CommandReplyTests.Register(runner); MonsterStatsTests.Register(runner); MetaSaveTests.Register(runner); + MetaResumeTests.Register(runner); + FellowOpenTests.Register(runner); + WieldBanTests.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 e9318c6..03abe8a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs @@ -43,8 +43,31 @@ internal static class ActionPacingTests private static readonly (uint Cell, float X, float Y, float Z) Me0 = (0xA9B40019u, 100f, 100f, 0f); private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; + // The macro switched off while the player runs by hand: RynthAi leaves the character running + // (the owner, 2026-11-07). It stops only movement of its own: autorun or a motion it turned on, + // or the server's walk to a target or a corpse for it (Combat, Looting). + private static void MacroStopLeavesPlayersRun() + { + Check.False(RynthAiPlugin.MacroStopHalts(false, "Default"), "idle, nothing of ours moving: no stop"); + Check.False(RynthAiPlugin.MacroStopHalts(false, "Buffing"), "buffing, nothing of ours moving: no stop"); + Check.False(RynthAiPlugin.MacroStopHalts(false, null), "no action yet: no stop"); + Check.True(RynthAiPlugin.MacroStopHalts(true, "Navigating"), "nav's autorun: stopped"); + Check.True(RynthAiPlugin.MacroStopHalts(false, "Combat"), "fighting (the server may be walking us to the target): stopped"); + Check.True(RynthAiPlugin.MacroStopHalts(false, "Looting"), "looting (the walk to the corpse): stopped"); + + FakeHost.Reset(); + MoveAudit.Reset(); + var host = FakeHost.Create(); + Check.False(MoveAudit.OwnMovementActive, "nothing sent: nothing of ours moving"); + host.SetAutoRunBy("Nav", true); + Check.True(MoveAudit.OwnMovementActive, "our autorun: ours is moving"); + host.SetAutoRunBy("Nav", false); + Check.False(MoveAudit.OwnMovementActive, "stopped again: not ours"); + } + public static void Register(Runner r) { + r.Add("macro off: the player's own running is left alone; RynthAi's movement is stopped", MacroStopLeavesPlayersRun); r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers); r.Add("pacing: the player's turn (RynthAi.Yield) holds every start, mode change and move, ends by itself, and lets what is out finish", PlayersTurn); r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AetheriaUnboxTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AetheriaUnboxTests.cs new file mode 100644 index 0000000..145f2c9 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AetheriaUnboxTests.cs @@ -0,0 +1,290 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Unbox Aetheria When Idle (a player's request, 2026-11-01: "auto aetheria unbox when idle option"). +// ACE (Entity/Aetheria.cs): an Aetheria Mana Stone used on a Coalesced Aetheria reveals its sigil +// ("A sigil rises ...", the name becomes "Aetheria", UseDone); the stone is not used up; busy is +// UseDone YoureTooBusy. RynthAi does it one piece at a time, only when idle, and backs off a refusal. +internal static class AetheriaUnboxTests +{ + private const uint Player = TickIsolationTests.Player; + private const uint Blue = 0x80000A51, Red = 0x80000A52, Stone = 0x80000A53, Revealed = 0x80000A54, Monster = 0x80000A55; + private const uint ItemTypeMisc = 0x80; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("aetheria: idle with the option on, a mana stone goes on one coalesced aetheria, and the next only after its sigil rose", UnboxesOneAtATime); + r.Add("aetheria: nothing while a monster is on us; it unboxes once the fight is over, and a fight mid-unbox takes the tick back", NotInAFight); + r.Add("aetheria: nothing with the option off or the macro off", NothingWhenOff); + r.Add("aetheria: a 'too busy' refusal waits 10 s, then longer; no answer at all is a failed try", RefusalBacksOff); + r.Add("aetheria: coalesced aetheria and no mana stone: said once in chat, not again", NoStoneSaidOnce); + r.Add("aetheria: an already revealed 'Aetheria' is left alone", RevealedLeftAlone); + r.Add("aetheria: /ra aetheria unbox does every piece with the option and the macro off, then says how many", ManualRun); + r.Add("aetheria: settings - off by default, saved, copied, sent to the engine face, metas reach UnboxAetheriaWhenIdle", Settings); + } + + private static void Item(uint id, string name, uint wcid) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = ItemTypeMisc; + FakeHost.Wcids[id] = wcid; + FakeHost.Containers[id] = Player; + } + + private static TickIsolationTests.Bot Rig(bool stone = true, bool combat = false, bool revealedOnly = false) + { + var bot = new TickIsolationTests.Bot(combat: combat, heal: false, arrange: () => + { + FakeHost.ContentsCalls = true; // the live pack walk + FakeHost.UseOnCalls = true; + if (revealedOnly) Item(Revealed, "Aetheria", AetheriaUnboxer.WcidBlue); + else + { + Item(Blue, AetheriaUnboxer.CoalescedName, AetheriaUnboxer.WcidBlue); + Item(Red, AetheriaUnboxer.CoalescedName, AetheriaUnboxer.WcidRed); + } + if (stone) Item(Stone, AetheriaUnboxer.StoneName, AetheriaUnboxer.WcidManaStone); + }); + foreach (uint id in new[] { Blue, Red, Stone, Revealed }) + if (FakeHost.Names.ContainsKey(id)) _ = bot.Cache[unchecked((int)id)]; + bot.S.UnboxAetheriaWhenIdle = true; + bot.S.MonsterRange = 20; + var unboxer = (AetheriaUnboxer)bot.Call("CreateAetheriaUnboxer", bot.S)!; + unboxer.NowMs = () => bot.Now; + bot.Set("_aetheriaUnboxer", unboxer); + return bot; + } + + private static AetheriaUnboxer U(TickIsolationTests.Bot bot) => (AetheriaUnboxer)bot.Get("_aetheriaUnboxer")!; + private static bool Tick(TickIsolationTests.Bot bot) => (bool)bot.Call("TickAetheriaUnbox", bot.S)!; + + /// The server's answer to the unbox in flight: the sigil line, the new name, the UseDone. + private static void Reveal(TickIsolationTests.Bot bot, uint id) + { + U(bot).OnChat(AetheriaUnboxer.SigilLine); + FakeHost.Names[id] = "Aetheria"; + FakeHost.UseDone(0); + } + + private static CombatManager.ScannedTarget At(double yards) => + new() { Id = unchecked((int)Monster), Distance = yards, Name = "Drudge Skulker" }; + + private static void UnboxesOneAtATime() + { + try + { + var bot = Rig(); + Check.True(Tick(bot), "the unbox goes out, and the bot holds still for the clap"); + Check.Eq(FakeHost.UsesOn.Count, 1, "one use-on"); + var first = FakeHost.UsesOn[0]; + Check.True(first.Source == Stone && (first.Target == Blue || first.Target == Red), "the mana stone on a coalesced aetheria"); + + for (int i = 0; i < 5; i++) { bot.Now += 500; Tick(bot); } + Check.Eq(FakeHost.UsesOn.Count, 1, "no answer yet: nothing more goes out"); + + Reveal(bot, first.Target); + Check.False(Tick(bot), "the sigil rose: the unbox is over"); + Check.Eq(U(bot).Revealed, 1, "one revealed"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[Aetheria] revealed")), "and logged"); + + bot.Now += 500; + Tick(bot); + Check.Eq(FakeHost.UsesOn.Count, 1, "the server stays busy for the return to ready: a short pause first"); + bot.Now += AetheriaUnboxer.GapMs; + Check.True(Tick(bot), "the next piece goes out"); + Check.Eq(FakeHost.UsesOn.Count, 2, "two use-ons"); + var second = FakeHost.UsesOn[1]; + Check.True(second.Source == Stone && second.Target != first.Target && (second.Target == Blue || second.Target == Red), + "the same stone (it isn't used up) on the other piece"); + + Reveal(bot, second.Target); + Tick(bot); + for (int i = 0; i < 20; i++) { bot.Now += 1_000; Tick(bot); } + Check.Eq(FakeHost.UsesOn.Count, 2, "nothing coalesced left: nothing more"); + Check.Eq(U(bot).Revealed, 2, "both revealed"); + Check.False(FakeHost.Chat.Any(c => c.Contains("no Aetheria Mana Stone")), "and no out-of-stones line (the stone is still there)"); + } + finally { TickIsolationTests.Done(); } + } + + private static void NotInAFight() + { + try + { + var bot = Rig(combat: true); + var cm = (CombatManager)bot.Get("_combatManager")!; + cm.SetScannedTargetsForTests(new[] { At(2) }); + for (int i = 0; i < 5; i++) { bot.Now += 2_000; Tick(bot); } + Check.Eq(FakeHost.UsesOn.Count, 0, "a monster on us: no unbox (the server would put us in peace mode)"); + + bot.S.EnableCombat = false; + for (int i = 0; i < 3; i++) { bot.Now += 2_000; Tick(bot); } + Check.Eq(FakeHost.UsesOn.Count, 0, "not with Enable Combat off either: a fight by hand counts"); + bot.S.EnableCombat = true; + + cm.SetScannedTargetsForTests(Array.Empty()); + bot.Now += 2_000; + Check.True(Tick(bot), "the fight is over: it unboxes"); + Check.Eq(FakeHost.UsesOn.Count, 1, "one use-on"); + + cm.SetScannedTargetsForTests(new[] { At(5) }); + Check.False(Tick(bot), "a monster comes mid-unbox: no hold, combat has the tick"); + Check.Eq(FakeHost.UsesOn.Count, 1, "and nothing more goes out"); + } + finally { TickIsolationTests.Done(); } + } + + private static void NothingWhenOff() + { + try + { + var bot = Rig(); + bot.S.UnboxAetheriaWhenIdle = false; + for (int i = 0; i < 5; i++) { bot.Now += 6_000; Tick(bot); } + Check.Eq(FakeHost.UsesOn.Count, 0, "the option off: nothing"); + + bot.S.UnboxAetheriaWhenIdle = true; + bot.S.IsMacroRunning = false; + for (int i = 0; i < 5; i++) { bot.Now += 6_000; Tick(bot); } + Check.Eq(FakeHost.UsesOn.Count, 0, "the macro off: nothing"); + + bot.S.IsMacroRunning = true; + bot.Now += 6_000; + Tick(bot); + Check.Eq(FakeHost.UsesOn.Count, 1, "both on: it unboxes"); + } + finally { TickIsolationTests.Done(); } + } + + private static void RefusalBacksOff() + { + try + { + var bot = Rig(); + Tick(bot); + Check.Eq(FakeHost.UsesOn.Count, 1, "the first try"); + FakeHost.UseDone(AetheriaUnboxer.TooBusyErr); + Check.False(Tick(bot), "refused as busy: over"); + + bot.Now += 9_000; + Tick(bot); + Check.Eq(FakeHost.UsesOn.Count, 1, "9 s later: still waiting"); + bot.Now += 1_500; + Tick(bot); + Check.Eq(FakeHost.UsesOn.Count, 2, "past 10 s: tried again"); + + // No answer at all: a failed try after the timeout, and a longer wait (30 s). + bot.Now += AetheriaUnboxer.UnboxTimeoutMs; + Check.False(Tick(bot), "no answer in 10 s: given up for now"); + bot.Now += 20_000; + Tick(bot); + Check.Eq(FakeHost.UsesOn.Count, 2, "20 s later: the second wait is 30 s"); + bot.Now += 11_000; + Tick(bot); + Check.Eq(FakeHost.UsesOn.Count, 3, "past 30 s: tried again"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[Aetheria] unbox of") && l.Contains("too busy")), "the refusal is logged"); + } + finally { TickIsolationTests.Done(); } + } + + private static void NoStoneSaidOnce() + { + try + { + var bot = Rig(stone: false); + for (int i = 0; i < 6; i++) { bot.Now += 6_000; Tick(bot); } + Check.Eq(FakeHost.UsesOn.Count, 0, "no stone: nothing to use"); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("no Aetheria Mana Stone")), 1, "said once in chat"); + Check.True(FakeHost.Chat.Any(c => c.Contains("2 coalesced aetheria")), "with how many are waiting"); + } + finally { TickIsolationTests.Done(); } + } + + private static void RevealedLeftAlone() + { + try + { + var bot = Rig(revealedOnly: true); + for (int i = 0; i < 4; i++) { bot.Now += 6_000; Tick(bot); } + Check.Eq(FakeHost.UsesOn.Count, 0, "an 'Aetheria' (sigil showing) is not unboxed again"); + Check.True(U(bot).Describe().Contains("0 coalesced"), "status: none coalesced (" + U(bot).Describe() + ")"); + } + finally { TickIsolationTests.Done(); } + } + + private static void ManualRun() + { + try + { + var bot = Rig(); + bot.S.UnboxAetheriaWhenIdle = false; + bot.S.IsMacroRunning = false; + var u = U(bot); + Check.True(u.RequestManual(out string reply), "asked by hand: " + reply); + Check.True(reply.Contains("2 coalesced"), "the reply says how many"); + Check.False(Tick(bot), "the macro is off: nothing to hold"); + Check.Eq(FakeHost.UsesOn.Count, 1, "but the unbox goes out"); + Reveal(bot, FakeHost.UsesOn[0].Target); + Tick(bot); + bot.Now += AetheriaUnboxer.GapMs; + Tick(bot); + Check.Eq(FakeHost.UsesOn.Count, 2, "the second piece"); + Reveal(bot, FakeHost.UsesOn[1].Target); + Tick(bot); + bot.Now += AetheriaUnboxer.GapMs; + Tick(bot); + Check.True(FakeHost.Chat.Any(c => c.Contains("Aetheria: revealed 2")), "the run ends with how many: " + string.Join(" | ", FakeHost.Chat)); + Check.False(u.ManualRun, "and is over"); + Check.False(u.RequestManual(out string none), "nothing left to unbox: refused"); + Check.True(none.Contains("no Coalesced Aetheria"), "with the reason: " + none); + } + finally { TickIsolationTests.Done(); } + } + + private static void Settings() + { + Check.False(new LegacyUiSettings().UnboxAetheriaWhenIdle, "off by default"); + var old = JsonSerializer.Deserialize("{\"EnableAutostack\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!; + Check.False(old.UnboxAetheriaWhenIdle, "a profile from before the setting: off"); + var saved = JsonSerializer.Deserialize( + JsonSerializer.Serialize(new LegacyUiSettings { UnboxAetheriaWhenIdle = true }, RynthAiJsonContext.Default.LegacyUiSettings), + RynthAiJsonContext.Default.LegacyUiSettings)!; + Check.True(saved.UnboxAetheriaWhenIdle, "on saves and loads"); + + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { UnboxAetheriaWhenIdle = true }, dst }); + Check.True(dst.UnboxAetheriaWhenIdle, "a profile switch copies it"); + + var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(payload != null && payload.UnboxAetheriaWhenIdle == null, "an older engine's payload has no value"); + var s = new LegacyUiSettings { UnboxAetheriaWhenIdle = true }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); // a stand-in with its profile in memory + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.UnboxAetheriaWhenIdle == true, "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.True(s.UnboxAetheriaWhenIdle, "an engine save without the field leaves it"); + dash.ApplySettingsJson("{\"UnboxAetheriaWhenIdle\":false}"); + Check.False(s.UnboxAetheriaWhenIdle, "an engine save with it sets it"); + + var ms = new LegacyUiSettings(); + var e = ExpressionTests.Engine(settings: ms); + Check.Eq(e.Evaluate("vtsetsetting[UnboxAetheriaWhenIdle, 1]"), "1", "metas: vtsetsetting knows it"); + Check.True(ms.UnboxAetheriaWhenIdle, "and turns it on"); + Check.Eq(e.Evaluate("vtgetsetting[UnboxAetheriaWhenIdle]"), "1", "vtgetsetting reads it back"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AutoStackTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AutoStackTests.cs index 0b917ae..fe7932b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/AutoStackTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AutoStackTests.cs @@ -13,6 +13,43 @@ internal static class AutoStackTests { 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); + r.Add("autostack: name guesses match pyreals exactly and the rest as whole words (Pyreal Mote, Spear, Pearl don't stack)", NameGuess); + r.Add("autostack: a guessed group the server refuses 3 times running is given up; a merge between resets it", Refusals); + } + + private static void NameGuess() + { + Check.Eq(25000, InventoryManager.NameFallbackMaxStack("Pyreal"), "pyreal coins"); + Check.Eq(25000, InventoryManager.NameFallbackMaxStack("Pyreals"), "pyreal coins, plural"); + Check.Eq(1, InventoryManager.NameFallbackMaxStack("Pyreal Mote"), "2026-11-08: motes don't stack"); + Check.Eq(1, InventoryManager.NameFallbackMaxStack("Quality Pyreal Ingot"), "ingots don't stack"); + Check.Eq(1, InventoryManager.NameFallbackMaxStack("Spear"), "'pea' inside a word"); + Check.Eq(1, InventoryManager.NameFallbackMaxStack("Black Pearl"), "'pea' inside a word"); + Check.Eq(1, InventoryManager.NameFallbackMaxStack("Arrowheads"), "'arrow' inside a word"); + Check.Eq(250, InventoryManager.NameFallbackMaxStack("Greater Deadly Armor Piercing Arrow"), "arrows"); + Check.Eq(250, InventoryManager.NameFallbackMaxStack("Deadly Fire Quarrel"), "quarrels"); + Check.Eq(100, InventoryManager.NameFallbackMaxStack("Iron Scarab"), "scarabs"); + Check.Eq(100, InventoryManager.NameFallbackMaxStack("Prismatic Taper"), "tapers"); + Check.Eq(1, InventoryManager.NameFallbackMaxStack(null), "no name"); + Check.Eq(1, InventoryManager.NameFallbackMaxStack(" "), "blank name"); + } + + private static void Refusals() + { + var r = new StackGroupRefusals(); + Check.False(r.Refused("w:6353"), "1st refusal"); + Check.False(r.Refused("w:6353"), "2nd refusal"); + Check.False(r.GivenUp("w:6353"), "not yet"); + Check.True(r.Refused("w:6353"), "3rd refusal gives it up, once"); + Check.True(r.GivenUp("w:6353"), "given up"); + Check.False(r.Refused("w:6353"), "already given up: no second notice"); + + Check.False(r.Refused("w:1"), "other group 1st"); + Check.False(r.Refused("w:1"), "other group 2nd"); + r.Merged("w:1"); + Check.False(r.Refused("w:1"), "a merge between resets the count"); + Check.False(r.GivenUp("w:1"), "the other group goes on"); + Check.False(r.Refused(""), "an empty group never counts"); } private static void GroupKey() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorFoldersTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorFoldersTests.cs new file mode 100644 index 0000000..7fb5a3e --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorFoldersTests.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Json; +using RynthCore.Loot.Editing; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.Plugin.RynthAi.Vendor; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-11-04 (Discord): "Autovendor creates folders for each server, but it only reads from the +// parent folder". A vendor's run looked in the character, server and main folders (UB's order), +// but everything a player sees or picks named the main folder only: the Loot Editor's picker listed +// AutoVendor and its server folders as one tree and never the character folder, the dashboard's +// Edit on a vendor with no profile made the new one in the main folder, beside the server folder +// AutoVendor had just made, and "No vendor profile exists" gave the main folder's path alone. +// +// AutoVendorManager.MainProfileDir points at the scratch folder here; FakeHost.WorldName is the server. +internal static unsafe class AutoVendorFoldersTests +{ + private const uint Player = 0x50000B01; + private const uint Vendor = 0x70000B01; + private const string VendorFile = "Town Vendor.utl"; + + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("autovendor folders: a profile only in AutoVendor\\ is found, for the run and the Edit button", ServerFolderFound); + r.Add("autovendor folders: character folder, then server, then main (named profiles before default.utl)", UbOrder); + r.Add("autovendor folders: the folders a vendor open makes are the ones read (a server name with a bad file character)", MadeFoldersAreRead); + r.Add("autovendor folders: a vendor with no profile gets its new one in the server folder (main before the server is known)", NewProfileInServerFolder); + r.Add("autovendor folders: the Loot Editor lists character, server and main profiles in that order, marked by folder", PickerListsEveryFolder); + r.Add("autovendor folders: the plugin's Loot Editor picker reads AutoVendor's folders", PluginPickerWired); + r.Add("autovendor folders: 'No vendor profile exists' names every folder it looked in", MissingProfileNamesEveryFolder); + } + + private sealed class Rig + { + public AutoVendorManager M = null!; + public string Main = "", Char = "", CharAv = ""; + public RynthCoreHost Host; + } + + /// A fresh main and character folder; is the server ("" = not known). + private static Rig World(string world, FakeHost.ApiHook? api = null) + { + FakeHost.Reset(); + FakeHost.ConfigureApi = api; + FakeHost.WorldName = world; + FakeHost.Names[Player] = "Test Seller"; + FakeHost.Names[Vendor] = "Town Vendor"; + string root = Path.Combine(Program.TempRoot, "avfolders-" + Guid.NewGuid().ToString("N")[..8]); + var rig = new Rig { Main = Path.Combine(root, "AutoVendor"), Char = Path.Combine(root, "SettingsProfiles", "Srv", "Char") }; + rig.CharAv = Path.Combine(rig.Char, AutoVendorManager.ProfileSubfolder); + AutoVendorManager.MainProfileDirOverride = rig.Main; + rig.Host = FakeHost.Create(Player); + var cache = new WorldObjectCache(rig.Host); + cache.SetPlayerId(Player); + // Off: the open only resolves the Edit button's profile, no session. + var settings = new LegacyUiSettings { AutoVendorEnabled = false, AutoVendorShowMerchantInfo = false }; + string charFolder = rig.Char; + rig.M = new AutoVendorManager(rig.Host, settings, cache, Player, () => charFolder); + return rig; + } + + private static void Scoped(Action body) + { + string? old = AutoVendorManager.MainProfileDirOverride; + try { body(); } + finally { AutoVendorManager.MainProfileDirOverride = old; FakeHost.WorldName = ""; } + } + + private static string Put(string dir, string name) + { + Directory.CreateDirectory(dir); + string p = Path.Combine(dir, name); + File.WriteAllText(p, "UTL\n1\n0\n"); + return p; + } + + private static bool Same(string? a, string b) + => a != null && string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase); + + // ── Tests ───────────────────────────────────────────────────────────────── + + private static void ServerFolderFound() => Scoped(() => + { + var rig = World("Conquest"); + string server = Path.Combine(rig.Main, "Conquest"); + string p = Put(server, VendorFile); + Put(rig.Main, "Other Vendor.utl"); // something in the main folder that isn't this vendor's + + Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), p), "the run's lookup finds AutoVendor\\Conquest\\" + VendorFile); + rig.M.OnVendorOpen(Vendor); + Check.True(Same(rig.M.OpenVendorProfilePath, p), "the Edit button opens the server folder's profile: " + rig.M.OpenVendorProfilePath); + Check.True(Same(rig.M.ResolveProfilePath("Town Vendor", true), p), "/ub autovendor Town Vendor (no .utl) finds it too"); + }); + + private static void UbOrder() => Scoped(() => + { + var rig = World("Conquest"); + string server = Path.Combine(rig.Main, "Conquest"); + string inChar = Put(rig.CharAv, VendorFile); + string inServer = Put(server, VendorFile); + string inMain = Put(rig.Main, VendorFile); + + Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), inChar), "the character folder wins"); + File.Delete(inChar); + Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), inServer), "then the server folder"); + File.Delete(inServer); + Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), inMain), "the main folder last"); + + // UB: the vendor's own profile in any folder before default.utl in any folder. + string serverDefault = Put(server, "default.utl"); + Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), inMain), "a named profile in main beats default.utl in the server folder"); + File.Delete(inMain); + Put(rig.Main, "default.utl"); + Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), serverDefault), "the server's default.utl before main's"); + + List dirs = rig.M.ProfileDirs(); + Check.Eq(dirs.Count, 3, "three folders"); + Check.True(dirs.Count == 3 && Same(dirs[0], rig.CharAv) && Same(dirs[1], server) && Same(dirs[2], rig.Main), + "ProfileDirs: character, server, main: " + string.Join(" | ", dirs)); + }); + + private static void MadeFoldersAreRead() => Scoped(() => + { + var rig = World("Dream:Weave "); + rig.M.OnVendorOpen(Vendor); // EnsureProfileFolders + string made = Path.Combine(rig.Main, "Dream_Weave"); + Check.True(Directory.Exists(made), "the server folder is made with the name's bad character replaced"); + Check.True(Directory.Exists(rig.CharAv), "the character's AutoVendor folder is made"); + var dirs = rig.M.ProfileDirs(); + Check.True(dirs.Any(d => Same(d, made)) && dirs.Any(d => Same(d, rig.CharAv)), "and both are read: " + string.Join(" | ", dirs)); + string p = Put(made, VendorFile); + Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), p), "a profile put in the made folder is found"); + }); + + private static void NewProfileInServerFolder() => Scoped(() => + { + var rig = World("Conquest"); + rig.M.OnVendorOpen(Vendor); + string expect = Path.Combine(rig.Main, "Conquest", VendorFile); + Check.True(Same(rig.M.OpenVendorProfilePath, expect), "Edit with no profile anywhere: a new one in AutoVendor\\Conquest: " + rig.M.OpenVendorProfilePath); + Check.True(Directory.Exists(Path.GetDirectoryName(expect)!), "its folder exists, so Save can create it"); + + var unknown = World(""); + Check.True(Same(unknown.M.ResolveProfilePath(VendorFile, false), Path.Combine(unknown.Main, VendorFile)), + "no server name: the main folder, as UB"); + }); + + private static List VendorFiles(LootEditorBridge b) + { + LootEditState s = JsonSerializer.Deserialize(b.StateJson(), LootEditJsonContext.Default.LootEditState)!; + return s.Files.Where(f => f.Display.StartsWith("AutoVendor", StringComparison.Ordinal)).ToList(); + } + + private static void PickerListsEveryFolder() => Scoped(() => + { + var rig = World("Conquest"); + string inChar = Put(rig.CharAv, VendorFile); + string inServer = Put(Path.Combine(rig.Main, "Conquest"), "default.utl"); + string inMain = Put(rig.Main, "default.utl"); + string otherServer = Put(Path.Combine(rig.Main, "DreamWeave"), "Elder Vendor.utl"); + + var b = new LootEditorBridge(() => string.Empty, _ => { }, () => rig.M.ProfileDirs()); + List files = VendorFiles(b); + string shown = string.Join(" | ", files.Select(f => f.Display)); + Check.Eq(files.Count, 4, "four AutoVendor profiles: " + shown); + if (files.Count != 4) return; + Check.True(Same(files[0].Path, inChar), "the character folder's first"); + Check.Eq(files[0].Display, "AutoVendor (character): " + VendorFile, "marked as the character's"); + Check.True(Same(files[1].Path, inServer), "then this server's"); + Check.Eq(files[1].Display, "AutoVendor (Conquest): default.utl", "marked by the server's folder"); + Check.True(Same(files[2].Path, inMain), "then the main folder's"); + Check.Eq(files[2].Display, "AutoVendor: default.utl", "the main folder keeps the plain mark"); + Check.True(Same(files[3].Path, otherServer), "other servers' folders last"); + Check.Eq(files[3].Display, "AutoVendor (DreamWeave): Elder Vendor.utl", "marked by their folder"); + Check.False(shown.Contains("Srv") || shown.Contains("Char"), "the character's name and folder path aren't in the picker"); + }); + + private static void PluginPickerWired() => Scoped(() => + { + var rig = World("Conquest"); + string inChar = Put(rig.CharAv, VendorFile); + string inServer = Put(Path.Combine(rig.Main, "Conquest"), VendorFile); + + var plugin = new RynthAiPlugin(); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi }); + typeof(RynthAiPlugin).GetField("_autoVendor", Any)!.SetValue(plugin, rig.M); + List files = VendorFiles(plugin.LootEditor); + Check.True(files.Any(f => Same(f.Path, inChar)), "the character folder's profile is listed: " + string.Join(" | ", files.Select(f => f.Display))); + Check.True(files.Any(f => Same(f.Path, inServer)), "the server folder's profile is listed"); + }); + + // The engine's vendor calls, present but with no vendor to show: enough for a session to start. + private static void VendorCalls(ref RynthCoreApiNative api) + { + api.Version = Math.Max(api.Version, 82u); + api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoVendorInfo; + api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoVendorItems; + api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoBuy; + api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoSell; + api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoTradeStatus; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int NoVendorInfo(VendorInfoNative* info) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int NoVendorItems(VendorItemNative* items, int max) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint NoBuy(uint vendor, VendorTradeEntryNative* entries, int count) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint NoSell(uint vendor, uint* ids, int count) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int NoTradeStatus(VendorTradeStatusNative* status) => 0; + + private static void MissingProfileNamesEveryFolder() => Scoped(() => + { + try + { + var rig = World("Conquest", VendorCalls); + var settings = new LegacyUiSettings { AutoVendorEnabled = true, AutoVendorShowMerchantInfo = false }; + string charFolder = rig.Char; + var m = new AutoVendorManager(rig.Host, settings, new WorldObjectCache(rig.Host), Player, () => charFolder); + m.OnVendorOpen(Vendor); + string line = FakeHost.Chat.FirstOrDefault(c => c.Contains("No vendor profile exists")) ?? string.Empty; + Check.True(line.Length > 0, "a vendor with no profile says so: " + string.Join(" / ", FakeHost.Chat)); + Check.True(line.Contains(VendorFile) && line.Contains("default.utl"), "the names it looked for: " + line); + Check.True(line.Contains(rig.CharAv) && line.Contains(Path.Combine(rig.Main, "Conquest")) && line.Contains(rig.Main), + "the character, server and main folders: " + line); + } + finally { FakeHost.ConfigureApi = null; } + }); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorZeroPayTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorZeroPayTests.cs new file mode 100644 index 0000000..ac759e0 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorZeroPayTests.cs @@ -0,0 +1,148 @@ +using System; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Vendor; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +/// +/// The engine trades with zero-rate vendors (a free storage vault, buy=0 sell=0). A vendor that pays +/// nothing for items (buy rate 0) met with default.utl gets nothing sold to it: that profile's Sell +/// rules turn loot into pyreals, and would hand every match over for nothing. The vendor's own +/// profile (or one named on /ub autovendor) sells as written, so a vault can still be filled. +/// TestMode shows the plan without trading. +/// +internal static unsafe class AutoVendorZeroPayTests +{ + private const uint Player = 0x50000D01; + private const uint Vendor = 0x70000D01; + private const string PaysNothing = "pays nothing for items"; + + private static float _buyRate, _sellRate; + + public static void Register(Runner r) + { + r.Add("autovendor zero pay: a vendor paying nothing, met with default.utl, gets nothing sold (said once, held back in TestMode)", DefaultProfileSellsNothing); + r.Add("autovendor zero pay: the vendor's own profile still sells to a zero-rate vault", OwnProfileSells); + r.Add("autovendor zero pay: a profile named on /ub autovendor counts as the vendor's own", NamedProfileSells); + r.Add("autovendor zero pay: a vendor that pays (buy rate above 0) is as before with default.utl", PayingVendorUnchanged); + } + + private static void VendorCalls(ref RynthCoreApiNative api) + { + api.Version = Math.Max(api.Version, 82u); + api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorInfo; + api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoVendorItems; + api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoBuy; + api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoSell; + api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl])&NoTradeStatus; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetVendorInfo(VendorInfoNative* info) + { + *info = default; + info->VendorId = Vendor; + info->ItemTypes = 0xFFFFFFFF; + info->MaxValue = 1_000_000; + info->BuyRate = _buyRate; + info->SellRate = _sellRate; + info->Flags = 1; // trading available + byte[] name = Encoding.ASCII.GetBytes("Town Vendor"); + for (int i = 0; i < name.Length; i++) info->Name[i] = name[i]; + return 1; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int NoVendorItems(VendorItemNative* items, int max) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint NoBuy(uint vendor, VendorTradeEntryNative* entries, int count) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint NoSell(uint vendor, uint* ids, int count) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int NoTradeStatus(VendorTradeStatusNative* status) => 0; + + /// Runs one TestMode session at the vendor with in the main folder. + private static void Session(float buy, float sell, string profileFile, Action? start = null) + { + _buyRate = buy; + _sellRate = sell; + FakeHost.Reset(); + FakeHost.ConfigureApi = VendorCalls; + FakeHost.Names[Player] = "Test Seller"; + FakeHost.Names[Vendor] = "Town Vendor"; + string root = Path.Combine(Program.TempRoot, "avzero-" + Guid.NewGuid().ToString("N")[..8]); + string main = Path.Combine(root, "AutoVendor"); + Directory.CreateDirectory(main); + File.WriteAllText(Path.Combine(main, profileFile), "UTL\n1\n0\n"); + AutoVendorManager.MainProfileDirOverride = main; + var host = FakeHost.Create(Player); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + var settings = new LegacyUiSettings + { + AutoVendorEnabled = start == null, AutoVendorEnableSelling = true, AutoVendorTestMode = true, AutoVendorShowMerchantInfo = false, + }; + string charFolder = Path.Combine(root, "Char"); + var m = new AutoVendorManager(host, settings, cache, Player, () => charFolder); + long now = 1_000_000; + AutoVendorManager.Clock = () => now; + m.OnVendorOpen(Vendor); + if (start != null) { settings.AutoVendorEnabled = true; start(m); } + for (int i = 0; i < 10; i++) { now += 250; m.Tick(0); } + } + + private static void Scoped(Action body) + { + string? oldDir = AutoVendorManager.MainProfileDirOverride; + var oldClock = AutoVendorManager.Clock; + try { body(); } + finally { AutoVendorManager.MainProfileDirOverride = oldDir; AutoVendorManager.Clock = oldClock; FakeHost.ConfigureApi = null; } + } + + private static string AllChat() => string.Join(" / ", FakeHost.Chat); + private static bool Said(string text) => FakeHost.Chat.Any(c => c.Contains(text, StringComparison.Ordinal)); + + private static void DefaultProfileSellsNothing() => Scoped(() => + { + foreach (float sell in new[] { 1.15f, 0f }) // a shop that pays nothing, and a vault + { + Session(0f, sell, "default.utl"); + Check.True(Said("TestMode is on"), $"sell {sell}: the TestMode session ran: " + AllChat()); + Check.Eq(FakeHost.Chat.Count(c => c.Contains(PaysNothing, StringComparison.Ordinal)), 1, $"sell {sell}: said once, at the start: " + AllChat()); + Check.True(Said("Town Vendor.utl"), $"sell {sell}: and names the profile to make"); + Check.True(Said("Held back (never sold):") && Said("everything - Town Vendor pays nothing"), $"sell {sell}: TestMode shows everything held back"); + Check.True(FakeHost.Logs.Any(l => l.Contains(PaysNothing, StringComparison.Ordinal)), $"sell {sell}: in the log too"); + } + }); + + private static void OwnProfileSells() => Scoped(() => + { + Session(0f, 0f, "Town Vendor.utl"); + Check.True(Said("TestMode is on"), "the TestMode session ran: " + AllChat()); + Check.False(Said(PaysNothing), "the vendor's own profile: no 'pays nothing' line"); + Check.False(Said("everything - "), "nothing held back for the rate"); + }); + + private static void NamedProfileSells() => Scoped(() => + { + Session(0f, 0f, "default.utl", m => m.CommandAutoVendor("default")); + Check.True(Said("TestMode is on"), "the TestMode session ran: " + AllChat()); + Check.False(Said(PaysNothing), "a profile named on the command: no 'pays nothing' line"); + }); + + private static void PayingVendorUnchanged() => Scoped(() => + { + Session(0.7f, 1.15f, "default.utl"); + Check.True(Said("TestMode is on"), "the TestMode session ran: " + AllChat()); + Check.False(Said(PaysNothing), "a vendor that pays: no 'pays nothing' line"); + Check.False(Said("everything - "), "nothing held back for the rate"); + }); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs index 104837d..1f7374b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs @@ -46,6 +46,7 @@ internal static class ChestLootTests r.Add("chest loot: reopening the chest loots it again (never marked done)", ReopenLootsAgain); r.Add("chest loot: a salvage-only item is left when no UST is carried, as on corpses", SalvageWithoutUstLeft); r.Add("chest loot: opened mid-fight it waits for combat, then is looted if still open", ChestWaitsForCombat); + r.Add("chest loot: an open chest is looted before a fight further than 5 yd off (a chest closes when you walk away)", OpenChestBeforeDistantFight); r.Add("chest loot: closed by the player mid-loot -> session ends, chest not reopened", ClosedMidLootNotReopened); r.Add("chest loot: a chest gets 2 minutes (not the 12 s corpse timeout), restarted by each pickup", ChestTimeoutLongAndRestarted); } @@ -482,6 +483,56 @@ internal static class ChestLootTests Check.Eq(FakeHost.Closes.Count, 1, "looted and closed after the fight"); } + private const uint Monster = 0x80263301; + + /// The chest world with a monster off and combat on. + private static Bot ChestWithMonster(float meters, out CombatManager combat) + { + BaseWorld("Unearthed Cache"); + FakeHost.Names[Monster] = "Drumtaken Ironstone Golem"; + FakeHost.ItemTypes[Monster] = 0x10; // creature + FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + meters, Me0.Y + 0.5f, Me0.Z); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.EnableCombat = true; + bot.S.MonsterRange = 50; + bot.Create(Chest, Gem, Spoon); + _ = bot.Cache[unchecked((int)Monster)]; + bot.Cache.OnUpdateHealth(Monster, 1f); + bot.Cache.Tick(); + combat = new CombatManager(host, bot.S, bot.Cache); + combat.SetPlayerId(Player); + typeof(CombatManager).GetField("_lastScanTime", Any)?.SetValue(combat, DateTime.MinValue); + combat.ScanNearbyTargets(); + bot.Set("_combatManager", combat); + return bot; + } + + // 2026-11-07: a meta opened a treasure cache with a golem 32 m off; combat walked to the golem, the + // cache closed and nothing was taken. + private static void OpenChestBeforeDistantFight() + { + var bot = ChestWithMonster(30f, out var combat); + Check.True(combat.HasEngageableTarget, "a monster 30 m off: combat wants the tick"); + Check.False((bool)bot.Call("IsOpenChestTurn", true, true)!, "no chest open: no chest turn"); + bot.ServerOpens(Chest); + Check.True(bot.HasLootWork(), "the open chest wants the tick"); + Check.True((bool)bot.Call("IsOpenChestTurn", true, true)!, "open chest, nothing within 5 yd: the chest goes first"); + Check.False((bool)bot.Call("IsOpenChestTurn", false, true)!, "(only when there is loot work)"); + var inputs = new ArbiterInputs(true, false, true, true, false, false, lootStarved: true); + Check.Eq(ActivityArbiter.Decide(in inputs), BotActivity.Looting, "the arbiter gives Looting the tick"); + bot.Set("_lootStarveTurn", true); + LootGemAndFinish(bot, Gem); + Check.True(FakeHost.Closes.Count >= 1, "the gem taken before the fight, the chest closed"); + Check.True(FakeHost.Logs.Any(l => l.Contains("looted before the fight")), "logged"); + Check.Eq(bot.Get("_lastChestLootedId"), Chest, "ralastchestlooted[] names the chest looted to the end"); + + var close = ChestWithMonster(2f, out var combat2); + Check.True(combat2.HasCloseThreat(RynthAiPlugin.LootStarveCloseYards), "a monster within 5 yd"); + close.ServerOpens(Chest); + Check.False((bool)close.Call("IsOpenChestTurn", true, true)!, "a monster at the chest is fought first"); + } + private static void ClosedMidLootNotReopened() { BaseWorld(); @@ -499,6 +550,7 @@ internal static class ChestLootTests Check.False(FakeHost.Uses.Contains(Chest), "the chest is never reopened by the looter"); Check.Eq(FakeHost.Closes.Count, 0, "nothing to close: it is closed already"); Check.False(bot.Marked(Chest), "and not marked: opening it again loots it"); + Check.Eq(bot.Get("_lastChestLootedId"), 0u, "a chest closed mid-loot doesn't count as looted (a meta opens it again)"); Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before looting finished")), "logged"); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs index 6ea13d5..3832162 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs @@ -53,6 +53,8 @@ internal static class CombatHookTests r.Add("combat hook: a script answer at an ignored monster is rejected, even one hitting us (RynthAi casts its own)", HookRejectsIgnoredTarget); r.Add("combat hook: a script heal (a drain) at a fight target whose rule turned to Priority 0 is rejected", HookHealRejectsIgnoredTarget); r.Add("blacklist: casts answered 'too busy' (UseDone 0x1D) are not no-damage casts (answered 0: the target is dropped)", RefusedCastsNotJudged); + r.Add("loot jump: Think sends no cast while in the air after a loot jump; it casts on the landing, or at the cap", LootJumpHoldsAttack); + r.Add("loot jump: a swing refused in the air (WeenieError 0x4EB) is not a no-damage attack (without it: a miss)", MeleeInAirNotJudged); r.Add("combat hook: ctx.pending is the cast in flight; ctx.last the last resolved one, err its first UseDone (final; -1 when missed or after 7 s)", LastErrIsTheCastsAnswer); r.Add("combat hook: an attack and a heal in flight take their UseDones in send order (attack 0x401, heal 0)", AnswersInSendOrder); r.Add("combat hook: a script heal refused for mana keeps its 2 s rest (no recovery fast retry)", ScriptHealNoFastRetry); @@ -1049,9 +1051,9 @@ internal static class CombatHookTests private static void RefusedCastsNotJudged() => Guard(() => { int drain = Id("Drain Health Other V"); - foreach (uint answer in new uint[] { 0, ActionPacer.TooBusyErr }) + foreach (uint answer in new uint[] { 0, ActionPacer.TooBusyErr, CombatManager.InTheAirErr }) { - string what = answer == 0 ? "answered 0" : "answered 0x1D"; + string what = answer == 0 ? "answered 0" : $"answered 0x{answer:X}"; var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; }); rig.S.BlacklistAttempts = 2; rig.S.EnableRaycasting = false; @@ -1071,13 +1073,71 @@ internal static class CombatHookTests Check.Eq(rig.C.activeTargetId, 0, "answered 0: two no-damage casts blacklist and drop the target"); else { - Check.Eq(rig.C.activeTargetId, Target, "answered 0x1D: refusals are not casts, the target is kept"); - Check.Eq(rig.C.RefusedCastsNotJudged, 2, "both kept out of the count"); - Check.True(FakeHost.Logs.Any(l => l.Contains("refused 'too busy' (UseDone 0x1D): not counted")), "logged"); + Check.Eq(rig.C.activeTargetId, Target, $"{what}: refusals are not casts, the target is kept"); + Check.Eq(rig.C.RefusedCastsNotJudged, 2, $"{what}: both kept out of the count"); + Check.Eq(Field(rig.C, "_consecutiveCastMisses"), 0, $"{what}: no miss counted"); + Check.True(FakeHost.Logs.Any(l => l.Contains(answer == ActionPacer.TooBusyErr + ? "refused 'too busy' (UseDone 0x1D): not counted" : "refused in the air (UseDone 0x4EB): not counted")), $"{what}: logged"); } } }); + // A jump-loot pickup's jump (ActionPacer.NoteLootJump) holds the attack until the landing. + // ACE refuses a cast, swing or shot in the air (Player_Magic/Melee/Missile: IsJumping). + private static void LootJumpHoldsAttack() => Guard(() => + { + bool pacer = ActionPacer.Enabled; + var clock = ActionPacer.NowMs; + long t = 1_000_000; + ActionPacer.Enabled = false; // only the air hold under test (it does not depend on the pacer switch) + ActionPacer.NowMs = () => t; + try + { + foreach (bool cap in new[] { false, true }) + { + string what = cap ? "landing never seen" : "landing seen"; + var rig = new AttackRig(think: true); + ActionPacer.ForgetLootJump(); + ActionPacer.NoteLootJump(rig.Host); // the pickup's jump, from the ground + var ground = FakeHost.PlayerPose; + FakeHost.PlayerPose = (ground.Cell, ground.X, ground.Y, ground.Z + 1.0f); + rig.C.Think(); + Check.Eq(FakeHost.Casts.Count, 0, $"{what}: no cast in the air"); + Check.Eq(rig.C.LastCombatSkipReason, "loot-jump-air", $"{what}: held for the landing"); + Check.Eq(rig.C.GetStateSnapshot().LastAttackCmd, DateTime.MinValue, $"{what}: no attack stamped"); + Check.Eq(rig.C.activeTargetId, Target, $"{what}: the target stays"); + t += ActionPacer.JumpLandMinMs + 100; + rig.C.Think(); + Check.Eq(FakeHost.Casts.Count, 0, $"{what}: still up: no cast"); + if (!cap) + FakeHost.PlayerPose = ground; // landed + else + t += ActionPacer.JumpLandMaxMs; // up for good: the cap + rig.C.Think(); + Check.Eq(rig.LastCast, "Flame Bolt VI", $"{what}: the cast goes at once"); + Check.Eq(Field(rig.C, "_consecutiveCastMisses"), 0, $"{what}: nothing counted for the held ticks"); + } + } + finally { ActionPacer.Enabled = pacer; ActionPacer.NowMs = clock; ActionPacer.ForgetLootJump(); ActionPacer.Forget("test"); } + }); + + private static void MeleeInAirNotJudged() => Guard(() => + { + foreach (bool inAir in new[] { false, true }) + { + var rig = new AttackRig(setup: () => { FakeHost.WeaponCalls = true; FakeHost.CombatModeValue = CombatMode.Melee; FakeHost.WeenieErrorCalls = true; }); + rig.S.BlacklistAttempts = 5; + rig.S.EnableRaycasting = false; // (the raycast warm-up drops every judgement) + rig.C.RecordOffensiveCast(Target); // a swing goes out + if (inAir) FakeHost.WeenieError(CombatManager.InTheAirErr); // ACE: "You can't do that while in the air" + SetField(rig.C, "_pendingJudgeCastAt", DateTime.Now.AddSeconds(-30)); + CallPrivate(rig.C, "JudgePendingCast"); + Check.Eq(Field(rig.C, "_consecutiveCastMisses"), inAir ? 0 : 1, + inAir ? "refused in the air: not a miss" : "control, no refusal: a no-damage swing is a miss"); + if (inAir) Check.True(FakeHost.Logs.Any(l => l.Contains("refused in the air (0x4EB)")), "logged"); + } + }); + private static void LastErrIsTheCastsAnswer() => Guard(() => { int drain = Id("Drain Health Other V"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CommandReplyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CommandReplyTests.cs index 092cb8b..1abd8e7 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CommandReplyTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CommandReplyTests.cs @@ -119,6 +119,11 @@ internal static class CommandReplyTests new(null, "/ra dunnav 1 2", K.Act), new(null, "/ra dunnav", K.Act), new(null, "/ra dunnav-patrol", K.Act), + new(null, "/ra dunroute banana", K.Act), + new(null, "/ra dunroute Hive exit to exit", K.Act), // outdoors here: "requires you to be inside a dungeon" + new(null, "/ra dunroute info", K.Act), + new(null, "/ra dunpatrol-save", K.Act), + new(null, "/ra dunpatrol-save Hive patrol", K.Act), // outdoors here new(null, "/ra nav restart", K.Act), new(null, "/ra nav banana", K.Act), new(null, "/ra meta banana", K.Act), @@ -158,9 +163,13 @@ internal static class CommandReplyTests new(null, "/ra fellowship leader", K.Act), new("/ra mstats reset", "/ra mstats", K.Act), // no monster selected with stats: why, and the usage new(null, "/ra mstats show", K.Act), // this rig's engine has no plugin windows: says so + new("/ra aetheria off", "/ra aetheria banana", K.Act), + new(null, "/ra aetheria unbox", K.Act), // nothing coalesced in this rig's pack: says so new(null, "/ra nosuchverb", K.Act), // ── /ra: output asked for ── new("/ra help", null, K.Query), + new("/ra aetheria", null, K.Query), + new("/ra aetheria status", null, K.Query), new("/ra", null, K.Query), new("/ra version", null, K.Query), new("/ra server", null, K.Query), @@ -207,6 +216,8 @@ internal static class CommandReplyTests new("/ra debug", null, K.Query), new("/ra loot", null, K.Query), new("/ra hazard", null, K.Query), + new("/ra dunroute where", null, K.Query), + new("/ra dunroute", null, K.Query), new("/ra hazard list", null, K.Query), new("/ra hazard texture list", null, K.Query), new("/ra groundloot", null, K.Query), @@ -479,6 +490,7 @@ internal static class CommandReplyTests Set("_combatManager", combat); Set("_fellowshipTracker", new FellowshipTracker()); Set("_jumper", new Jumper(host, S, text => P.Reply.Fail(text))); + Set("_aetheriaUnboxer", new RynthCore.Plugin.RynthAi.Loot.AetheriaUnboxer(host, S, cache) { PlayerId = () => Player }); Set("_initialized", true); Set("_loginComplete", true); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs new file mode 100644 index 0000000..c543735 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs @@ -0,0 +1,1342 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Raycasting; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; +using V3 = RynthCore.Plugin.RynthAi.Raycasting.Vector3; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Dungeon routes made on demand (2026-10-30): /ra dunroute to exit|far|portal | |room , +// /ra dunpatrol-save, /ra dunroute info|where, and the "RynthAi.Routes" interface (Shared/RynthAiRoutesApi.cs) +// that does the same with JSON. One implementation (RynthAiPlugin.DunRoutes.cs, DungeonRouteMaker.cs), so: +// - routes on a hand-built dungeon (world metres in landblock 0x7E7E, floors at z 0, as PatrolPortalTests): +// to the exit portal (named like one), to a portal by name, to a spot, to a room, to the far end; what +// isn't walkable (lava/acid, a drop) or isn't there is refused with the reason; other portals kept out of; +// - the saved files: VTank format, read back by RynthAi's own parser, run by NavigationEngine to the end, in +// the dungeon by the engine's own area check; the patrol saved is the lap /ra dunnav-patrol installs; +// - name rules, the JSON requests (bad ones refused), the jobs (queued, working, done, failed, kept 32); +// - the plugin: chat commands answer, the interface's jobs run on the tick and wait out portal space; +// - Tiny Hive on the real dats, when they are on this PC. +internal static class DunRouteTests +{ + public static void Register(Runner r) + { + r.Add("dun routes: to the exit portal (named like one): stops at its edge, a Portal step uses it, other portals kept out of", ToExit); + r.Add("dun routes: the exit is picked by its destination, its name, where you came in, or as the only portal", ExitPick); + r.Add("dun routes: to a portal by name (exact, else contained, the nearest of several); an unknown name lists the known", ToPortalByName); + r.Add("dun routes: to a spot in dungeon coordinates ends on it; a spot outside the dungeon is refused", ToPosition); + r.Add("dun routes: to a room by number, and to the farthest spot on foot", ToRoomAndFar); + r.Add("dun routes: lava/acid, a drop, no portal known and no map are said as such", Refusals); + r.Add("dun routes: a route that passes another portal is bent round it", BentRoundAnotherPortal); + r.Add("dun routes: the saved route is VTank's format, reads back the same, and NavigationEngine runs it to the end in the dungeon", SavedRouteRuns); + r.Add("dun routes: info says points, length, cells, landblock and whether it is this dungeon's", Info); + r.Add("dun routes: name rules (the nav rules: no folders, no reserved names, .nav dropped); never overwrite unless asked", NameRules); + r.Add("dun routes: the command words: to [overwrite], names holding 'to', portal names holding 'to'", CommandWords); + r.Add("dun routes: the interface's JSON requests: the four ops parse, bad input is refused with the reason", JsonRequests); + r.Add("dun routes: jobs: queued, working, done, failed; 32 kept, the oldest finished dropped; unknown ids; ids never reused", JobStates); + r.Add("dun routes: the RynthAi.Routes table answers only its own name and versions; nothing queued without RynthAi", RoutesTable); + r.Add("dun routes: plugin: /ra dunroute saves to NavProfiles and answers; again without overwrite refused, with it replaced", PluginDunRoute); + r.Add("dun routes: plugin: /ra dunpatrol-save writes the lap /ra dunnav-patrol installs, read back by RynthAi's nav parser", PluginPatrolSave); + r.Add("dun routes: plugin: the patrol save asks the server policy as dunnav-patrol does; dunroute isn't refused", PluginPatrolPolicy); + r.Add("dun routes: plugin: interface jobs run on the tick, wait out portal space, give up after 30 s, answer JSON", PluginJobs); + r.Add("dun routes: plugin: where lists the portals with distances and the exit; arrival is where the character landed", PluginWhere); + r.Add("dun routes: Tiny Hive 0x0289 on the real dats: a route to the Surface Portal and to the far end (if the dats are here)", TinyHiveRealDats); + r.Add("dun doorways: the doorway flags survive save and reload (NavProfiles\\.rynthai-routes.json); the .nav stays VTank's", DoorwaysSurviveReload); + r.Add("dun doorways: an edited file gets no flags (one log line); a nav the route maker didn't write is never touched", DoorwaysEditedFile); + r.Add("dun doorways: plugin: restored on load in its dungeon only (another dungeon: none, until you are in it)", DoorwaysPluginLoad); + r.Add("dun doorways: a missing or corrupt sidecar never breaks loading; the next save writes a good one", DoorwaysCorruptSidecar); + r.Add("dun doorways: an overwrite updates the entry; an entry whose file is gone is pruned", DoorwaysOverwriteAndPrune); + r.Add("dun doorways: NavigationEngine reaches the restored doorway points within 1 yd (a plain point at 1.5)", DoorwaysEngineReach); + } + + // ── The sample dungeon ─────────────────────────────────────────────────── + + private const uint Lb = 0x7E7E; + private const double Ox = 0x7E * 192.0, Oy = 0x7E * 192.0; + private const uint SurfaceId = 0x7E7E9001, DepthsId = 0x7E7E9002; + + /// A hand-built dungeon in landblock 0x7E7E; positions are landblock-local metres. + private sealed class Sample + { + public readonly Dictionary Graph = new(); + public readonly List<(uint, V3[])> Portals = new(), Floors = new(), Walls = new(); + private uint _next = (Lb << 16) | 0x0100; + public readonly uint[,] Hall = new uint[3, 3]; + public uint C1, C2, Nook, E1, Side, W1, West; + + /// A cell whose floor is the rectangle (x0,y0)-(x1,y1) (local) at height z; its origin is the middle. + public uint Cell(double x0, double y0, double x1, double y1, double z = 0) + { + uint id = _next++; + Graph[id] = new DungeonNavNode + { + CellId = id, + EW = DungeonGeometry.WorldToNav(Ox + (x0 + x1) / 2), + NS = DungeonGeometry.WorldToNav(Oy + (y0 + y1) / 2), + Z = (float)z, + }; + Floors.Add((id, Rect(Ox + x0, Oy + y0, Ox + x1, Oy + y1, z))); + return id; + } + + public void OpenX(uint a, uint b, double x, double y0, double y1) => Open(a, b, Quad(Ox + x, Oy + y0, Ox + x, Oy + y1)); + public void OpenY(uint a, uint b, double y, double x0, double x1) => Open(a, b, Quad(Ox + x0, Oy + y, Ox + x1, Oy + y)); + + private void Open(uint a, uint b, V3[] quad) + { + Graph[a].Neighbors.Add(b); + Graph[b].Neighbors.Add(a); + Portals.Add((a, quad)); + Portals.Add((b, quad.Reverse().ToArray())); + } + + public DungeonGeometry Geo() => DungeonGeometry.Build(Graph, Portals, Floors, Walls); + + // nook (12.35..17.65, 50..54): the Surface Portal at (15, 52) + // c2 (12.35..17.65, 40..50) + // c1 (12.35..17.65, 30..40) + // hall (0..30, 0..30): 3x3 cells of 10 m, the start in its middle (15, 15) + // west room (-25..-10, 15..35) - w1 (-10..0, y 22.35..27.65) - hall - e1 (30..40, y 2.35..7.65) - side room + // (40..50, -5..15): the Portal to the Depths in its middle (45, 5) + public Sample() + { + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + Hall[i, j] = Cell(i * 10, j * 10, i * 10 + 10, j * 10 + 10); + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + { + if (i < 2) OpenX(Hall[i, j], Hall[i + 1, j], i * 10 + 10, j * 10, j * 10 + 10); + if (j < 2) OpenY(Hall[i, j], Hall[i, j + 1], j * 10 + 10, i * 10, i * 10 + 10); + } + C1 = Cell(12.35, 30, 17.65, 40); + C2 = Cell(12.35, 40, 17.65, 50); + Nook = Cell(12.35, 50, 17.65, 54); + OpenY(Hall[1, 2], C1, 30, 12.35, 17.65); + OpenY(C1, C2, 40, 12.35, 17.65); + OpenY(C2, Nook, 50, 12.35, 17.65); + E1 = Cell(30, 2.35, 40, 7.65); + Side = Cell(40, -5, 50, 15); + OpenX(Hall[2, 0], E1, 30, 2.35, 7.65); + OpenX(E1, Side, 40, 2.35, 7.65); + W1 = Cell(-10, 22.35, 0, 27.65); + West = Cell(-25, 15, -10, 35); + OpenX(W1, Hall[0, 2], 0, 22.35, 27.65); + OpenX(West, W1, -10, 22.35, 27.65); + } + + public uint Start => Hall[1, 1]; + + public PatrolPortal Surface(string name = "Surface Portal") => new() { Id = SurfaceId, Name = name, Cell = Nook, X = Ox + 15, Y = Oy + 52, Z = 0 }; + public PatrolPortal Depths(string name = "Portal to the Depths") => new() { Id = DepthsId, Name = name, Cell = Side, X = Ox + 45, Y = Oy + 5, Z = 0 }; + + /// A world with the character at (lx, ly) local in (default: the hall's middle). + public DunRouteWorld World(double lx = 15, double ly = 15, uint cell = 0, bool geo = true, params PatrolPortal[] portals) => new() + { + Landblock = Lb, + PlayerCell = cell != 0 ? cell : Start, + StartCell = cell != 0 ? cell : Start, + X = Ox + lx, Y = Oy + ly, Z = 0, + Graph = Graph, + Geo = geo ? Geo() : null, + Portals = portals.Length > 0 ? portals.ToList() : new List { Surface(), Depths() }, + }; + } + + private static V3[] Rect(double x0, double y0, double x1, double y1, double z) => new[] + { + new V3((float)x0, (float)y0, (float)z), new V3((float)x1, (float)y0, (float)z), + new V3((float)x1, (float)y1, (float)z), new V3((float)x0, (float)y1, (float)z), + }; + + private static V3[] Quad(double x0, double y0, double x1, double y1) => new[] + { + new V3((float)x0, (float)y0, 0f), new V3((float)x1, (float)y1, 0f), + new V3((float)x1, (float)y1, 3f), new V3((float)x0, (float)y0, 3f), + }; + + private static double LX(NavPoint p) => DungeonGeometry.NavToWorld(p.EW) - Ox; + private static double LY(NavPoint p) => DungeonGeometry.NavToWorld(p.NS) - Oy; + private static string Pts(IEnumerable pts) => string.Join(" ", pts.Select(p => $"{(p.Type == NavPointType.Point ? "" : p.Type + "@")}({LX(p):F1},{LY(p):F1})")); + + private static double SegDist(double px, double py, double ax, double ay, double bx, double by) + { + double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy; + double t = l2 < 1e-12 ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / l2, 0, 1); + double cx = ax + dx * t - px, cy = ay + dy * t - py; + return Math.Sqrt(cx * cx + cy * cy); + } + + /// The nearest any walked point and leg of an open route comes to (lx, ly) local. + private static double Nearest(List pts, double lx, double ly) + { + double best = double.MaxValue; + var walk = pts.Where(p => NavRouteParser.IsPlainWaypoint(p.Type)).ToList(); + for (int i = 0; i < walk.Count; i++) + { + best = Math.Min(best, Math.Sqrt((LX(walk[i]) - lx) * (LX(walk[i]) - lx) + (LY(walk[i]) - ly) * (LY(walk[i]) - ly))); + if (i + 1 < walk.Count) best = Math.Min(best, SegDist(lx, ly, LX(walk[i]), LY(walk[i]), LX(walk[i + 1]), LY(walk[i + 1]))); + } + return best; + } + + private static DunRouteBuild Build(DunRouteWorld w, DunTarget t) + { + var b = DungeonRouteMaker.TryBuildRoute(w, t, out string error); + Check.True(b != null, $"{t.Words()}: built ({error})"); + return b!; + } + + // ── Routes ─────────────────────────────────────────────────────────────── + + private static void ToExit() + { + var d = new Sample(); + var w = d.World(); + var b = Build(w, DunTarget.Exit); + var pts = b.Route.Points; + Check.Eq(b.Route.RouteType, NavRouteType.Once, "a Once route"); + Check.Eq(b.Portal?.Name, "Surface Portal", "the Surface Portal is the exit"); + Check.Eq(b.Why, "named like an exit", "why: its name"); + Check.Near(LX(pts[0]), 15, 1e-6, "it starts where the character stands (x)"); + Check.Near(LY(pts[0]), 15, 1e-6, "... (y)"); + var step = pts[^1]; + Check.Eq(step.Type, NavPointType.PortalNPC, "it ends with a Portal step: " + Pts(pts)); + Check.Eq(step.TargetName, "Surface Portal", "the step names the portal"); + Check.Eq(step.ObjectClass, DungeonRouteMaker.PortalObjectClass, "object class Portal (14), as VTank writes it"); + Check.Near(DungeonGeometry.NavToWorld(step.PortalExitEW) - Ox, 15, 1e-6, "the step keeps the portal's position (x)"); + Check.Near(DungeonGeometry.NavToWorld(step.PortalExitNS) - Oy, 52, 1e-6, "... (y)"); + var last = pts[^2]; + double r = d.Surface().Radius; + double dEnd = Math.Sqrt((LX(last) - 15) * (LX(last) - 15) + (LY(last) - 52) * (LY(last) - 52)); + Check.True(dEnd >= r - 0.05 && dEnd <= r + 0.5, $"the walk stops at the portal's edge ({dEnd:F2} m, keep-out {r} m)"); + Check.True(Nearest(pts, 15, 52) >= r - 0.05, $"nothing walked comes inside the circle before ({Nearest(pts, 15, 52):F2} m)"); + Check.True(pts.Any(p => LY(p) > 30 && LY(p) < 50 && Math.Abs(LX(p) - 15) < 1.0), "it goes up the north corridor, on its centre line"); + Check.True(Nearest(pts, 45, 5) >= d.Depths().Radius, "nowhere near the other portal"); + Check.Eq(b.StartCell, d.Start, "start cell"); + Check.Eq(b.GoalCell, d.Nook, "goal cell: the nook the portal is in"); + Check.True(b.Doorways >= 2, $"lined up on the corridor's doorways ({b.Doorways})"); + Check.True(b.Yards > 30 && b.Yards < 45, $"about the walk's length ({b.Yards:F1} yd)"); + Check.True(b.Notes.Any(n => n.Contains("2 portals known")), "it says how many portals are known: " + string.Join(" | ", b.Notes)); + Check.True(b.TargetText.Contains("the exit portal 'Surface Portal'"), b.TargetText); + } + + private static void ExitPick() + { + var d = new Sample(); + // Named like an exit, whichever is nearer. + foreach (string name in new[] { "Exit Portal", "Portal Out", "Leave the Hive", "Return to the Surface" }) + { + var w = d.World(portals: new[] { d.Surface(name), d.Depths() }); + Check.Eq(DungeonRouteMaker.ExitCandidates(w)[0].Portal.Name, name, $"'{name}' is named like an exit"); + } + Check.False(DungeonRouteMaker.ExitWords.IsMatch("Portal to Outpost"), "'Outpost' isn't 'out'"); + Check.False(DungeonRouteMaker.ExitWords.IsMatch("Shoutout Portal"), "nor 'Shoutout'"); + + // Neither named like one: where the character came in. + var plain = d.World(portals: new[] { d.Surface("Portal to the Hub"), d.Depths() }); + Check.Eq(DungeonRouteMaker.ExitCandidates(plain).Count, 0, "no name, no arrival: no exit"); + Check.True(DungeonRouteMaker.TryBuildRoute(plain, DunTarget.Exit, out string err) == null, "no route"); + Check.True(err.Contains("can't tell which portal is the exit") && err.Contains("'Portal to the Hub'") && err.Contains("'Portal to the Depths'"), + "and it lists the portals known: " + err); + plain.Arrival = (d.Side, Ox + 43, Oy + 0, 0); + var c = DungeonRouteMaker.ExitCandidates(plain); + Check.Eq(c[0].Portal.Name, "Portal to the Depths", "came in by the side room: the portal there"); + Check.Eq(c[0].Why, "the portal nearest where you came in", "why"); + plain.Arrival = (d.West, Ox - 17.5, Oy + 25, 0); + Check.Eq(DungeonRouteMaker.ExitCandidates(plain).Count, 0, "came in 42 m and 66 m from them: neither within 40 m"); + + // The appraised destination says the landscape: that one, whatever the names. + var dest = d.World(portals: new[] { d.Surface("Exit Portal"), d.Depths("Portal to Holtburg") }); + dest.PortalDestination = id => id == DepthsId ? "42.1N, 33.6E" : null; + Check.Eq(DungeonRouteMaker.ExitCandidates(dest)[0].Portal.Name, "Portal to Holtburg", "a destination on the landscape beats a name"); + Check.True(DungeonRouteMaker.ExitCandidates(dest)[0].Why.Contains("42.1N, 33.6E"), "and says it"); + + // The only portal known; never a wrecked one. + var one = d.World(portals: new[] { d.Depths("Portal to the Hub") }); + Check.Eq(DungeonRouteMaker.ExitCandidates(one)[0].Why, "the only portal known here", "the only one"); + var wreck = d.World(portals: new[] { d.Depths("Destroyed Exit Portal") }); + Check.Eq(DungeonRouteMaker.ExitCandidates(wreck).Count, 0, "a destroyed portal is never the exit"); + } + + private static void ToPortalByName() + { + var d = new Sample(); + var w = d.World(); + var b = Build(w, new DunTarget(DunTargetKind.Portal, Portal: "depths")); + Check.Eq(b.Portal?.Name, "Portal to the Depths", "a name containing it"); + Check.Eq(b.Why, "its name has 'depths' in it", "why"); + Check.Eq(b.Route.Points[^1].Type, NavPointType.PortalNPC, "a Portal step at the end"); + Check.Eq(b.GoalCell, d.Side, "the side room"); + var last = b.Route.Points[^2]; + Check.True(LX(last) < 45 - d.Depths().Radius + 0.1 && LX(last) > 38, $"stops west of it, coming in by the doorway ({LX(last):F1}, {LY(last):F1})"); + Check.True(Nearest(b.Route.Points, 15, 52) >= d.Surface().Radius, "the other portal kept out of"); + + var exact = Build(w, new DunTarget(DunTargetKind.Portal, Portal: "SURFACE PORTAL")); + Check.Eq(exact.Portal?.Name, "Surface Portal", "an exact name, any case"); + Check.Eq(exact.Why, "", "nothing to explain"); + + var two = d.World(portals: new[] { d.Surface("Portal to the Depths"), d.Depths("Portal to the Depths") }); + var near = Build(two, new DunTarget(DunTargetKind.Portal, Portal: "Portal to the Depths")); + Check.Eq(near.Portal?.Id, DepthsId, "two of that name: the nearer (the side room's, 32 m against the nook's 37 m)"); + Check.True(near.Why.StartsWith("2 portals match"), near.Why); + + Check.True(DungeonRouteMaker.TryBuildRoute(w, new DunTarget(DunTargetKind.Portal, Portal: "Lifestone"), out string err) == null, "an unknown name"); + Check.True(err.Contains("no portal named 'Lifestone'") && err.Contains("'Surface Portal'"), "says so and lists the known: " + err); + } + + private static void ToPosition() + { + var d = new Sample(); + var w = d.World(); + var b = Build(w, new DunTarget(DunTargetKind.Position, X: -17.5, Y: 25, Z: 0)); + var end = b.Route.Points[^1]; + Check.Eq(end.Type, NavPointType.Point, "it ends on a waypoint"); + Check.Near(LX(end), -17.5, 1e-6, "on the spot (x)"); + Check.Near(LY(end), 25, 1e-6, "on the spot (y)"); + Check.Near(end.Z, 0, 1e-9, "its height"); + Check.Eq(b.GoalCell, d.West, "in the west room"); + // Through the west corridor on its centre line: some leg crosses x = -5 (the corridor's middle) at y 25. + var pts = b.Route.Points; + bool through = false; + for (int i = 0; i + 1 < pts.Count && !through; i++) + { + double ax = LX(pts[i]), bx = LX(pts[i + 1]); + if ((ax - -5) * (bx - -5) > 0 || Math.Abs(bx - ax) < 1e-9) continue; + double y = LY(pts[i]) + (LY(pts[i + 1]) - LY(pts[i])) * (-5 - ax) / (bx - ax); + through = Math.Abs(y - 25) < 0.5; + } + Check.True(through, "through the west corridor, on its centre line: " + Pts(pts)); + Check.True(b.TargetText.Contains("(-17.5, 25, 0)"), b.TargetText); + + Check.True(DungeonRouteMaker.TryBuildRoute(w, new DunTarget(DunTargetKind.Position, X: 500, Y: 500, Z: 0), out string err) == null, "a spot far outside"); + Check.True(err.Contains("isn't inside this dungeon"), err); + + // Its own cell: the straight walk. + var here = Build(w, new DunTarget(DunTargetKind.Position, X: 18, Y: 12, Z: 0)); + Check.Eq(here.Route.Points.Count, 2, "the character's spot and the target: " + Pts(here.Route.Points)); + } + + private static void ToRoomAndFar() + { + var d = new Sample(); + var w = d.World(); + var rooms = DungeonPathfinder.BuildRooms(d.Graph, w.Geo!); + Check.Eq(rooms.Cells[rooms.RoomOf[d.Start]].Count, 9, "the hall is one room of 9 cells"); + int side = rooms.RoomOf[d.Side]; + var b = Build(w, new DunTarget(DunTargetKind.Room, Room: side)); + Check.Eq(b.Room, side, "the room asked for"); + Check.Eq(b.GoalCell, d.Side, "its cell"); + // The side room's middle is the Depths portal: the route ends just outside its reach. + var end = b.Route.Points[^1]; + double dd = Math.Sqrt((LX(end) - 45) * (LX(end) - 45) + (LY(end) - 5) * (LY(end) - 5)); + Check.True(dd >= d.Depths().Radius - 0.05, $"the middle is in the portal's reach: the end moved out ({dd:F2} m)"); + Check.True(b.LeftOut.Any(l => l.Contains("kept out of portal 'Portal to the Depths'")), "and it says so: " + string.Join(" | ", b.LeftOut)); + Check.True(DungeonRouteMaker.TryBuildRoute(w, new DunTarget(DunTargetKind.Room, Room: rooms.Cells.Count), out string err) == null, "a room past the last"); + Check.True(err.Contains($"rooms are 0 to {rooms.Cells.Count - 1}"), err); + var noMap = d.World(geo: false); + Check.True(DungeonRouteMaker.TryBuildRoute(noMap, new DunTarget(DunTargetKind.Room, Room: 0), out err) == null && err.Contains("isn't loaded yet"), "rooms need the map: " + err); + + uint far = DungeonRouteMaker.FarthestCell(d.Graph, d.Start, null, out double yd); + Check.Eq(far, d.West, $"the west room is the farthest on foot ({yd:F1} yd)"); + Check.Near(yd, 42.5, 0.01, "10 + 10 + 10 + 12.5"); + var f = Build(w, DunTarget.Far); + Check.Eq(f.GoalCell, d.West, "far: the west room"); + Check.True(f.TargetText.Contains("farthest spot on foot"), f.TargetText); + Check.Eq(DungeonRouteMaker.FarthestCell(d.Graph, d.Start, new HashSet { d.W1 }, out _), d.Side, "with the west corridor lava: the side room"); + } + + private static void Refusals() + { + var d = new Sample(); + var w = d.World(); + w.Hazards = new HashSet { d.C1 }; + Check.True(DungeonRouteMaker.TryBuildRoute(w, DunTarget.Exit, out string err) == null, "the only corridor to the exit is lava"); + Check.True(err.Contains("through lava/acid cells"), err); + w.Hazards = new HashSet { d.Nook }; + var into = Build(w, DunTarget.Exit); + Check.Eq(into.GoalCell, d.Nook, "the goal itself may be one (the player asked to go there)"); + Check.True(into.LeftOut.Any(l => l.Contains("1 lava/acid cell kept out of")), string.Join(" | ", into.LeftOut)); + + // A pit 10 m below the second corridor: reached only by a drop. + uint pit = d.Cell(12.35, 42, 17.65, 48, -10); + d.Graph[d.C2].Neighbors.Add(pit); + d.Graph[pit].Neighbors.Add(d.C2); + var dw = d.World(); + Check.True(DungeonRouteMaker.TryBuildRoute(dw, new DunTarget(DunTargetKind.Position, X: 15, Y: 45, Z: -10), out err) == null, "the pit"); + Check.True(err.Contains("only reached by a drop"), err); + + var none = d.World(portals: Array.Empty()); + none.Portals.Clear(); + Check.True(DungeonRouteMaker.TryBuildRoute(none, DunTarget.Exit, out err) == null && err.Contains("no portal is known in this dungeon yet"), err); + Check.True(DungeonRouteMaker.TryBuildRoute(none, new DunTarget(DunTargetKind.Portal, Portal: "x"), out err) == null && err.Contains("knows no portal"), err); + + // Without the map geometry: the cell walk, said so. + var noMap = Build(d.World(geo: false), DunTarget.Exit); + Check.True(noMap.Notes.Any(n => n.Contains("dungeon map isn't loaded yet")), "said: " + string.Join(" | ", noMap.Notes)); + Check.Eq(noMap.Route.Points[^1].Type, NavPointType.PortalNPC, "still a Portal step at the end"); + Check.True(Nearest(noMap.Route.Points, 15, 52) >= d.Surface().Radius - 0.05, "and still stops at the circle"); + + var explored = d.World(); + explored.Explored = 0.35; + var e = Build(explored, DunTarget.Far); + Check.True(e.Notes.Any(n => n.Contains("35% of this dungeon's floor explored")), "the explored share, when known: " + string.Join(" | ", e.Notes)); + } + + private static void BentRoundAnotherPortal() + { + // The character east of the Depths portal in the side room; the exit is west through its doorway, so + // the straight walk to the doorway goes through the portal. + var d = new Sample(); + var w = d.World(49, 5, d.Side); + var b = Build(w, DunTarget.Exit); + double r = d.Depths().Radius; + Check.True(Nearest(b.Route.Points, 45, 5) >= r - 0.05, $"bent round the Depths portal ({Nearest(b.Route.Points, 45, 5):F2} m): {Pts(b.Route.Points)}"); + Check.True(b.LeftOut.Any(l => l.Contains("kept out of portal 'Portal to the Depths'")), "said: " + string.Join(" | ", b.LeftOut)); + Check.Eq(b.Route.Points[^1].TargetName, "Surface Portal", "and on to the exit"); + } + + // ── Files ──────────────────────────────────────────────────────────────── + + private static string Fresh(string sub) + { + string dir = Path.Combine(Program.TempRoot, sub); + if (Directory.Exists(dir)) Directory.Delete(dir, true); + Directory.CreateDirectory(dir); + DungeonRouteMaker.Folder = dir; + return dir; + } + + private static void SavedRouteRuns() + { + string dir = Fresh("NavProfiles-run"); + var d = new Sample(); + var w = d.World(); + var exit = Build(w, DunTarget.Exit); + Check.True(DungeonRouteMaker.TrySave("Hive exit", exit.Route, false, Lb, out string path, out bool overwrote, out string err), "saved: " + err); + Check.Eq(path, Path.Combine(dir, "Hive exit.nav"), "NavProfiles\\.nav"); + Check.False(overwrote, "a new file"); + var lines = File.ReadAllLines(path); + Check.Eq(lines[0], "uTank2 NAV 1.2", "VTank's header"); + Check.Eq(lines[1], "4", "route type Once (4)"); + Check.Eq(lines[2], exit.Route.Points.Count.ToString(), "the point count"); + + var back = NavRouteParser.Load(path); + Check.True(back.LoadWarning == null, "no load warning"); + Check.Eq(back.RouteType, NavRouteType.Once, "read back: Once"); + Check.Eq(back.Points.Count, exit.Route.Points.Count, "the same points"); + for (int i = 0; i < back.Points.Count; i++) + { + var a = exit.Route.Points[i]; var b = back.Points[i]; + Check.True(a.Type == b.Type && a.NS == b.NS && a.EW == b.EW && a.Z == b.Z, $"point {i} exactly as laid ({a} / {b})"); + } + Check.Eq(back.Points[^1].TargetName, "Surface Portal", "the Portal step's name"); + Check.True(back.Points[^1].IsTie, "tied to the portal's spot"); + + // Every point is in this dungeon, as NavigationEngine's area hold judges it. + foreach (var p in back.Points) + { + var a = NavRecoveryPlanner.ClassifyArea(d.Start, p.NS, p.EW, lb => lb == Lb, + (lb, ns, ew) => d.Graph.Values.Any(n => Math.Sqrt((n.NS - ns) * (n.NS - ns) + (n.EW - ew) * (n.EW - ew)) * 240 <= 60), out _, out _); + Check.Eq(a, NavAreaCheck.Match, $"({LX(p):F1}, {LY(p):F1}) is in this dungeon for the engine"); + } + + // The spot route, run by NavigationEngine with a character walked onto each point: it gets to the end. + var spot = Build(w, new DunTarget(DunTargetKind.Position, X: -17.5, Y: 25, Z: 0)); + Check.True(DungeonRouteMaker.TrySave("To the west room", spot.Route, false, Lb, out string spotPath, out _, out err), "saved: " + err); + var route = NavRouteParser.Load(spotPath); + FakeHost.Reset(); + long now = 1_000_000; + NavigationEngine.Clock = () => now; + try + { + FakeHost.PlayerPose = (d.Start, 15f, 15f, 0f); + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, EnableNavigation = true, CurrentRoute = route, ActiveNavIndex = 0 }; + Check.True(NavRouteParser.StartsAtFirstPoint(route.RouteType, s.NavResumeNearest), "a Once route starts at [0], the character's spot"); + var e = new NavigationEngine(host, s); + for (int i = 0; i < route.Points.Count && s.EnableNavigation; i++) + { + var p = route.Points[i]; + FakeHost.PlayerPose = (d.Start, (float)LX(p), (float)LY(p), (float)(p.Z * 240.0)); + for (int k = 0; k < 3 && s.EnableNavigation && s.ActiveNavIndex <= i; k++) { now += 100; e.Tick(); } + Check.True(s.ActiveNavIndex > i || !s.EnableNavigation, $"at point {i} ({LX(p):F1}, {LY(p):F1}) it moves on (index {s.ActiveNavIndex})"); + } + Check.False(s.EnableNavigation, "the end of the Once route turns navigation off: it got there"); + Check.Eq(s.ActiveNavIndex, route.Points.Count, "the index is past the end"); + } + finally { NavigationEngine.Clock = () => Environment.TickCount64; } + } + + private static void Info() + { + string dir = Fresh("NavProfiles-info"); + var d = new Sample(); + var w = d.World(); + var exit = Build(w, DunTarget.Exit); + DungeonRouteMaker.TrySave("Hive exit", exit.Route, false, Lb, out string path, out _, out _); + var route = NavRouteParser.Load(path); + Dictionary? GraphOf(uint lb) => lb == Lb ? d.Graph : null; + bool? IsDungeon(uint lb) => lb == Lb; + + var info = DungeonRouteMaker.DescribeRoute("Hive exit", path, route, d.Start, GraphOf, IsDungeon); + Check.Eq(info.Type, NavRouteType.Once, "type"); + Check.Eq(info.Points, route.Points.Count, "points"); + Check.Eq(info.Waypoints, route.Points.Count - 1, "all but the Portal step are walked"); + Check.Eq(info.Steps["portal"], 1, "one Portal step"); + Check.Near(info.Yards, exit.Yards, 1e-6, "its length"); + Check.Eq(info.Landblock, Lb, "landblock 7E7E"); + Check.Eq(info.Dungeon, true, "a dungeon"); + Check.Eq(info.ForThisDungeon, "yes", "made for this dungeon"); + Check.Eq(info.PointsHere, info.Waypoints, "every point here"); + Check.True(info.Cells >= 2, $"the cells under its points ({info.Cells})"); + Check.Eq(info.StartCell, d.Start, "starts in the hall's middle"); + Check.Eq(info.EndCell, d.C2, "ends in the corridor before the nook: the walk stops at the portal's reach"); + var json = JsonDocument.Parse(DungeonRouteMaker.InfoJson(info)).RootElement; + Check.Eq(json.GetProperty("forThisDungeon").GetString(), "yes", "JSON: forThisDungeon"); + Check.Eq(json.GetProperty("landblock").GetString(), "7E7E", "JSON: landblock hex"); + Check.Eq(json.GetProperty("steps").GetProperty("portal").GetInt32(), 1, "JSON: steps.portal"); + Check.Eq(json.GetProperty("startCell").GetString(), d.Start.ToString("X8"), "JSON: startCell"); + + // In another dungeon (landblock 7E7F, its own cells): not this one's. + var elsewhere = DungeonRouteMaker.DescribeRoute("Hive exit", path, route, 0x7E7F0105, lb => lb == 0x7E7F ? new Dictionary + { + [0x7E7F0105] = new() { CellId = 0x7E7F0105, EW = DungeonGeometry.WorldToNav(Ox + 50), NS = DungeonGeometry.WorldToNav(Oy + 192 + 100) }, + } : GraphOf(lb), lb => lb is Lb or 0x7E7F); + Check.Eq(elsewhere.ForThisDungeon, "no", "from another dungeon: no"); + Check.Eq(elsewhere.Landblock, Lb, "and it says where it was made"); + Check.True(elsewhere.Notes.Any(n => n.Contains("made in landblock 7E7E; you are in 7E7F")), string.Join(" | ", elsewhere.Notes)); + + // On the landscape: can't tell. + var outside = DungeonRouteMaker.DescribeRoute("Hive exit", path, route, 0xA9B40021, GraphOf, IsDungeon); + Check.Eq(outside.ForThisDungeon, "unknown", "not in a dungeon: unknown"); + Check.Eq(outside.Cells, info.Cells, "its own landblock still described"); + + // Points outside their dungeon's own 192 m square (the west room is in 7D7E's square, as Tiny Hive's + // cells are in 0288's): the dungeon is the one whose cells they are by, not the square they fall in. + var west = Build(w, new DunTarget(DunTargetKind.Position, X: -17.5, Y: 25, Z: 0)); + DungeonRouteMaker.TrySave("West", west.Route, false, Lb, out string westPath, out _, out _); + var westInfo = DungeonRouteMaker.DescribeRoute("West", westPath, NavRouteParser.Load(westPath), 0xA9B40021, GraphOf, IsDungeon); + Check.True(westInfo.Landblocks.Contains(0x7D7E), "some of its points fall in 7D7E's square: " + string.Join(",", westInfo.Landblocks.Select(l => l.ToString("X4")))); + Check.Eq(westInfo.Landblock, Lb, "but it is 7E7E's route"); + Check.Eq(westInfo.Dungeon, true, "a dungeon"); + Check.True(westInfo.Cells >= 2 && westInfo.EndCell == d.West, $"its cells found ({westInfo.Cells}, ending in {westInfo.EndCell:X8})"); + + // A patrol-shaped (Circular) file: the closing leg counts. + var loop = new NavRouteParser { RouteType = NavRouteType.Circular }; + loop.Points.Add(DungeonRouteMaker.WorldPt(Ox + 5, Oy + 5, 0)); + loop.Points.Add(DungeonRouteMaker.WorldPt(Ox + 25, Oy + 5, 0)); + loop.Points.Add(DungeonRouteMaker.WorldPt(Ox + 25, Oy + 25, 0)); + Check.Near(DungeonRouteMaker.RouteYards(loop), 20 + 20 + Math.Sqrt(800), 1e-6, "a lap: 20 + 20 + the way back"); + } + + private static void NameRules() + { + string dir = Fresh("NavProfiles-names"); + Check.True(DunRouteRequest.TryName("Hive exit", out string n, out _) && n == "Hive exit", "a plain name"); + Check.True(DunRouteRequest.TryName(" \"Hive exit.nav\" ", out n, out _) && n == "Hive exit", "quotes, spaces and .nav dropped: " + n); + foreach (string bad in new[] { "", " ", "a/b", "a\\b", "..", "x..y", "a:b", "a*b", "a?b", "a 20 ? bad[..20] + "..." : bad)}' refused ({why})"); + Check.True(why.Contains("can't be a route name"), "with the reason: " + why); + } + Check.True(DunRouteRequest.TryName(new string('x', 120), out _, out _), "120 characters is fine"); + + var route = new NavRouteParser { RouteType = NavRouteType.Once }; + route.Points.Add(DungeonRouteMaker.WorldPt(Ox + 5, Oy + 5, 0)); + Check.True(DungeonRouteMaker.TrySave("Mine", route, false, Lb, out string path, out bool ow, out string err), "first save: " + err); + Check.False(ow, "nothing replaced"); + string before = File.ReadAllText(path); + route.Points.Add(DungeonRouteMaker.WorldPt(Ox + 6, Oy + 6, 0)); + Check.False(DungeonRouteMaker.TrySave("Mine", route, false, Lb, out _, out ow, out err), "again without overwrite: refused"); + Check.True(err.Contains("already in NavProfiles") && err.Contains("overwrite"), err); + Check.Eq(File.ReadAllText(path), before, "the file is untouched"); + Check.True(DungeonRouteMaker.TrySave("mine.nav", route, true, Lb, out string p2, out ow, out err), "with overwrite: " + err); + Check.True(ow, "it says it replaced one"); + Check.Eq(NavRouteParser.Load(p2).Points.Count, 2, "the new route is in it"); + Check.False(DungeonRouteMaker.TrySave("../escape", route, true, Lb, out _, out _, out err), "no folders, overwrite or not"); + Check.False(File.Exists(Path.Combine(dir, "..", "escape.nav")), "nothing written outside NavProfiles"); + } + + private static void CommandWords() + { + static DunRouteRequest? P(string words, out string error) + => RynthAiPlugin.TryParseDunRouteWords(words.Split(' ', StringSplitOptions.RemoveEmptyEntries), out var r, out error) ? r : null; + var r = P("Hive exit to exit", out string e); + Check.True(r != null && r.Name == "Hive exit" && r.To == DunTarget.Exit && !r.Overwrite, "name, to exit: " + e); + r = P("Way to the Hub to exit overwrite", out e); + Check.True(r != null && r.Name == "Way to the Hub" && r.To!.Kind == DunTargetKind.Exit && r.Overwrite, "a name holding 'to', and overwrite: " + e); + r = P("X to portal Portal to the Depths", out e); + Check.True(r != null && r.Name == "X" && r.To!.Kind == DunTargetKind.Portal && r.To.Portal == "Portal to the Depths", "a portal name holding 'to': " + e); + r = P("Spot to 110.5 -3.25 -24", out e); + Check.True(r != null && r.To!.Kind == DunTargetKind.Position && r.To.X == 110.5 && r.To.Y == -3.25 && r.To.Z == -24, "a spot: " + e); + r = P("Spot to [110.5, -3.25, -24]", out e); + Check.True(r != null && r.To!.Kind == DunTargetKind.Position && r.To.Z == -24, "a spot in brackets with commas: " + e); + r = P("R to room 3", out e); + Check.True(r != null && r.To!.Kind == DunTargetKind.Room && r.To.Room == 3, "a room: " + e); + r = P("F to FAR", out e); + Check.True(r != null && r.To == DunTarget.Far, "far, any case: " + e); + Check.Null(P("Spot to 1 2", out e), "two numbers"); + Check.True(e.Contains("three numbers"), e); + Check.Null(P("R to room -1", out e), "a negative room"); + Check.Null(P("X to portal", out e), "portal with no name"); + Check.True(e.Contains("needs the portal's name"), e); + Check.Null(P("X to the moon", out e), "an unknown target"); + Check.True(e.Contains("isn't a target"), e); + Check.Null(P("No target here", out e), "no 'to'"); + Check.True(e.Contains("no \"to\""), e); + Check.Null(P("a/b to exit", out e), "a bad name"); + Check.True(e.Contains("can't be a route name"), e); + } + + // ── The interface ──────────────────────────────────────────────────────── + + private static void JsonRequests() + { + static DunRouteRequest? Ok(string json) + { + bool ok = DunRouteRequest.TryParseJson(json, out var r, out string e); + Check.True(ok, $"{json} accepted ({e})"); + return ok ? r : null; + } + var a = Ok("{\"op\":\"dunroute\",\"name\":\"Hive exit\",\"to\":\"exit\"}"); + Check.True(a!.Op == DunRouteOp.DunRoute && a.Name == "Hive exit" && a.To == DunTarget.Exit && !a.Overwrite, "dunroute to exit"); + a = Ok("{\"op\":\"dunroute\",\"name\":\"D\",\"to\":{\"portal\":\"Portal to the Depths\"},\"overwrite\":true}"); + Check.True(a!.To!.Kind == DunTargetKind.Portal && a.To.Portal == "Portal to the Depths" && a.Overwrite, "to a portal, overwrite"); + a = Ok("{\"op\":\"dunroute\",\"name\":\"S\",\"to\":{\"x\":110.5,\"y\":-3.25,\"z\":-24}}"); + Check.True(a!.To!.Kind == DunTargetKind.Position && a.To.X == 110.5 && a.To.Y == -3.25 && a.To.Z == -24, "to a spot"); + a = Ok("{\"op\":\"dunroute\",\"name\":\"F\",\"to\":\"far\"}"); + Check.True(a!.To == DunTarget.Far, "far"); + a = Ok("{\"op\":\"dunroute\",\"name\":\"R\",\"to\":{\"room\":12}}"); + Check.True(a!.To!.Kind == DunTargetKind.Room && a.To.Room == 12, "a room"); + a = Ok("{\"op\":\"dunpatrol\",\"name\":\"Hive patrol.nav\"}"); + Check.True(a!.Op == DunRouteOp.DunPatrol && a.Name == "Hive patrol", "dunpatrol (.nav dropped)"); + a = Ok("{\"op\":\"info\",\"name\":\"Hive patrol\"}"); + Check.True(a!.Op == DunRouteOp.Info, "info"); + a = Ok(" {\"op\":\"where\"} "); + Check.True(a!.Op == DunRouteOp.Where, "where"); + + (string Json, string Says)[] bad = + { + ("", "no request"), + ("not json", "not JSON"), + ("[1,2]", "must be a JSON object"), + ("\"where\"", "must be a JSON object"), + ("{}", "\"op\" is missing"), + ("{\"op\":3}", "\"op\" must be a string"), + ("{\"op\":\"teleport\"}", "must be dunroute, dunpatrol, info or where"), + ("{\"op\":\"where\",\"name\":\"x\"}", "isn't a field of where"), + ("{\"op\":\"where\",\"op\":\"info\"}", "given twice"), + ("{\"op\":\"dunroute\",\"to\":\"exit\"}", "\"name\" is missing"), + ("{\"op\":\"dunroute\",\"name\":5,\"to\":\"exit\"}", "\"name\" must be a string"), + ("{\"op\":\"dunroute\",\"name\":\"a/b\",\"to\":\"exit\"}", "can't be a route name"), + ("{\"op\":\"dunroute\",\"name\":\"CON\",\"to\":\"exit\"}", "Windows reserves"), + ("{\"op\":\"dunroute\",\"name\":\"x\"}", "\"to\" is missing"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":\"moon\"}", "\"to\" must be"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":5}", "\"to\" must be"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{}}", "\"to\" is one of"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{\"portal\":\"\"}}", "the portal's name"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{\"portal\":\"a\",\"room\":1}}", "\"to\" is one of"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{\"x\":1,\"y\":2}}", "\"z\" is missing"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{\"x\":1,\"y\":\"2\",\"z\":3}}", "\"y\" must be a number"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{\"x\":1,\"y\":2,\"z\":1e9}}", "landblock-local metres"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{\"room\":-1}}", "a room number, 0 or more"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{\"room\":1.5}}", "a room number"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":{\"house\":1}}", "doesn't take \"house\""), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":\"exit\",\"overwrite\":\"yes\"}", "\"overwrite\" must be true or false"), + ("{\"op\":\"dunroute\",\"name\":\"x\",\"to\":\"exit\",\"overwite\":true}", "isn't a field of dunroute"), + ("{\"op\":\"info\",\"name\":\"x\",\"overwrite\":true}", "isn't a field of info"), + ("{\"op\":\"dunpatrol\",\"name\":\"x\",\"to\":\"exit\"}", "isn't a field of dunpatrol"), + ("{\"op\":\"where\"", "not JSON"), + ("{\"op\":\"where\",\"x\":" + new string('[', 20) + new string(']', 20) + "}", "not JSON"), + ("{\"op\":\"where\",\"pad\":\"" + new string('x', 9000) + "\"}", "longer than 8192 bytes"), + }; + foreach (var (json, says) in bad) + { + Check.False(DunRouteRequest.TryParseJson(json, out _, out string e), $"refused: {(json.Length > 60 ? json[..60] + "..." : json)}"); + Check.True(e.Contains(says), $" says \"{says}\": {e}"); + } + } + + private static void JobStates() + { + var jobs = new DunRouteJobs(); + long now = 1000; + jobs.Clock = () => now; + var where = new DunRouteRequest { Op = DunRouteOp.Where }; + uint id = jobs.Add(where, out string err); + Check.Eq(id, 1u, "the first id is 1: " + err); + Check.True(jobs.TryPoll(id, out string json), "known"); + var j = JsonDocument.Parse(json).RootElement; + Check.Eq(j.GetProperty("state").GetString(), "queued", "queued"); + Check.Eq(j.GetProperty("op").GetString(), "where", "its op"); + Check.Eq(j.GetProperty("result").ValueKind, JsonValueKind.Null, "no result yet"); + + var job = jobs.Next()!; + Check.Eq(job.Id, id, "the next job to work"); + jobs.Working(job, "waiting: you're in portal space"); + jobs.TryPoll(id, out json); + j = JsonDocument.Parse(json).RootElement; + Check.Eq(j.GetProperty("state").GetString(), "working", "working"); + Check.Eq(j.GetProperty("detail").GetString(), "waiting: you're in portal space", "detail says what it waits for"); + Check.False(jobs.WaitedTooLong(job), "not yet too long"); + now += DunRouteJobs.WaitLimitMs + 1; + Check.True(jobs.WaitedTooLong(job), "30 s on: too long"); + jobs.Finish(job, true, "in dungeon 7E7E", "{\"inDungeon\":true}"); + jobs.TryPoll(id, out json); + j = JsonDocument.Parse(json).RootElement; + Check.Eq(j.GetProperty("state").GetString(), "done", "done"); + Check.True(j.GetProperty("result").GetProperty("inDungeon").GetBoolean(), "the result is the op's JSON object"); + Check.True(jobs.Next() == null, "nothing left to work"); + + uint f = jobs.Add(where, out _); + jobs.Finish(jobs.Next()!, false, "Cannot get player position.", "{\"ignored\":1}"); + jobs.TryPoll(f, out json); + j = JsonDocument.Parse(json).RootElement; + Check.Eq(j.GetProperty("state").GetString(), "failed", "failed"); + Check.Eq(j.GetProperty("detail").GetString(), "Cannot get player position.", "with the reason"); + Check.Eq(j.GetProperty("result").ValueKind, JsonValueKind.Null, "and no result"); + + Check.False(jobs.TryPoll(999, out json), "an id never given"); + j = JsonDocument.Parse(json).RootElement; + Check.Eq(j.GetProperty("state").GetString(), "unknown", "state unknown"); + Check.True(j.GetProperty("detail").GetString()!.Contains("only the last 32 are kept"), "says why"); + Check.False(jobs.TryPoll(0, out _), "0 is never a job"); + + // 32 kept: the 33rd drops the oldest finished one. + for (int i = 0; i < 30; i++) jobs.Add(where, out _); + Check.Eq(jobs.Count, 32, "32 kept"); + uint next = jobs.Add(where, out err); + Check.Eq(next, 33u, "the 33rd: " + err); + Check.Eq(jobs.Count, 32, "still 32"); + Check.False(jobs.TryPoll(1, out _), "the oldest finished one (1) was dropped"); + Check.True(jobs.TryPoll(f, out _), "the next finished one (2) is still there"); + uint again = jobs.Add(where, out _); + Check.False(jobs.TryPoll(f, out _), "then it goes too"); + Check.Eq(again, 34u, "ids keep counting up, never reused"); + // All 32 unfinished: refused. + Check.Eq(jobs.Add(where, out err), 0u, "every kept job unfinished: refused"); + Check.True(err.Contains("32 jobs are still unfinished"), err); + // Work is in order: the oldest unfinished first. + Check.Eq(jobs.Next()!.Id, 3u, "the oldest unfinished is worked first"); + + Check.Eq(JsonDocument.Parse(DunRouteJobs.QueuedJson(7)).RootElement.GetProperty("state").GetString(), "queued", "Request's answer: queued"); + Check.Eq(JsonDocument.Parse(DunRouteJobs.ErrorJson("bad \"x\"")).RootElement.GetProperty("error").GetString(), "bad \"x\"", "Request's error, escaped"); + } + + private static unsafe void RoutesTable() + { + try + { + Check.True(RoutesInterface.Query(RynthAiYieldApiV1.InterfaceName, 1) == IntPtr.Zero, "another interface's name"); + Check.True(RoutesInterface.Query(RynthAiRoutesApiV1.InterfaceName, 0) == IntPtr.Zero, "version 0"); + Check.True(RoutesInterface.Query(RynthAiRoutesApiV1.InterfaceName, 2) == IntPtr.Zero, "a newer version than RynthAi has"); + IntPtr p = RoutesInterface.Query(RynthAiRoutesApiV1.InterfaceName, 1); + Check.True(p != IntPtr.Zero, "v1 answers"); + var t = (RynthAiRoutesApiV1*)p; + Check.Eq(t->Version, 1u, "table version"); + Check.Eq(t->StructSize, (uint)sizeof(RynthAiRoutesApiV1), "table size"); + Check.True(t->Request != null && t->Poll != null, "functions filled in"); + Check.True(RoutesInterface.Query(RynthAiRoutesApiV1.InterfaceName, 1) == p, "the same table on every call"); + byte[] req = System.Text.Encoding.UTF8.GetBytes("{\"op\":\"where\"}\0"); + byte* answer = null; + uint id; + fixed (byte* r = req) id = t->Request(r, &answer); + Check.Eq(id, 0u, "no plugin instance: refused"); + string text = System.Runtime.InteropServices.Marshal.PtrToStringUTF8((IntPtr)answer) ?? ""; + Check.True(text.Contains("\"error\""), "with an error (no plugin instance, or none logged in): " + text); + byte* json = null; + Check.Eq(t->Poll(5, &json), 0, "Poll: no such job"); + Check.True((System.Runtime.InteropServices.Marshal.PtrToStringUTF8((IntPtr)json) ?? "").Contains("\"unknown\""), "state unknown"); + } + finally + { + RoutesInterface.Release(); + } + } + + // ── The plugin ─────────────────────────────────────────────────────────── + + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + private const uint Player = 0x50000E01; + + private sealed class Rig + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new(); + public readonly Sample D = new(); + public readonly DungeonGeometry Geo; + public readonly WorldObjectCache Cache; + + public Rig(string folder, string world = "", double lx = 15, double ly = 15, bool namedExit = true) + { + FakeHost.Reset(); + ServerPolicy.Forget(); + Fresh(folder); + Geo = D.Geo(); + FakeHost.WorldName = world; + FakeHost.Names[Player] = "Tester"; + At(lx, ly, D.Start); + FakeHost.Names[SurfaceId] = namedExit ? "Surface Portal" : "Portal to the Hub"; + FakeHost.ItemTypes[SurfaceId] = 0x00010000; + FakeHost.Positions[SurfaceId] = (D.Nook, 15f, 52f, 0f); + FakeHost.Names[DepthsId] = "Portal to the Depths"; + FakeHost.ItemTypes[DepthsId] = 0x00010000; + FakeHost.Positions[DepthsId] = (D.Side, 45f, 5f, 0f); + var host = FakeHost.Create(Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); // a stand-in with its profile in memory + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Cache = new WorldObjectCache(host); + Cache.SetPlayerId(Player); + foreach (uint id in new[] { SurfaceId, DepthsId }) Cache.OnCreateObject(id); + Cache.Tick(); + Set("_objectCache", Cache); + Set("_playerId", Player); + Set("_initialized", true); + Set("_loginComplete", true); + P.DungeonMapOverride = lb => lb == Lb ? (D.Graph, Geo) : null; + S.DunPatrolCoverage = (int)PatrolCoverage.Everything; + } + + public void At(double lx, double ly, uint cell) => FakeHost.PlayerPose = (cell, (float)lx, (float)ly, 0f); + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P); + public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + public void Tick() => Call("TickDunRoutes"); + + /// A line typed in the chat bar; the chat lines it wrote. + public List Typed(string line) + { + int before = FakeHost.Chat.Count; + int eat = 0; + P.OnChatBarEnter(line, ref eat); + Check.Eq(eat, 1, $"'{line}' is RynthAi's"); + return FakeHost.Chat.Skip(before).ToList(); + } + + public (uint Id, string Error) Request(string json) + { + uint id = P.RouteRequest(json, out string error); + return (id, error); + } + + public JsonElement Poll(uint id) + { + P.RouteJobs.TryPoll(id, out string json); + return JsonDocument.Parse(json).RootElement.Clone(); + } + } + + private static string Show(List lines) => lines.Count == 0 ? "(nothing)" : string.Join(" | ", lines); + + private static void PluginDunRoute() + { + var rig = new Rig("NavProfiles-cmd"); + var said = rig.Typed("/ra dunroute Hive exit to exit"); + Check.True(said.Count >= 1 && said[0].StartsWith("[RynthAi] DunRoute: saved Hive exit.nav:"), "it answers: " + Show(said)); + Check.True(said[0].Contains("the exit portal 'Surface Portal' (named like an exit)") && said[0].Contains("/ra nav load Hive exit"), "where to and how to run it"); + Check.True(said.Any(l => l.Contains("note:") && l.Contains("2 portals known")), "and what isn't known: " + Show(said)); + string file = Path.Combine(DungeonRouteMaker.Folder, "Hive exit.nav"); + Check.True(File.Exists(file), "the file is in NavProfiles"); + var route = NavRouteParser.Load(file); + Check.Eq(route.RouteType, NavRouteType.Once, "a Once route"); + Check.Eq(route.Points[^1].Type, NavPointType.PortalNPC, "ending at the portal"); + Check.True(rig.S.CurrentRoute.Points.Count == 0 && !rig.S.EnableNavigation, "nothing loaded or started"); + + said = rig.Typed("/ra dunroute Hive exit to far"); + Check.True(said.Count == 1 && said[0].Contains("already in NavProfiles: add overwrite"), "again without overwrite: refused: " + Show(said)); + Check.Eq(NavRouteParser.Load(file).Points[^1].Type, NavPointType.PortalNPC, "the file is untouched"); + said = rig.Typed("/ra dunroute Hive exit to far overwrite"); + Check.True(said[0].Contains("replaced Hive exit.nav") && said[0].Contains("farthest spot on foot"), "with overwrite: replaced: " + Show(said)); + Check.Eq(NavRouteParser.Load(file).Points[^1].Type, NavPointType.Point, "the new route is in it"); + + said = rig.Typed("/ra dunroute Way to the west to -17.5 25 0"); + Check.True(said[0].Contains("saved Way to the west.nav") && said[0].Contains("(-17.5, 25, 0)"), "a name holding 'to': " + Show(said)); + said = rig.Typed("/ra dunroute D to portal depths"); + Check.True(said[0].Contains("portal 'Portal to the Depths'"), "to a portal by name: " + Show(said)); + + said = rig.Typed("/ra dunroute info Hive exit"); + Check.True(said[0].Contains("Hive exit.nav: once") && said[0].Contains("landblock 7E7E (a dungeon)") && said[0].Contains("made for this dungeon: yes"), + "info: " + Show(said)); + said = rig.Typed("/ra dunroute info Nothing Here"); + Check.True(said.Count == 1 && said[0].Contains("no route named 'Nothing Here'"), "info on a missing file: " + Show(said)); + said = rig.Typed("/ra dunroute"); + Check.True(said.Count >= 1 && said[0].Contains("Usage: /ra dunroute"), "bare: the usage"); + said = rig.Typed("/ra dunroute X to the moon"); + Check.True(said.Count == 1 && said[0].Contains("isn't a target") && said[0].Contains("Usage"), "a wrong target: why and the usage: " + Show(said)); + Check.Eq(FakeHost.ChatTypes[^1], CommandReply.FailColor, "in the failure colour"); + + rig.At(42.1, 33.6, 0xA9B4002Fu); + said = rig.Typed("/ra dunroute Out to exit"); + Check.True(said.Count == 1 && said[0].Contains("dunroute requires you to be inside a dungeon"), "outdoors: " + Show(said)); + } + + private static void PluginPatrolSave() + { + var rig = new Rig("NavProfiles-patrol"); + var said = rig.Typed("/ra dunpatrol-save Hive patrol"); + Check.True(said.Count >= 1 && said[0].StartsWith("[RynthAi] DunPatrol-Save: saved Hive patrol.nav: the circular patrol dunnav-patrol walks from here"), + "it answers: " + Show(said)); + Check.True(said[0].Contains("coverage everything"), "with the settings it was laid with"); + string file = Path.Combine(DungeonRouteMaker.Folder, "Hive patrol.nav"); + var lines = File.ReadAllLines(file); + Check.Eq(lines[0], "uTank2 NAV 1.2", "VTank's header"); + Check.Eq(lines[1], "1", "route type Circular (1)"); + var saved = NavRouteParser.Load(file); + Check.True(saved.LoadWarning == null, "RynthAi's parser reads it without a warning"); + Check.Eq(saved.RouteType, NavRouteType.Circular, "Circular"); + Check.True(saved.Points.Count >= 8 && saved.Points.All(p => p.Type == NavPointType.Point), $"a lap of waypoints ({saved.Points.Count})"); + Check.True(saved.Points.All(p => Nearest(new List { p }, 15, 52) >= DungeonPathfinder.PortalKeepOutDefault - 0.05), "every point out of the Surface Portal's reach"); + Check.True(rig.S.CurrentRoute.Points.Count == 0 && !rig.S.EnableNavigation && !rig.S.IsMacroRunning, "nothing loaded or started"); + + // The same lap /ra dunnav-patrol installs (in its order, from where it starts; its lead-in aside). + rig.P.HandleDungeonNavPatrol(); + var installed = rig.S.CurrentRoute; + Check.Eq(installed.RouteType, NavRouteType.Circular, "dunnav-patrol installed a patrol"); + int start = rig.S.ActiveNavIndex; + var walked = new List(); + for (int k = 0; k < installed.Points.Count; k++) walked.Add(installed.Points[(start + k) % installed.Points.Count]); + int at = 0; + foreach (var p in saved.Points) + { + while (at < walked.Count && !(walked[at].NS == p.NS && walked[at].EW == p.EW && walked[at].Z == p.Z)) at++; + Check.True(at < walked.Count, $"saved point ({LX(p):F1}, {LY(p):F1}) is the installed patrol's, in its order"); + at++; + } + Check.True(installed.Points.Count - saved.Points.Count <= 3, $"all of it but a lead-in ({installed.Points.Count} installed, {saved.Points.Count} saved)"); + Check.True(saved.Points[0].NS == walked[0].NS && saved.Points[0].EW == walked[0].EW, "it starts where dunnav-patrol starts"); + + said = rig.Typed("/ra dunpatrol-save Hive patrol"); + Check.True(said.Count == 1 && said[0].Contains("already in NavProfiles"), "again: refused without overwrite: " + Show(said)); + said = rig.Typed("/ra dunpatrol-save Hive patrol overwrite"); + Check.True(said[0].Contains("replaced Hive patrol.nav"), "with overwrite: " + Show(said)); + said = rig.Typed("/ra dunpatrol-save"); + Check.True(said.Count == 1 && said[0].Contains("Usage: /ra dunpatrol-save"), "no name: the usage"); + said = rig.Typed("/ra dunpatrol-save a|b"); + Check.True(said.Count == 1 && said[0].Contains("can't be a route name"), "a bad name: " + Show(said)); + + said = rig.Typed("/ra dunroute info Hive patrol"); + Check.True(said[0].Contains("circular") && said[0].Contains("made for this dungeon: yes"), "info on the saved patrol: " + Show(said)); + } + + private static void PluginPatrolPolicy() + { + // The patrol is off in Threads on DreamWeave (ServerPolicy): the save builds the same patrol, so it asks too. + var rig = new Rig("NavProfiles-policy", world: "DreamWeave"); + ServerPolicy.NoteChat("[REALM] id=0 inst=7841 eph=1 name=Base World", rig.D.Start); + var said = rig.Typed("/ra dunpatrol-save Thread patrol"); + Check.True(said.Count == 1 && said[0].Contains("turned off in Threads"), "refused with the policy's line: " + Show(said)); + Check.False(File.Exists(Path.Combine(DungeonRouteMaker.Folder, "Thread patrol.nav")), "nothing written"); + said = rig.Typed("/ra dunroute Thread exit to exit"); + Check.True(said[0].Contains("saved Thread exit.nav"), "a route to the exit still works there: " + Show(said)); + ServerPolicy.Forget(); + } + + private static void PluginJobs() + { + var rig = new Rig("NavProfiles-jobs"); + var (id, err) = rig.Request("{\"op\":\"dunroute\",\"name\":\"Job exit\",\"to\":\"exit\"}"); + Check.True(id > 0, "queued: " + err); + Check.Eq(rig.Poll(id).GetProperty("state").GetString(), "queued", "queued until the tick"); + Check.False(File.Exists(Path.Combine(DungeonRouteMaker.Folder, "Job exit.nav")), "nothing done before the tick"); + rig.Tick(); + var j = rig.Poll(id); + Check.Eq(j.GetProperty("state").GetString(), "done", "done on the tick: " + j.GetProperty("detail").GetString()); + var res = j.GetProperty("result"); + Check.Eq(res.GetProperty("file").GetString(), Path.Combine(DungeonRouteMaker.Folder, "Job exit.nav"), "result.file"); + Check.Eq(res.GetProperty("type").GetString(), "once", "result.type"); + Check.True(res.GetProperty("points").GetInt32() >= 3 && res.GetProperty("yards").GetDouble() > 30, "points and yards"); + Check.Eq(res.GetProperty("to").GetProperty("kind").GetString(), "exit", "to.kind"); + Check.Eq(res.GetProperty("to").GetProperty("portal").GetString(), "Surface Portal", "to.portal"); + Check.Eq(res.GetProperty("to").GetProperty("id").GetString(), SurfaceId.ToString("X8"), "to.id"); + Check.Near(res.GetProperty("to").GetProperty("x").GetDouble(), 15, 0.01, "to.x landblock-local"); + Check.Near(res.GetProperty("from").GetProperty("y").GetDouble(), 15, 0.01, "from.y landblock-local"); + Check.Eq(res.GetProperty("landblock").GetString(), "7E7E", "landblock"); + Check.True(res.GetProperty("leftOut").ValueKind == JsonValueKind.Array && res.GetProperty("notes").GetArrayLength() >= 1, "leftOut and notes arrays"); + Check.True(File.Exists(Path.Combine(DungeonRouteMaker.Folder, "Job exit.nav")), "the file"); + Check.True(FakeHost.Chat.All(l => !l.Contains("Job exit")), "a job says nothing in chat"); + + // A failure: the same name again. + (id, _) = rig.Request("{\"op\":\"dunroute\",\"name\":\"Job exit\",\"to\":\"far\"}"); + rig.Tick(); + j = rig.Poll(id); + Check.Eq(j.GetProperty("state").GetString(), "failed", "failed"); + Check.True(j.GetProperty("detail").GetString()!.Contains("already in NavProfiles"), "with the reason"); + Check.Eq(j.GetProperty("result").ValueKind, JsonValueKind.Null, "no result"); + + // Portal space: it waits (working), then runs when the character lands; 30 s of it and it gives up. + var jobs = rig.P.RouteJobs; + long now = 5000; + jobs.Clock = () => now; + FakeHost.Portaling = true; + (id, _) = rig.Request("{\"op\":\"dunpatrol\",\"name\":\"Job patrol\"}"); + rig.Tick(); + j = rig.Poll(id); + Check.Eq(j.GetProperty("state").GetString(), "working", "in portal space: working"); + Check.True(j.GetProperty("detail").GetString()!.Contains("portal space"), "waiting for portal space: " + j.GetProperty("detail").GetString()); + now += 1000; + FakeHost.Portaling = false; + rig.Tick(); + j = rig.Poll(id); + Check.Eq(j.GetProperty("state").GetString(), "done", "landed: done: " + j.GetProperty("detail").GetString()); + Check.Eq(j.GetProperty("result").GetProperty("type").GetString(), "circular", "the patrol"); + Check.True(j.GetProperty("result").GetProperty("cells").GetInt32() == rig.D.Graph.Count, "cells"); + + FakeHost.Portaling = true; + (id, _) = rig.Request("{\"op\":\"where\"}"); + rig.Tick(); + now += DunRouteJobs.WaitLimitMs + 1; + rig.Tick(); + j = rig.Poll(id); + Check.Eq(j.GetProperty("state").GetString(), "failed", "30 s in portal space: failed"); + Check.True(j.GetProperty("detail").GetString()!.StartsWith("gave up after 30 s"), j.GetProperty("detail").GetString()!); + FakeHost.Portaling = false; + + // Refused at once. + var (bad, why) = rig.Request("{\"op\":\"dunroute\",\"name\":\"x\"}"); + Check.Eq(bad, 0u, "a bad request: no job"); + Check.True(why.Contains("\"to\" is missing"), why); + rig.Set("_loginComplete", false); + (bad, why) = rig.Request("{\"op\":\"where\"}"); + Check.True(bad == 0 && why.Contains("isn't logged in"), "not logged in: " + why); + rig.Set("_loginComplete", true); + + // info as a job. + (id, _) = rig.Request("{\"op\":\"info\",\"name\":\"Job exit\"}"); + rig.Tick(); + j = rig.Poll(id); + Check.Eq(j.GetProperty("result").GetProperty("forThisDungeon").GetString(), "yes", "info's result"); + } + + private static void PluginWhere() + { + var rig = new Rig("NavProfiles-where", namedExit: false); + // RynthAi sees the character land: first where it was (outdoors), then in the side room after portal space. + rig.At(42.1, 33.6, 0xA9B4002Fu); + rig.Tick(); + FakeHost.Portaling = true; + rig.At(43, 0, rig.D.Side); + rig.Tick(); + FakeHost.Portaling = false; + rig.Tick(); + rig.At(15, 15, rig.D.Start); + Check.True(FakeHost.Logs.Any(l => l.Contains("came into dungeon 7E7E")), "the arrival is noted"); + + var said = rig.Typed("/ra dunroute where"); + Check.True(said[0].Contains("in dungeon 7E7E") && said[0].Contains($"{rig.D.Graph.Count} cells"), "where: " + Show(said)); + Check.True(said[0].Contains("you're in room"), "the room it is in"); + Check.True(said.Any(l => l.Contains("portal 'Portal to the Depths'") && l.Contains("exit: the portal nearest where you came in")), "the exit by the arrival: " + Show(said)); + Check.True(said.Any(l => l.Contains("portal 'Portal to the Hub'") && l.Contains("yd on foot")), "the other, with its walk"); + Check.True(said.Any(l => l.Contains("you came in at cell")), "where it came in"); + + var (id, _) = rig.Request("{\"op\":\"where\"}"); + rig.Tick(); + var res = rig.Poll(id).GetProperty("result"); + Check.True(res.GetProperty("inDungeon").GetBoolean(), "inDungeon"); + Check.Eq(res.GetProperty("cell").GetString(), rig.D.Start.ToString("X8"), "cell"); + Check.True(res.GetProperty("map").GetBoolean() && res.GetProperty("rooms").GetInt32() >= 8, "map and rooms"); + var portals = res.GetProperty("portals"); + Check.Eq(portals.GetArrayLength(), 2, "both portals"); + Check.Eq(portals[0].GetProperty("name").GetString(), "Portal to the Depths", "nearest first (32 m, then the Hub's 37 m)"); + Check.Eq(portals[1].GetProperty("name").GetString(), "Portal to the Hub", "then the other"); + Check.True(portals[1].GetProperty("walkYards").GetDouble() >= portals[1].GetProperty("yards").GetDouble(), "walk at least the straight line"); + Check.Eq(portals[0].GetProperty("exit").GetString(), "the portal nearest where you came in", "why it would be the exit"); + Check.Eq(portals[1].GetProperty("exit").ValueKind, JsonValueKind.Null, "the other wouldn't"); + Check.Eq(portals[0].GetProperty("id").GetString(), DepthsId.ToString("X8"), "its id"); + Check.Near(portals[0].GetProperty("x").GetDouble(), 45, 0.01, "landblock-local x"); + Check.Near(res.GetProperty("arrival").GetProperty("x").GetDouble(), 43, 0.01, "arrival x"); + + // The exit, then, is that one. + said = rig.Typed("/ra dunroute Out to exit"); + Check.True(said[0].Contains("the exit portal 'Portal to the Depths' (the portal nearest where you came in)"), "dunroute to exit: " + Show(said)); + + // A logout forgets where it came in. + rig.Call("ForgetDunArrival"); + said = rig.Typed("/ra dunroute Out2 to exit"); + Check.True(said.Count == 1 && said[0].Contains("can't tell which portal is the exit"), "not seen arriving: " + Show(said)); + + rig.At(42.1, 33.6, 0xA9B4002Fu); + (id, _) = rig.Request("{\"op\":\"where\"}"); + rig.Tick(); + res = rig.Poll(id).GetProperty("result"); + Check.False(res.GetProperty("inDungeon").GetBoolean(), "outdoors: inDungeon false"); + Check.Eq(res.GetProperty("landblock").GetString(), "A9B4", "and where"); + } + + // ── Doorway points across a save (DunRouteSidecar) ─────────────────────── + + private static List DoorIdx(NavRouteParser r) + => Enumerable.Range(0, r.Points.Count).Where(i => r.Points[i].Doorway).ToList(); + + /// The exit route on the sample, saved as ; its doorway indexes. + private static (Sample D, string Path, List Doors) SavedExit(string folder, string name = "Hive exit") + { + string dir = Fresh(folder); + var d = new Sample(); + var b = Build(d.World(), DunTarget.Exit); + var doors = DoorIdx(b.Route); + Check.True(doors.Count >= 1, $"the exit route has doorway points ({doors.Count}: {string.Join(",", doors)})"); + Check.True(DungeonRouteMaker.TrySave(name, b.Route, false, Lb, out string path, out _, out string err), "saved: " + err); + return (d, path, doors); + } + + private static void DoorwaysSurviveReload() + { + var (_, path, doors) = SavedExit("NavProfiles-door1"); + string side = DunRouteSidecar.PathIn(DungeonRouteMaker.Folder); + Check.True(File.Exists(side), "NavProfiles\\.rynthai-routes.json written beside it"); + var json = JsonDocument.Parse(File.ReadAllBytes(side)).RootElement; + var entry = json.GetProperty("routes")[0]; + Check.Eq(entry.GetProperty("file").GetString(), "Hive exit.nav", "the file name"); + Check.Eq(entry.GetProperty("sha256").GetString(), DunRouteSidecar.Hash(File.ReadAllBytes(path)), "its SHA-256 as saved"); + Check.Eq(entry.GetProperty("landblock").GetString(), "7E7E", "the dungeon"); + Check.Eq(string.Join(",", entry.GetProperty("doorways").EnumerateArray().Select(e => e.GetInt32())), string.Join(",", doors), "the doorway indexes"); + + // The .nav is VTank's, flag line "0" on every point. + var lines = File.ReadAllLines(path); + int count = int.Parse(lines[2]); + var plain = NavRouteParser.Load(path); + Check.Eq(plain.Points.Count, count, "the file reads as before"); + Check.Eq(DoorIdx(plain).Count, 0, "a plain load has no doorway flags (the format has none)"); + + var e = DunRouteSidecar.Match(DungeonRouteMaker.Folder, path, plain, out string? log); + Check.NotNull(e, "the loaded file is the route maker's, unchanged: " + log); + Check.Eq(DunRouteSidecar.Apply(plain, e!), doors.Count, "every doorway point restored"); + Check.Eq(string.Join(",", DoorIdx(plain)), string.Join(",", doors), "on the same points as when it was laid"); + } + + private static void DoorwaysEditedFile() + { + var (d, path, _) = SavedExit("NavProfiles-door2"); + var lines = File.ReadAllLines(path).ToList(); + lines[4] = (double.Parse(lines[4], System.Globalization.CultureInfo.InvariantCulture) + 0.001).ToString(System.Globalization.CultureInfo.InvariantCulture); // the first point's EW + File.WriteAllLines(path, lines); + var edited = NavRouteParser.Load(path); + Check.Null(DunRouteSidecar.Match(DungeonRouteMaker.Folder, path, edited, out string? log), "an edited file: no entry"); + Check.True(log != null && log.Contains("was changed since the route maker saved it"), "and one line saying so: " + log); + Check.Eq(DoorIdx(edited).Count, 0, "no flags"); + + // A nav the route maker didn't write, and a route in hand that isn't the file's (dunnav leaves the path). + string other = Path.Combine(DungeonRouteMaker.Folder, "Recorded.nav"); + var rec = new NavRouteParser { RouteType = NavRouteType.Circular }; + rec.Points.Add(DungeonRouteMaker.WorldPt(Ox + 5, Oy + 5, 0)); + rec.Points.Add(DungeonRouteMaker.WorldPt(Ox + 25, Oy + 5, 0)); + rec.Save(other); + Check.Null(DunRouteSidecar.Match(DungeonRouteMaker.Folder, other, NavRouteParser.Load(other), out log), "a recorded nav: not the route maker's"); + Check.Null(log, "and nothing logged"); + var (_, path3, _) = SavedExit("NavProfiles-door2b"); + Check.Null(DunRouteSidecar.Match(DungeonRouteMaker.Folder, path3, Build(d.World(), DunTarget.Far).Route, out log), "a route in hand that isn't the file's: nothing"); + Check.Null(log, "nothing logged"); + Check.Null(DunRouteSidecar.Match(DungeonRouteMaker.Folder, Path.Combine(Program.TempRoot, "Hive exit.nav"), NavRouteParser.Load(path3), out _), "the same name in another folder: not this list's"); + } + + private static void DoorwaysPluginLoad() + { + var rig = new Rig("NavProfiles-door3"); + var said = rig.Typed("/ra dunroute Hive exit to exit"); + Check.True(said[0].Contains("saved Hive exit.nav"), Show(said)); + string path = Path.Combine(DungeonRouteMaker.Folder, "Hive exit.nav"); + var saved = DunRouteSidecar.Read(DungeonRouteMaker.Folder, out _).Single(); + Check.True(saved.Doorways.Count >= 1, $"the command recorded its doorway points ({saved.Doorways.Count})"); + + // Loaded while the character is in another dungeon: nothing, until it is in this one. + rig.At(50, 100, 0x7E7F0105u); + rig.S.CurrentNavPath = path; + rig.S.CurrentRoute = NavRouteParser.Load(path); + rig.Tick(); + Check.Eq(DoorIdx(rig.S.CurrentRoute).Count, 0, "in another dungeon: no flags"); + rig.Tick(); + Check.Eq(DoorIdx(rig.S.CurrentRoute).Count, 0, "still none there"); + rig.At(15, 15, rig.D.Start); + rig.Tick(); + Check.Eq(string.Join(",", DoorIdx(rig.S.CurrentRoute)), string.Join(",", saved.Doorways), "in its dungeon: the doorway points restored"); + Check.True(FakeHost.Logs.Any(l => l.Contains("'Hive exit.nav':") && l.Contains("doorway point(s) restored")), "logged"); + + // Loaded in its dungeon: at once (the next tick, before navigation). + rig.S.CurrentRoute = NavRouteParser.Load(path); + rig.Tick(); + Check.Eq(DoorIdx(rig.S.CurrentRoute).Count, saved.Doorways.Count, "loaded in the dungeon: restored on the next tick"); + + // The patrol save keeps its doorway points too. + said = rig.Typed("/ra dunpatrol-save Hive patrol"); + Check.True(said[0].Contains("saved Hive patrol.nav"), Show(said)); + string ppath = Path.Combine(DungeonRouteMaker.Folder, "Hive patrol.nav"); + rig.S.CurrentNavPath = ppath; + rig.S.CurrentRoute = NavRouteParser.Load(ppath); + rig.Tick(); + var entry = DunRouteSidecar.Read(DungeonRouteMaker.Folder, out _).Single(x => x.File == "Hive patrol.nav"); + Check.True(entry.Doorways.Count > 0 && DoorIdx(rig.S.CurrentRoute).Count == entry.Doorways.Count, + $"the saved patrol walks its doorways as dunnav-patrol does ({entry.Doorways.Count} points)"); + rig.P.HandleDungeonNavPatrol(); + Check.True(rig.S.CurrentRoute.Points.Count(p => p.Doorway) >= entry.Doorways.Count, "as many as dunnav-patrol's own lap has"); + + // Edited after loading, before the character is in its dungeon: not restored. + rig.At(50, 100, 0x7E7F0105u); + rig.S.CurrentNavPath = path; + rig.S.CurrentRoute = NavRouteParser.Load(path); + rig.Tick(); + NavRouteEditing.Apply(rig.S, list => { list.RemoveAt(1); return list; }); + rig.At(15, 15, rig.D.Start); + rig.Tick(); + Check.Eq(DoorIdx(rig.S.CurrentRoute).Count, 0, "edited in memory first: no flags"); + Check.True(FakeHost.Logs.Any(l => l.Contains("was edited before you were in its dungeon")), "said in the log"); + } + + private static void DoorwaysCorruptSidecar() + { + var (_, path, doors) = SavedExit("NavProfiles-door4"); + string side = DunRouteSidecar.PathIn(DungeonRouteMaker.Folder); + foreach (string junk in new[] { "{ not json", "[1,2,3]", "{\"routes\":5}", "\u0000\u0001garbage" }) + { + File.WriteAllText(side, junk); + var r = NavRouteParser.Load(path); + Check.Eq(r.Points.Count, int.Parse(File.ReadAllLines(path)[2]), "with a corrupt list the nav loads as ever"); + Check.Null(DunRouteSidecar.Match(DungeonRouteMaker.Folder, path, r, out string? log), "no entry"); + Check.True(log != null && log.Contains(DunRouteSidecar.FileName), "the problem logged: " + log); + Check.Eq(DoorIdx(r).Count, 0, "no flags"); + } + // A good entry beside a bad one: the good one still counts. + string good = File.ReadAllText(side); + File.WriteAllText(side, "{\"version\":1,\"routes\":[{\"file\":\"x.nav\",\"sha256\":\"nope\"}]}"); + Check.Eq(DunRouteSidecar.Read(DungeonRouteMaker.Folder, out string? p1).Count, 0, "a bad entry is skipped: " + p1); + File.Delete(side); + Check.Null(DunRouteSidecar.Match(DungeonRouteMaker.Folder, path, NavRouteParser.Load(path), out string? none), "no list: no entry"); + Check.Null(none, "and nothing to log"); + + // The next save writes a good list again. + File.WriteAllText(side, "{ not json"); + var d = new Sample(); + var notes = new List(); + Check.True(DungeonRouteMaker.TrySave("Hive exit", Build(d.World(), DunTarget.Exit).Route, true, Lb, out _, out _, out _, notes), "saved over the corrupt list"); + Check.True(notes.Any(n => n.Contains("corrupt") && n.Contains("written again")), "and said: " + string.Join(" | ", notes)); + var r2 = NavRouteParser.Load(path); + var e2 = DunRouteSidecar.Match(DungeonRouteMaker.Folder, path, r2, out _); + Check.NotNull(e2, "the list is good again"); + Check.Eq(DunRouteSidecar.Apply(r2, e2!), doors.Count, "and restores"); + + // The plugin's tick with a corrupt list: no exception, no flags. + var rig = new Rig("NavProfiles-door4b"); + rig.Typed("/ra dunroute Hive exit to exit"); + File.WriteAllText(DunRouteSidecar.PathIn(DungeonRouteMaker.Folder), "\u0000garbage"); + rig.S.CurrentNavPath = Path.Combine(DungeonRouteMaker.Folder, "Hive exit.nav"); + rig.S.CurrentRoute = NavRouteParser.Load(rig.S.CurrentNavPath); + rig.Tick(); + Check.Eq(DoorIdx(rig.S.CurrentRoute).Count, 0, "the tick with a corrupt list: no flags (and nothing threw)"); + } + + private static void DoorwaysOverwriteAndPrune() + { + var (d, path, _) = SavedExit("NavProfiles-door5"); + Check.True(DungeonRouteMaker.TrySave("Far end", Build(d.World(), DunTarget.Far).Route, false, Lb, out string farPath, out _, out _), "a second route"); + Check.Eq(DunRouteSidecar.Read(DungeonRouteMaker.Folder, out _).Count, 2, "two entries"); + string before = DunRouteSidecar.Read(DungeonRouteMaker.Folder, out _).Single(e => e.File == "Hive exit.nav").Sha256; + var other = Build(d.World(), new DunTarget(DunTargetKind.Portal, Portal: "depths")); + Check.True(DungeonRouteMaker.TrySave("Hive exit", other.Route, true, Lb, out _, out bool ow, out _), "overwritten"); + Check.True(ow, "it was an overwrite"); + var list = DunRouteSidecar.Read(DungeonRouteMaker.Folder, out _); + var now = list.Single(e => e.File == "Hive exit.nav"); + Check.True(now.Sha256 != before && now.Sha256 == DunRouteSidecar.Hash(File.ReadAllBytes(path)), "the entry follows the new file"); + Check.Eq(string.Join(",", now.Doorways), string.Join(",", DoorIdx(other.Route)), "with the new route's doorway points"); + Check.Eq(list.Count, 2, "still one entry a file"); + + File.Delete(farPath); + DungeonRouteMaker.TrySave("Spot", Build(d.World(), new DunTarget(DunTargetKind.Position, X: -17.5, Y: 25, Z: 0)).Route, false, Lb, out _, out _, out _); + list = DunRouteSidecar.Read(DungeonRouteMaker.Folder, out _); + Check.False(list.Any(e => e.File == "Far end.nav"), "the entry of a file that's gone is pruned at the next save"); + Check.Eq(string.Join(",", list.Select(e => e.File)), "Hive exit.nav,Spot.nav", "the rest kept"); + } + + private static void DoorwaysEngineReach() + { + var (d, path, doors) = SavedExit("NavProfiles-door6"); + var restored = NavRouteParser.Load(path); + DunRouteSidecar.Apply(restored, DunRouteSidecar.Match(DungeonRouteMaker.Folder, path, restored, out _)!); + // A doorway point with a plain one before it at least 4 yd away. + int k = doors.First(i => i > 0 && NavRouteParser.IsPlainWaypoint(restored.Points[i - 1].Type) + && Dist(restored.Points[i - 1], restored.Points[i]) >= 4); + var a = restored.Points[k - 1]; var p = restored.Points[k]; + double len = Dist(a, p), ux = (LX(p) - LX(a)) / len, uy = (LY(p) - LY(a)) / len; + + int Walk(NavRouteParser route, double shortBy) + { + FakeHost.Reset(); + long now = 1_000_000; + NavigationEngine.Clock = () => now; + try + { + FakeHost.PlayerPose = (d.Start, (float)(LX(p) - ux * 3.5), (float)(LY(p) - uy * 3.5), 0f); + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, EnableNavigation = true, CurrentRoute = route, ActiveNavIndex = k }; + var e = new NavigationEngine(host, s); + now += 100; e.Tick(); + FakeHost.PlayerPose = (d.Start, (float)(LX(p) - ux * shortBy), (float)(LY(p) - uy * shortBy), 0f); + now += 100; e.Tick(); + return s.ActiveNavIndex; + } + finally { NavigationEngine.Clock = () => Environment.TickCount64; } + } + + Check.True(restored.Points[k].Doorway, $"point {k} is a restored doorway point"); + Check.Eq(Walk(restored, 1.2), k, "1.2 yd short of a restored doorway point: not there yet (its reach is 1 yd)"); + Check.Eq(Walk(restored, 0.9), k + 1, "0.9 yd: reached"); + var plain = NavRouteParser.Load(path); + Check.Eq(Walk(plain, 1.2), k + 1, "the same file loaded plain (no list): reached at 1.2 yd, the ordinary 1.5 yd reach"); + } + + private static double Dist(NavPoint a, NavPoint b) => Math.Sqrt((LX(a) - LX(b)) * (LX(a) - LX(b)) + (LY(a) - LY(b)) * (LY(a) - LY(b))); + + // ── Tiny Hive on the real dats ─────────────────────────────────────────── + + private const string AcDir = @"C:\Turbine\Asheron's Call"; + + private static void TinyHiveRealDats() + { + if (!Directory.Exists(AcDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; } + var loader = new GeometryLoader(); + if (!loader.Initialize(AcDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; } + try + { + const uint lb = 0x0289, start = 0x028902A5, nook = 0x028902BA; + var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat); + var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS); + Check.True(graph.Count > 400 && geo != null, $"Tiny Hive loaded ({graph.Count} cells)"); + var s = graph[start]; + // The Surface Portal (weenie 11218, 0x7028905D): cell 028902BA, local (110, -3.77927, -23.995). + var p = new PatrolPortal { Id = 0x7028905D, Name = "Surface Portal", Cell = nook, X = 2 * 192 + 110, Y = 0x89 * 192 - 3.77927, Z = -23.995 }; + var w = new DunRouteWorld + { + Landblock = lb, PlayerCell = start, StartCell = start, + X = DungeonGeometry.NavToWorld(s.EW), Y = DungeonGeometry.NavToWorld(s.NS), Z = s.Z, + Graph = graph, Geo = geo, Portals = new List { p }, + }; + var exit = Build(w, DunTarget.Exit); + Check.Eq(exit.Portal?.Name, "Surface Portal", "the exit"); + Check.Eq(exit.Route.Points[^1].Type, NavPointType.PortalNPC, "a Portal step at the end"); + var last = exit.Route.Points[^2]; + double d = Math.Sqrt(Math.Pow(DungeonGeometry.NavToWorld(last.EW) - p.X, 2) + Math.Pow(DungeonGeometry.NavToWorld(last.NS) - p.Y, 2)); + Check.True(d >= p.Radius - 0.05 && d < p.Radius + 1.0, $"the walk stops at its edge ({d:F2} m)"); + Console.WriteLine($" exit: {exit.Route.Points.Count} points, {exit.Yards:F1} yd, {exit.PathCells} cells, {exit.Doorways} doorway(s)"); + + var far = Build(w, DunTarget.Far); + Check.True(far.Yards > 100 && far.PathCells > 10, $"the far end is a long way ({far.Yards:F0} yd, {far.PathCells} cells)"); + double near = DungeonPathfinder.NearestApproach(far.Route.Points.Where(q => NavRouteParser.IsPlainWaypoint(q.Type)).ToList(), false, p); + Check.True(near >= p.Radius - 0.05, $"and keeps out of the Surface Portal on its level ({near:F1} m)"); + Console.WriteLine($" far: cell {far.GoalCell:X8}, {far.Route.Points.Count} points, {far.Yards:F0} yd"); + } + finally { DungeonPathfinder.InvalidateCache(); } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs index c17710f..0b4718d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs @@ -677,6 +677,13 @@ internal static class ExpressionTests Check.Near(s.NavOffTrackYards, 160, 1e-6, "NavOffTrackYards clamps to at least 160"); Is(e, "vtsetsetting[AutoVendorTries, 99]", "1"); Check.Eq(s.AutoVendorTries, 20, "AutoVendorTries clamps to 20"); + Is(e, "vtgetsetting[ChestRelockWaitSec]", "125"); + Is(e, "vtsetsetting[ChestRelockWaitSec, 30]", "1"); + Check.Eq(s.ChestRelockWaitSec, 30, "ChestRelockWaitSec (Item Tool's re-lock wait) set"); + Is(e, "vtsetsetting[ChestRelockWaitSec, 2]", "1"); + Check.Eq(s.ChestRelockWaitSec, 5, "ChestRelockWaitSec clamps to at least 5"); + Is(e, "vtsetsetting[ChestRelockWaitSec, soon]", "1"); + Check.Eq(s.ChestRelockWaitSec, 5, "unparsable leaves the value"); Is(e, "vtsetsetting[BowArcVelocity, NaN]", "1"); Check.True(float.IsFinite(s.BowArcVelocity), "NaN is refused"); Is(e, "vtsetsetting[NotASetting, 7]", "1"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/FellowOpenTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/FellowOpenTests.cs new file mode 100644 index 0000000..ecbaced --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/FellowOpenTests.cs @@ -0,0 +1,200 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Open fellowship on create (2026-11-04, a Discord request): with Auto Fellowship Management on, a +// fellowship RynthAi creates is opened once it exists and this character leads it, as VTank's auto +// fellow management does. Never a fellowship made or closed by hand. +internal static class FellowOpenTests +{ + public static void Register(Runner r) + { + r.Add("fellow open: /mt fellow create, then /fellowship open once we lead it (setting on)", OpenAfterCreate); + r.Add("fellow open: nothing opened with the setting off, or with Auto Fellowship Management off", NotWhenOff); + r.Add("fellow open: a meta's own /fellowship create is opened too", MetaCreateLine); + r.Add("fellow open: never when already in a fellowship, led by another, already open, or a hand-made one", NeverOthers); + r.Add("fellow open: the wait ends when no fellowship comes", WaitEnds); + r.Add("fellow open: on by default, a meta setting, and an older engine leaves it alone", DefaultsAndPlumbing); + } + + private const uint Player = 0x50000F41; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + private const string Open = "/fellowship open"; + + private sealed class World + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() { AutoFellowMgmt = true }; + public bool InFellowship, IsLeader, IsOpen; + + public World() + { + FakeHost.Reset(); + FakeHost.Names[Player] = "Tester"; + FakeHost.PlayerIdValue = Player; + var host = FakeHost.Create(playerId: Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); // a stand-in with its profile in memory + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Set("_playerId", Player); + Set("_initialized", true); + Set("_loginComplete", true); + P.FellowStateOverride = () => (InFellowship, IsLeader, IsOpen); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(P, new object[] { line })!; + public bool Meta(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMetaChatCommand", Any)!.Invoke(P, new object[] { line })!; + public void Tick() => typeof(RynthAiPlugin).GetMethod("TickFellowOpen", Any)!.Invoke(P, null); + public long WaitUntil + { + get => (long)typeof(RynthAiPlugin).GetField("_fellowOpenUntil", Any)!.GetValue(P)!; + set => Set("_fellowOpenUntil", value); + } + public int Opens => FakeHost.ChatCommands.Count(c => c == Open); + + /// The server made the fellowship: we lead it, closed. + public void Created() { InFellowship = true; IsLeader = true; IsOpen = false; } + } + + private static void OpenAfterCreate() + { + var w = new World(); + Check.True(w.Mt("/mt fellow create Hunters"), "/mt fellow create is handled"); + Check.True(FakeHost.ChatCommands.Contains("/fellowship create Hunters"), "the create went to the chat parser"); + w.Tick(); + Check.Eq(w.Opens, 0, "not opened before the fellowship exists"); + w.Created(); + w.Tick(); + Check.Eq(w.Opens, 1, "opened once we lead it"); + Check.True(FakeHost.ChatCommands.IndexOf("/fellowship create Hunters") < FakeHost.ChatCommands.IndexOf(Open), "after the create"); + w.Tick(); w.Tick(); + Check.Eq(w.Opens, 1, "and only once"); + + // The player closes it by hand later: it stays closed. + w.IsOpen = false; + for (int i = 0; i < 5; i++) w.Tick(); + Check.Eq(w.Opens, 1, "a fellowship closed by hand is not opened again"); + } + + private static void NotWhenOff() + { + var w = new World(); + w.S.OpenFellowOnCreate = false; + w.Mt("/mt fellow create Hunters"); + Check.True(FakeHost.ChatCommands.Contains("/fellowship create Hunters"), "the create still goes out"); + w.Created(); + w.Tick(); w.Tick(); + Check.Eq(w.Opens, 0, "Open fellowship on create off: nothing opened"); + + var w2 = new World(); + w2.S.AutoFellowMgmt = false; // Open fellowship on create left on (its default) + w2.Mt("/mt fellow create Hunters"); + w2.Created(); + w2.Tick(); + Check.Eq(w2.Opens, 0, "Auto Fellowship Management off: nothing opened"); + + // Switched off while the create waits. + var w3 = new World(); + w3.Mt("/mt fellow create Hunters"); + w3.S.OpenFellowOnCreate = false; + w3.Tick(); + w3.S.OpenFellowOnCreate = true; + w3.Created(); + w3.Tick(); + Check.Eq(w3.Opens, 0, "switched off before the fellowship came: nothing opened"); + } + + private static void MetaCreateLine() + { + var w = new World(); + Check.False(w.Meta("/fellowship create Hunters"), "a meta's /fellowship create goes on to the chat parser"); + w.Created(); + w.Tick(); + Check.Eq(w.Opens, 1, "and is opened"); + + var w2 = new World(); + w2.Meta("/mt fellow create Hunters"); + w2.Created(); + w2.Tick(); + Check.Eq(w2.Opens, 1, "a meta's /mt fellow create is opened"); + + var w3 = new World(); + w3.Meta("/fellowship recruit Hunters"); + w3.Meta("/fellowship create"); + w3.Created(); + w3.Tick(); + Check.Eq(w3.Opens, 0, "other fellowship lines, and a create without a name, arm nothing"); + } + + private static void NeverOthers() + { + // Already in a fellowship: the create fails, and the fellowship we're in isn't ours to open. + var w = new World(); + w.Created(); + w.Mt("/mt fellow create Hunters"); + w.Tick(); w.Tick(); + Check.Eq(w.Opens, 0, "already in a fellowship: nothing opened"); + + // Someone else's fellowship turns up (we were recruited meanwhile). + var w2 = new World(); + w2.Mt("/mt fellow create Hunters"); + w2.InFellowship = true; w2.IsLeader = false; + w2.Tick(); + w2.IsLeader = true; // made leader later + w2.Tick(); + Check.Eq(w2.Opens, 0, "led by another: nothing opened, and the wait is over"); + + // Already open. + var w3 = new World(); + w3.Mt("/mt fellow create Hunters"); + w3.Created(); w3.IsOpen = true; + w3.Tick(); + Check.Eq(w3.Opens, 0, "already open: nothing sent"); + + // A fellowship the player made without RynthAi. + var w4 = new World(); + w4.Created(); + for (int i = 0; i < 3; i++) w4.Tick(); + Check.Eq(w4.Opens, 0, "a fellowship RynthAi didn't create is left alone"); + } + + private static void WaitEnds() + { + var w = new World(); + w.Mt("/mt fellow create Hunters"); + Check.True(w.WaitUntil > 0, "the create waits"); + w.WaitUntil = Environment.TickCount64 - 1; // the wait is over + w.Tick(); + Check.Eq(w.WaitUntil, 0L, "the wait ends"); + w.Created(); + w.Tick(); + Check.Eq(w.Opens, 0, "a fellowship made after the wait is not opened"); + } + + private static void DefaultsAndPlumbing() + { + Check.True(new LegacyUiSettings().OpenFellowOnCreate, "on by default"); + Check.False(new LegacyUiSettings().AutoFellowMgmt, "Auto Fellowship Management stays off by default, so nothing changes until it's on"); + Check.Eq(new SettingsBridgePayload().OpenFellowOnCreate, (bool?)null, "the bridge sends null when an older engine doesn't know it"); + + FakeHost.Reset(); + var s = new LegacyUiSettings(); + var m = new MetaManager(s, FakeHost.Create(), new PlayerVitalsCache()); + Check.Eq(m.Expressions.Evaluate("ragetsetting[OpenFellowOnCreate]"), "1", "metas read it"); + m.Expressions.Evaluate("rasetsetting[OpenFellowOnCreate, 0]"); + Check.False(s.OpenFellowOnCreate, "and set it"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HealGraceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HealGraceTests.cs new file mode 100644 index 0000000..cccfecc --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HealGraceTests.cs @@ -0,0 +1,321 @@ +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; + +// The heal grace (ActionPacer.HealGraceMs, 2 s): a heal under a heal line no longer waits on a kit the +// server shows no sign of taking, a kit answered with a bare UseDone, a kit nobody answered, or a busy +// count nobody cleared. A kit with no result line used to hold every vital for 8 s (the kit wait's old +// time limit). The animation gate and the cast gate are unchanged: a heal still waits for a gesture. +internal static class HealGraceTests +{ + private const uint Player = 0x50000E41; + private const uint Corpse = 0x80068AD1; + private const uint Kit = 0x8004BF01; + private const uint Potion = 0x8004BF02; + private const uint Pack = Player; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; + + public static void Register(Runner r) + { + r.Add("heal grace: the kit wait ends on its line, its UseDone(0) with no line, 2 s with no sign the server took it, or 3.5 s", KitWaitVerdicts); + r.Add("heal grace: a heal goes ahead of a kit on yourself nobody answered after 2 s; a corpse use, a potion and a non-heal still wait", PacerItemUseGrace); + r.Add("heal grace: a plain heal still waits for the character's animation past 2 s (the animation gate is unchanged)", PacerGestureUnchanged); + r.Add("heal grace: a live busy count holds a heal 2 s at most from its rise (not on top of the pacer's hold)", BusyCountGrace); + r.Add("heal grace: KitPending lets a kit with no sign from the server go at 2 s (a retry)", KitNoProgressRetried); + r.Add("heal grace: KitPending waits for a kit the server started up to 3.5 s", KitStartedWaitsToLimit); + r.Add("heal grace: with neither GetCastBusyState nor the UseDone sequence, a kit waits the 3.5 s limit (no retry at 2 s)", KitNoSignalsWaitsToLimit); + r.Add("heal grace: KitPending ends 700 ms after the kit's own UseDone(0) with no line; a later UseDone or a playing motion keeps it", KitAnsweredNoLine); + } + + private static void KitWaitVerdicts() + { + const double G = ActionPacer.HealGraceMs; + Check.Eq(BuffManager.KitWaitVerdict(500, -1, -1, false, false), BuffManager.KitWaitEnd.Waiting, "500 ms, nothing yet: wait"); + Check.Eq(BuffManager.KitWaitVerdict(G - 1, -1, -1, false, false), BuffManager.KitWaitEnd.Waiting, "just under the grace: wait"); + Check.Eq(BuffManager.KitWaitVerdict(G, -1, -1, false, false), BuffManager.KitWaitEnd.NotTaken, "the grace with no sign from the server: let go (sent again)"); + Check.Eq(BuffManager.KitWaitVerdict(G + 500, -1, -1, false, true), BuffManager.KitWaitEnd.Waiting, "animating now: the kit may be playing, wait"); + Check.Eq(BuffManager.KitWaitVerdict(G + 500, -1, -1, true, false), BuffManager.KitWaitEnd.Waiting, "the heal motion was seen: wait for its line"); + Check.Eq(BuffManager.KitWaitVerdict(3500, -1, -1, true, true), BuffManager.KitWaitEnd.TimedOut, "3.5 s whatever happened: let go"); + Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 699, true, false), BuffManager.KitWaitEnd.Waiting, "UseDone(0) 699 ms ago, no line: wait"); + Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 700, true, false), BuffManager.KitWaitEnd.Answered, "UseDone(0) 700 ms ago, no line: none is coming"); + Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 700, true, true), BuffManager.KitWaitEnd.Waiting, "UseDone(0) but a motion plays: another action's answer, wait"); + Check.Eq(BuffManager.KitWaitVerdict(1200, 300, -1, true, false), BuffManager.KitWaitEnd.Waiting, "line seen 300 ms ago: the vitals grace runs"); + Check.Eq(BuffManager.KitWaitVerdict(9000, 300, -1, true, false), BuffManager.KitWaitEnd.Waiting, "a line seen: its grace runs out even past the limit"); + Check.Eq(BuffManager.KitWaitVerdict(1200, 700, -1, true, false), BuffManager.KitWaitEnd.Landed, "line seen 700 ms ago: done"); + } + + private static long _t; + + private static RynthCoreHost PacedWorld() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.SalvageCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.StopCalls = true; + FakeHost.BusyCalls = true; + FakeHost.CombatModeValue = 2; + FakeHost.Names[Player] = "Tester"; + FakeHost.Names[Corpse] = "Corpse of Drumtaken Ursuin"; + FakeHost.Names[Kit] = "Treated Healing Kit"; + FakeHost.Names[Potion] = "Health Draught"; + FakeHost.Bitfields[Corpse] = 0x2000; + FakeHost.Containers[Kit] = Pack; + FakeHost.Containers[Potion] = Pack; + _t = 20_000_000; + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => _t; + UseAudit.Reset("RynthAi", () => true); + UseAudit.NowMs = () => _t; + MoveAudit.Reset(); + MoveAudit.NowMs = () => _t; + var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!; + UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u }); + return FakeHost.Create(Player); + } + + 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; + FakeHost.CastBusy = 0; + } + + private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal)); + + private static void PacerItemUseGrace() + { + try + { + var host = PacedWorld(); + host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself"); + Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "the kit is the outstanding action"); + _t += ActionPacer.HealGraceMs - 1; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "1 ms under the grace: the heal waits for the kit's answer"); + _t += 1; + Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "at the grace: a non-heal still waits"); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at the grace: the heal goes (the kit is sent again)"); + Check.True(Logged("heal grace"), "logged"); + + // A potion (an item use with no target) keeps the pacer's own limit. + FakeHost.UseDone(0); + host.UseFor(Potion, "Buff", "vitals: drink"); + Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "the potion is the outstanding action"); + _t += ActionPacer.HealGraceMs + 100; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a potion at 2.1 s: the heal still waits (not on yourself)"); + FakeHost.UseDone(0); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "answered: the heal goes"); + + // A corpse use keeps its rule: a plain heal waits for its answer (the server's turn to it). + host.UseFor(Corpse, "Loot", "open"); + _t += 3900; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a corpse use at 3.9 s: the plain heal still waits"); + FakeHost.UseDone(0); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "answered: the heal goes"); + } + finally { PaceOff(); } + } + + private static void PacerGestureUnchanged() + { + try + { + var host = PacedWorld(); + FakeHost.CastBusy = 1; // the client's motion queue reads busy + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "animating: the heal waits"); + _t += ActionPacer.HealGraceMs + 500; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "2.5 s of animation: a plain heal still waits (a send into a gesture draws 'too busy')"); + FakeHost.CastBusy = 0; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "the queue reads clear: the heal goes"); + } + finally { PaceOff(); } + } + + private static void BusyCountGrace() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, UsePotions = false }; + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + var t0 = new DateTime(2026, 1, 1, 12, 0, 0); + DateTime now = t0; + b.Clock = () => now; + var resets = new System.Collections.Generic.List(); + b.SetStaleBusyCallback(why => resets.Add(why)); + + FakeHost.UseDoneSeq = 5; + b.BusyCount = 1; // rises at t0: a count with no UseDone since, real as far as anyone can tell + Check.True(b.BusyHoldsHeal(), "t=0: the count holds the heal"); + now = t0.AddMilliseconds(ActionPacer.HealGraceMs - 1); + Check.True(b.BusyHoldsHeal(), "1 ms under the grace from the rise: held"); + now = t0.AddMilliseconds(ActionPacer.HealGraceMs); + Check.False(b.BusyHoldsHeal(), "2 s after the rise: the heal goes"); + Check.Eq(b.StaleBusyClears, 1, "cleared once"); + Check.Eq(b.BusyCount, 0, "the count is reset"); + Check.True(resets.Count == 1 && resets[0].Contains("heal grace", StringComparison.Ordinal), "through the stale-busy callback, saying why"); + + // First asked 1.9 s after the rise (the pacer's hold): the count holds it only 0.1 s more. + now = t0.AddMilliseconds(10_000); + b.BusyCount = 1; + now = t0.AddMilliseconds(11_900); + Check.True(b.BusyHoldsHeal(), "first asked 1.9 s after the rise: held"); + now = t0.AddMilliseconds(12_000); + Check.False(b.BusyHoldsHeal(), "2.0 s after the rise: goes (no 2 s more on top of the pacer's hold)"); + + // A count that only goes up further (1 -> 2) keeps its rise time. + now = t0.AddMilliseconds(20_000); + b.BusyCount = 1; + now = t0.AddMilliseconds(21_000); + b.BusyCount = 2; + now = t0.AddMilliseconds(22_000); + Check.False(b.BusyHoldsHeal(), "2 s after the first rise, 1 s after 1 -> 2: goes"); + } + + // -- KitPending and NoteKitProgress, driven through BuffManager (real time: the kit wait reads RynthClock) + + private sealed class Rig + { + public readonly BuffManager B; + public readonly LegacyUiSettings S; + public readonly RynthCoreHost H; + public Rig(bool serverGates = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = serverGates; // GetCastBusyState and the UseDone sequence + FakeHost.LastUseDoneCalls = serverGates; + FakeHost.CombatModeValue = CombatMode.Magic; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic + var host = FakeHost.Create(); + H = host; + S = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false, + }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, S); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + B = new BuffManager(host, S, sm, v); + B.SetCharacterSkills(skills); + B.MarkLiveBuffsReadyForTests(); + } + } + + private static void SleepUntil(System.Diagnostics.Stopwatch sw, long ms) + { + long left = ms - sw.ElapsedMilliseconds; + if (left > 0) System.Threading.Thread.Sleep((int)left); + } + + private static void KitNoProgressRetried() + { + var r = new Rig(); + var sw = System.Diagnostics.Stopwatch.StartNew(); + r.B.MarkKitUsed(); + Check.True(r.B.KitPending(), "kit just used: waiting"); + SleepUntil(sw, 1700); + Check.True(r.B.KitPending(), "1.7 s, nothing from the server: still waiting"); + SleepUntil(sw, ActionPacer.HealGraceMs + 100); + Check.False(r.B.KitPending(), "past the heal grace with no motion, UseDone or line: let go"); + Check.Eq(r.B.KitRetries, 1, "counted as a retry"); + Check.True(FakeHost.Logs.Any(l => l.Contains("shows no sign the server took it", StringComparison.Ordinal)), "logged"); + } + + // An engine with neither GetCastBusyState nor the UseDone sequence can't show the server took a kit: + // no retry at the heal grace (the kit may be playing), only the 3.5 s limit. + private static void KitNoSignalsWaitsToLimit() + { + var r = new Rig(serverGates: false); + Check.False(r.H.HasGetCastBusyState || r.H.HasUseDoneSeq, "the rig: neither capability"); + var sw = System.Diagnostics.Stopwatch.StartNew(); + r.B.MarkKitUsed(); + SleepUntil(sw, ActionPacer.HealGraceMs + 300); + Check.True(r.B.KitPending(), "past the heal grace: still waiting (nothing could show the server took it)"); + Check.Eq(r.B.KitRetries, 0, "no retry at 2 s"); + SleepUntil(sw, 3500 + 150); + Check.False(r.B.KitPending(), "past 3.5 s: let go"); + } + + private static void KitStartedWaitsToLimit() + { + var r = new Rig(); + var sw = System.Diagnostics.Stopwatch.StartNew(); + r.B.MarkKitUsed(); + FakeHost.CastBusy = 1; // the heal motion plays + r.B.OnHeartbeat(); // the heartbeat records it (NoteKitProgress) + FakeHost.CastBusy = 0; + SleepUntil(sw, 3300); + Check.True(r.B.KitPending(), "the server took it: 3.3 s, still waiting for its line"); + SleepUntil(sw, 3500 + 150); // the 3.5 s limit, as a literal: the test must not follow the constant + Check.False(r.B.KitPending(), "past 3.5 s: let go"); + Check.Eq(r.B.KitRetries, 1, "counted"); + } + + private static void KitAnsweredNoLine() + { + var r = new Rig(); + FakeHost.UseDoneSeq = 10; + var sw = System.Diagnostics.Stopwatch.StartNew(); + r.B.MarkKitUsed(); + FakeHost.UseDone(0); // the kit's own answer (seq + 1), no result line + Check.True(r.B.KitPending(), "answered just now: the line could still be in flight"); + SleepUntil(sw, 550); + Check.True(r.B.KitPending(), "550 ms after the answer: waiting"); + SleepUntil(sw, 850); + Check.False(r.B.KitPending(), "700 ms after a UseDone(0) with no line: none is coming, let go"); + Check.True(FakeHost.Logs.Any(l => l.Contains("was answered (UseDone) with no result line", StringComparison.Ordinal)), "logged"); + + // Not the kit's own answer: two UseDones since the send (another action's, then one more). + var o = new Rig(); + FakeHost.UseDoneSeq = 20; + var sw2 = System.Diagnostics.Stopwatch.StartNew(); + o.B.MarkKitUsed(); + FakeHost.UseDone(0); + FakeHost.UseDone(0); + Check.True(o.B.KitPending(), "seq + 2 is not the kit's answer"); + SleepUntil(sw2, 850); + Check.True(o.B.KitPending(), "850 ms: still waiting (not taken as answered)"); + + // A UseDone(0) while a motion plays (the heal motion of this kit; the UseDone was another action's). + var m = new Rig(); + FakeHost.UseDoneSeq = 30; + var sw3 = System.Diagnostics.Stopwatch.StartNew(); + m.B.MarkKitUsed(); + FakeHost.UseDone(0); + FakeHost.CastBusy = 1; + Check.True(m.B.KitPending(), "answered, the motion playing: waiting"); + SleepUntil(sw3, 900); + Check.True(m.B.KitPending(), "900 ms, the motion still playing: still waiting for the line"); + FakeHost.CastBusy = 0; + Check.False(m.B.KitPending(), "the motion over, no line: let go"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs new file mode 100644 index 0000000..51f4dbc --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs @@ -0,0 +1,339 @@ +using System; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The Buffing hold: health under Heal At held the +// arbiter on Buffing for 17 s with no heal landing (a used-up kit re-sent), the character stopped +// attacking the boss and died. In a fight, 6 s under a heal line with no heal landing now hands combat +// the tick for 5 s (BuffManager.HealHold.cs). +internal static class HealHoldTests +{ + private const uint Player = 0x500000B6; + private const uint ListedKit = 0x80088BDA; // the stack the Consumables rule was added from + private const uint Kit1 = 0x80073C1B; + private const uint Kit2 = 0x80073C1A; + private const string KitName = "Treated Healing Kit"; + + public static void Register(Runner r) + { + r.Add("heal hold: 6 s under a heal line with no heal landing hands combat the tick for 5 s; a heal landing holds it again", HealHoldReleases); + r.Add("heal hold: while combat has the tick a heal makes no stance change or wand swap; a caster in Magic still casts", HealHoldNoStanceChange); + r.Add("heal hold: a macro stop resets the hold; the first heartbeat after a restart in a fight does not release", HealHoldResetsOnMacroStop); + r.Add("heal hold: no release at 6 s while a kit in flight is animating; a kit that never animates still releases", HealHoldWaitsForAnimatingKit); + r.Add("heal hold: no release at 6 s while a wand wield is in flight; released once it is done", HealHoldWaitsForWield); + r.Add("heal hold: while combat has the tick, Kit Min Success is computed in the current stance, not peace", ReleasedKitChanceNotPeace); + r.Add("heal hold: the release logs its start, its end and the first wand swap it refuses (one line each)", HealHoldLogLines); + r.Add("heal hold: while combat has the tick, under Emergency Heal At the kit despite Kit Min Success still goes", ReleasedEmergencyLastResortKit); + } + + private static void HealHoldLogLines() + { + var b = MeleeSpellRig(out var v, out var setNow); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + setNow(t0); b.OnHeartbeat(); + setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat(); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[RynthAi] Vitals: heal hold started", StringComparison.Ordinal)), 1, "the start is logged once"); + setNow(t0.AddMilliseconds(6500)); b.CheckVitals(); + setNow(t0.AddMilliseconds(7000)); b.CheckVitals(); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("heal hold: no wand swap for Heal Self while combat has the tick", StringComparison.Ordinal)), 1, + "the refused wand swap is logged once per release: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("heal hold", StringComparison.Ordinal)))); + setNow(t0.AddMilliseconds(11_000)); b.OnHeartbeat(); + Check.True(FakeHost.Logs.Any(l => l.Contains("heal hold ended (its 5 s are over", StringComparison.Ordinal)), "the window's end is logged"); + setNow(t0.AddMilliseconds(17_000)); b.OnHeartbeat(); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("heal hold started", StringComparison.Ordinal)), 2, "the second release is logged"); + v.CurrentHealth = 90; + setNow(t0.AddMilliseconds(18_000)); b.OnHeartbeat(); + Check.True(FakeHost.Logs.Any(l => l.Contains("heal hold ended (health 90% is over the heal lines)", StringComparison.Ordinal)), "health back over the line ends it, logged"); + } + + // The safety floor: a release refuses stance changes, never the last-resort kit. + private static void ReleasedEmergencyLastResortKit() + { + var b = KitRig(); + FakeHost.Skills[(Player, 21)] = (10, 2); // Healing low: the kit's chance is under any real Kit Min Success + RigSettings.KitMinSuccessPct = 95; + RigSettings.EmergencyHealAt = 30; + SetHealth(b, 20); + var t0 = new DateTime(2026, 1, 1, 12, 1, 3); + b.Clock = () => t0; + typeof(BuffManager).GetField("_hhReleasedUntil", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(b, t0.AddMilliseconds(5000)); // combat has the tick + Check.True(b.HealHoldReleased, "the rig: released"); + Check.True(b.CheckVitals(), "20% under Emergency Heal At 30%: the vitals act"); + Check.Eq(FakeHost.UsesOn.Count, 1, "a kit goes out"); + Check.True(FakeHost.Logs.Any(l => l.Contains("despite Kit Min Success", StringComparison.Ordinal)), + "the kit despite Kit Min Success (logged): " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("Vitals", StringComparison.Ordinal)))); + } + + private static BuffManager MeleeSpellRig(out PlayerVitalsCache v, out Func setNow, int mode = CombatMode.Melee, + bool monsterInRange = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.CombatModeValue = mode; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 75, TopOffHP = 75, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false, + }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 48, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + b.SetCharacterSkills(skills); + b.MarkLiveBuffsReadyForTests(); + b.InCombatOverride = () => monsterInRange; // the boss within Monster Range + DateTime now = new DateTime(2026, 1, 1, 12, 0, 50); + b.Clock = () => now; + setNow = t => now = t; + RigSettings = s; + return b; + } + + /// The settings of the last rig built (MeleeSpellRig or KitRig). + private static LegacyUiSettings RigSettings = new(); + + /// A melee character with two healing kits and Life Magic untrained: kits are the only heal. + private static BuffManager KitRig(int mode = CombatMode.Melee, bool modeCalls = false) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = modeCalls; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.CombatModeValue = mode; + FakeHost.Names[Kit1] = KitName; + FakeHost.Names[Kit2] = KitName; + // Life Magic untrained (a read, not the capable stub): kits are the only heal, no Heal Self. + FakeHost.Skills[(Player, 33)] = (10, 1); + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false, + KitMinSuccessPct = 0, PeaceModeForKits = false, + }; + s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)ListedKit), Name = KitName, Type = "HealthKit" }); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + b.SetCharacterSkills(skills); + b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { Kit1, Kit2 })); + RigSettings = s; + return b; + } + + private static void SetHealth(BuffManager b, int hp) + { + var f = typeof(BuffManager).GetField("_vitals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + ((PlayerVitalsCache)f.GetValue(b)!).CurrentHealth = (uint)hp; + } + + // HeartbeatCore returns before TickHealHold while the macro is off, so the hold's timer must be reset + // there: a restart in a fight (the HP failsafe's recall turning it back on, too) released at once. + private static void HealHoldResetsOnMacroStop() + { + var b = MeleeSpellRig(out _, out var setNow, CombatMode.Magic); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + setNow(t0); b.OnHeartbeat(); + setNow(t0.AddMilliseconds(5000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5 s under the line: held"); + RigSettings.IsMacroRunning = false; + setNow(t0.AddMilliseconds(10_000)); b.OnHeartbeat(); + RigSettings.IsMacroRunning = true; + setNow(t0.AddMilliseconds(15_000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "macro back on in the fight: the vitals hold the tick (a fresh count)"); + Check.Eq(b.HealHoldReleases, 0, "no release on the first heartbeat after the restart"); + setNow(t0.AddMilliseconds(20_900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s after the restart: still held"); + setNow(t0.AddMilliseconds(21_000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s after the restart with nothing landing: released"); + } + + private static void HealHoldReleases() + { + // A caster in Magic stance: its Heal Self goes out with no stance step, so nothing but the + // hold itself (no wand-flip backoff) decides what WantsVitalRecharge reads. + var b = MeleeSpellRig(out var v, out var setNow, CombatMode.Magic); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + setNow(t0); + b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "48% under Heal At 75%: vitals want the tick"); + setNow(t0.AddMilliseconds(5900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s with no heal landing: still held"); + setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s with no heal landing: combat gets the tick"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no heal landed", StringComparison.Ordinal)), "logged"); + setNow(t0.AddMilliseconds(10_900)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "4.9 s into the 5 s window: combat still has it"); + setNow(t0.AddMilliseconds(11_000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "the window over: vitals hold the tick again"); + setNow(t0.AddMilliseconds(16_900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s into the next hold: held"); + setNow(t0.AddMilliseconds(17_000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s again with nothing landing: released again"); + + // A heal landing (health up 3 points or more) ends a release and restarts the count. + v.CurrentHealth = 52; + setNow(t0.AddMilliseconds(18_000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "a heal landed (48 -> 52): the vitals hold the tick again"); + v.CurrentHealth = 50; + setNow(t0.AddMilliseconds(23_900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s after the landing: held"); + setNow(t0.AddMilliseconds(24_000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s after it with nothing more: released"); + + // Over the line ends the episode; a new dip starts a fresh 6 s count. + v.CurrentHealth = 90; + setNow(t0.AddMilliseconds(25_000)); b.OnHeartbeat(); + v.CurrentHealth = 40; + setNow(t0.AddMilliseconds(26_000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "a new dip: held from the start"); + setNow(t0.AddMilliseconds(31_900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s into the new dip: held (the count restarted)"); + setNow(t0.AddMilliseconds(32_000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s into the new dip: released"); + + // No monster within Monster Range: nothing to fight, the vitals keep the tick. + var q = MeleeSpellRig(out _, out var setNowQ, CombatMode.Magic, monsterInRange: false); + setNowQ(t0); q.OnHeartbeat(); + setNowQ(t0.AddMilliseconds(20_000)); q.OnHeartbeat(); + Check.True(q.WantsVitalRecharge, "no monster in range: 20 s with no heal landing, still held (nav and loot don't get it)"); + Check.Eq(q.HealHoldReleases, 0, "never released"); + } + + private static void HealHoldNoStanceChange() + { + var b = MeleeSpellRig(out _, out var setNow); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + setNow(t0); + Check.True(b.CheckVitals(), "control: melee, no kit: Heal Self starts its stance change"); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "control: Magic mode was asked for"); + b.OnHeartbeat(); + int before = FakeHost.CombatModeRequests.Count; + int wieldsBefore = FakeHost.Wields.Count; + // The heartbeat that releases the hold runs the vitals step too (the flip's 2 s backoff is over). + setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "the rig: combat has the tick"); + setNow(t0.AddMilliseconds(7000)); + b.CheckVitals(); + Check.Eq(FakeHost.CombatModeRequests.Count, before, "while combat has the tick: no stance change for Heal Self"); + Check.Eq(FakeHost.Wields.Count, wieldsBefore, "and no wield"); + + // A caster already in Magic stance needs no change: its Heal Self still goes. + var c = MeleeSpellRig(out _, out var setNowC, CombatMode.Magic); + setNowC(t0); + c.OnHeartbeat(); + setNowC(t0.AddMilliseconds(6000)); c.OnHeartbeat(); + Check.False(c.WantsVitalRecharge, "caster rig: combat has the tick"); + int casts = FakeHost.Casts.Count; + c.CheckVitals(); + Check.True(FakeHost.Casts.Count > casts, "caster in Magic: Heal Self is cast while combat has the tick"); + + // A caster in Magic stance with Use Kits in Magic Mode and Peace Mode for Kits: the kit's peace + // switch is a stance change too. Control first (not released): it goes out. + foreach (bool released in new[] { false, true }) + { + var k = KitRig(CombatMode.Magic, modeCalls: true); + RigSettings.UseKitsInMagicMode = true; + RigSettings.PeaceModeForKits = true; + var t1 = new DateTime(2026, 1, 1, 12, 1, 0); + k.Clock = () => t1; + if (released) + typeof(BuffManager).GetField("_hhReleasedUntil", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(k, t1.AddMilliseconds(5000)); + k.CheckVitals(); + int peace = FakeHost.CombatModeRequests.Count(m => m == CombatMode.NonCombat); + if (released) + { + Check.Eq(peace, 0, "Magic stance, combat has the tick: no peace switch for the kit"); + Check.Eq(FakeHost.UsesOn.Count, 1, "the kit is used in the stance it is in"); + } + else + Check.Eq(peace, 1, "control, Magic stance, not released: the kit's peace switch goes out"); + } + } + + // A release must not cut off a heal the server is already playing. A kit that has animated + // (heal grace's NoteKitProgress), or a wand wield in flight, holds the release back; a removed kit + // never animates, so it still releases. + private static void HealHoldWaitsForAnimatingKit() + { + foreach (bool animating in new[] { true, false }) + { + string how = animating ? "animating kit" : "kit with no motion"; + var b = KitRig(); + b.InCombatOverride = () => true; + var t0 = new DateTime(2026, 1, 1, 12, 0, 58); + DateTime now = t0; + b.Clock = () => now; + FakeHost.UseDoneSeq = 10; + b.OnHeartbeat(); // the hold starts counting + if (FakeHost.UsesOn.Count == 0) b.CheckVitals(); + Check.Eq(FakeHost.UsesOn.Count, 1, $"{how}: the kit is in flight"); + FakeHost.CastBusy = animating ? 1 : 0; + now = t0.AddMilliseconds(6000); + b.OnHeartbeat(); + FakeHost.CastBusy = 0; + if (animating) + { + Check.Eq(b.HealHoldReleases, 0, "6 s, the kit's heal motion playing: no release"); + Check.True(b.WantsVitalRecharge, "the vitals keep the tick for it"); + } + else + Check.Eq(b.HealHoldReleases, 1, "6 s, a kit the server never animated (the live failure): released"); + } + } + + private static void HealHoldWaitsForWield() + { + var b = MeleeSpellRig(out _, out var setNow); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + var pending = typeof(BuffManager).GetField("_pendingWieldId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + setNow(t0); b.OnHeartbeat(); + pending.SetValue(b, unchecked((int)0x80084C1E)); // the wand's wield sent, the server not done yet + setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat(); + Check.Eq(b.HealHoldReleases, 0, "6 s, a wand wield in flight: no release"); + Check.True(b.WantsVitalRecharge, "the vitals keep the tick"); + pending.SetValue(b, 0); + setNow(t0.AddMilliseconds(6100)); b.OnHeartbeat(); + Check.Eq(b.HealHoldReleases, 1, "the wield done, still nothing landed: released"); + } + + private static void ReleasedKitChanceNotPeace() + { + var b = KitRig(); + FakeHost.Skills[(Player, 21)] = (75, 2); // Healing (STypeSkill 21), trained + RigSettings.PeaceModeForKits = true; + RigSettings.KitMinSuccessPct = 30; + SetHealth(b, 34); // 66 missing + var t0 = new DateTime(2026, 1, 1, 12, 1, 3); + b.Clock = () => t0; + typeof(BuffManager).GetField("_hhReleasedUntil", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(b, t0.AddMilliseconds(5000)); // combat has the tick + Check.True(b.HealHoldReleased, "the rig: released"); + b.CheckVitals(); + // (75 + 25) x 1.1 = 110 against 66 x 2 x 1.1 = 145 in melee: 25%, under 30. In peace it would be + // 66 x 2 = 132: 34%, over it. No peace switch goes out while released, so melee is the stance. + Check.True(FakeHost.Logs.Any(l => l.Contains("would work 25% of the time on 66 missing (skill 110 vs 145)", StringComparison.Ordinal)), + "the chance is the melee one: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("would work", StringComparison.Ordinal)))); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTextColorTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTextColorTests.cs new file mode 100644 index 0000000..dc9ffe2 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTextColorTests.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-11-05, a player asked to colour the item info lines (AutoID on select, /ra iteminfo, ...) +// without changing their chat type: picking "allegiance" as the chat type for its colour also +// moved the lines to where allegiance lines go. Item Info's "Info text colour" asks the engine +// (SendPluginCommand "RynthCore.Chat" nextcolor, engine UI/Data/ChatOwnColors.cs) to draw the next +// line in that colour just before each line is written; the line keeps its chat type. Unset, the +// lines go out exactly as before. An engine without it answers "no" once and is not asked again. +internal static class ItemInfoTextColorTests +{ + private const uint Player = 0x50000E52; + private const uint Sword = 0x80266101; + private const uint ItemTypeMelee = 0x1; + private const string Target = "RynthCore.Chat"; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("item info colour: unset, the lines go out as before and nothing is asked", DefaultUnchanged); + r.Add("item info colour: set, each line asks for it just before it is written, its chat type unchanged", ColouredLines); + r.Add("item info colour: an engine without it is asked once, then the lines go out plain", OlderEngine); + r.Add("item info colour: the Test button and /ra iteminfo me use it too", TestButtonAndSelf); + r.Add("item info colour: saved with the profile, reset, sanitized, the settings map", SettingsRoundTrip); + r.Add("item info colour: /ra iteminfo color always answers", Command); + } + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new(); + + public Bot(RynthCoreHost host) + { + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true); // a stand-in with its profile in memory + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + Set("_objectCache", cache); + Set("_playerId", Player); + cache.OnCreateObject(Sword); + cache.OnCreateObject(Player); + cache.Tick(); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public void Call(string method, params object[] args) => typeof(RynthAiPlugin).GetMethod(method, Any)!.Invoke(P, args); + public void Print() => Call("PrintItemInfo", unchecked((int)Sword), true); + public void Cmd(params string[] words) => Call("HandleItemInfoCommand", new object[] { new[] { "ra", "iteminfo" }.Concat(words).ToArray() }); + } + + /// A gold long sword, identified, with a spell: pet-style output is several lines. + private static Bot World(bool pluginCommands = true, bool delivered = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData + FakeHost.PluginCommandCalls = pluginCommands; + FakeHost.PluginCommandDelivered = delivered; + FakeHost.Names[Player] = "Colour Tester"; + FakeHost.Names[Sword] = "Long Sword"; + FakeHost.ItemTypes[Sword] = ItemTypeMelee; + FakeHost.Containers[Sword] = Player; + foreach (var (k, v) in new (uint, int)[] { (1, (int)ItemTypeMelee), (19, 9000), (5, 300), (131, 60), (105, 6), (353, 2), (45, 1), (204, 0) }) + FakeHost.Ints[(Sword, k)] = v; + FakeHost.SpellIds[Sword] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") }; + FakeHost.Appraised.Add(Sword); + return new Bot(FakeHost.Create(Player)); + } + + private static List ItemLines() => + Enumerable.Range(0, FakeHost.Chat.Count).Where(i => FakeHost.Chat[i].StartsWith("[RynthAi Item] ", StringComparison.Ordinal)).ToList(); + + private static List Asks() => + Enumerable.Range(0, FakeHost.PluginCommands.Count).Where(i => FakeHost.PluginCommands[i].Plugin == Target).ToList(); + + private static void DefaultUnchanged() + { + var fresh = new MagItemInfoSettings(); + Check.Eq(fresh.TextColor, "", "Info text colour: the chat type's own colour by default"); + + Bot bot = World(); + bot.S.ItemInfoSettings.DetailChatType = 7; + bot.Print(); + List lines = ItemLines(); + Check.True(lines.Count >= 2, "pet-style: a name line and detail lines: " + string.Join(" | ", FakeHost.Chat)); + Check.Eq(Asks().Count, 0, "no colour asked for"); + Check.Eq(FakeHost.PluginCommands.Count, 0, "nothing sent to the engine at all"); + if (lines.Count >= 2) + { + Check.Eq(FakeHost.ChatTypes[lines[0]], 1, "the name line in the Item Info chat type (1)"); + Check.True(lines.Skip(1).All(i => FakeHost.ChatTypes[i] == 7), "detail lines in theirs (7)"); + Check.True(FakeHost.Chat[lines[0]].StartsWith("[RynthAi Item] Gold Long Sword", StringComparison.Ordinal), "the text: " + FakeHost.Chat[lines[0]]); + } + } + + private static void ColouredLines() + { + Bot bot = World(); + bot.S.ItemInfoSettings.DetailChatType = 7; + bot.Print(); + List plain = ItemLines().Select(i => FakeHost.Chat[i]).ToList(); + List plainTypes = ItemLines().Select(i => FakeHost.ChatTypes[i]).ToList(); + + bot = World(); + bot.S.ItemInfoSettings.DetailChatType = 7; + bot.S.ItemInfoSettings.TextColor = "#EE921E"; + bot.Print(); + List lines = ItemLines(); + List asks = Asks(); + Check.Eq(lines.Count, plain.Count, "as many lines as without a colour"); + Check.True(lines.Select(i => FakeHost.Chat[i]).SequenceEqual(plain), "the same text"); + Check.True(lines.Select(i => FakeHost.ChatTypes[i]).SequenceEqual(plainTypes), "the same chat types (the same tab and AC chat window)"); + Check.Eq(asks.Count, lines.Count, "one colour asked for per line"); + Check.True(asks.All(i => FakeHost.PluginCommands[i] == (Target, "nextcolor", "#EE921E")), "nextcolor #EE921E: " + string.Join(" | ", FakeHost.PluginCommands)); + Check.True(asks.Select(i => FakeHost.PluginCommandChatCounts[i]).SequenceEqual(lines), + "each asked for just before its own line (nothing written in between)"); + } + + private static void OlderEngine() + { + Bot bot = World(delivered: false); // an engine from before 2026-11-05: no "RynthCore.Chat" + bot.S.ItemInfoSettings.TextColor = "#EE921E"; + bot.Print(); + bot.Print(); + Check.Eq(Asks().Count, 1, "asked once"); + Check.Eq(ItemLines().Count % 2, 0, "every line of both prints written"); + Check.True(ItemLines().Count >= 4, "in its chat type's colour: " + string.Join(" | ", FakeHost.Chat)); + + bot = World(pluginCommands: false); // an engine before API v64 + bot.S.ItemInfoSettings.TextColor = "#EE921E"; + bot.Print(); + Check.True(ItemLines().Count >= 2, "no SendPluginCommand at all: the lines still go out"); + } + + private static void TestButtonAndSelf() + { + Bot bot = World(); + bot.S.ItemInfoSettings.TextColor = "#3FBFFF"; + bot.Call("TestItemInfoChatType", 18); + Check.Eq(FakeHost.Chat.LastOrDefault(), "[RynthAi Item] Item info chat test (type 18, colour #3FBFFF)", "the Test line names both"); + Check.Eq(FakeHost.ChatTypes.LastOrDefault(), 18, "in the chat type tested"); + Check.Eq(Asks().Count, 1, "in the colour"); + + bot.Call("PrintSelfRatings", Player, true); + int selfLines = ItemLines().Count - 1; + Check.True(selfLines >= 1, "your ratings print: " + string.Join(" | ", FakeHost.Chat)); + Check.Eq(Asks().Count, 1 + selfLines, "each ratings line in the colour too"); + } + + private static void SettingsRoundTrip() + { + // Profile: save, load (CopySettings), save again unchanged. + var saved = new LegacyUiSettings(); + saved.ItemInfoSettings.TextColor = "#EE921E"; + string json = JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings); + var live = new LegacyUiSettings(); + typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)! + .Invoke(null, new object[] { JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!, live }); + Check.Eq(live.ItemInfoSettings.TextColor, "#EE921E", "the colour survives a save and load"); + Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings), json, "and saves back unchanged"); + + // A profile from before the setting: the chat type's own colour. + var doc = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject(); + var info = doc[doc.Select(kv => kv.Key).Single(k => k.Equals("ItemInfoSettings", StringComparison.OrdinalIgnoreCase))]!.AsObject(); + string? key = info.Select(kv => kv.Key).SingleOrDefault(k => k.Equals("TextColor", StringComparison.OrdinalIgnoreCase)); + Check.True(key != null, "the field is in the profile JSON"); + if (key != null) info.Remove(key); + var old = new LegacyUiSettings(); + typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)! + .Invoke(null, new object[] { JsonSerializer.Deserialize(doc.ToJsonString(), RynthAiJsonContext.Default.LegacyUiSettings)!, old }); + Check.Eq(old.ItemInfoSettings.TextColor, "", "a profile without it: the chat type's colour"); + + // Sanitize tidies a hand-edited value; Reset all to defaults clears it. + var s = new MagItemInfoSettings { TextColor = " ee921e " }; + s.Sanitize(); + Check.Eq(s.TextColor, "#EE921E", "a code without # is tidied"); + s.TextColor = "orange"; s.Sanitize(); + Check.Eq(s.TextColor, "", "a word that isn't a code: the chat type's colour"); + s.TextColor = "#12345"; s.Sanitize(); + Check.Eq(s.TextColor, "", "a short code: cleared"); + s.TextColor = "#3FBFFF"; + s.ResetToDefaults(); + Check.Eq(s.TextColor, "", "reset: the chat type's colour"); + + // The named colours are codes; the first is the default. + Check.Eq(MagItemInfoCatalog.TextColors[0].Color, "", "the first choice is the chat type's own colour"); + Check.True(MagItemInfoCatalog.TextColors.Skip(1).All(c => MagItemInfoCatalog.NormalizeTextColor(c.Color) == c.Color), "every named colour is a #RRGGBB code"); + Check.Eq(MagItemInfoCatalog.TextColors.Select(c => c.Word).Distinct(StringComparer.OrdinalIgnoreCase).Count(), MagItemInfoCatalog.TextColors.Length, "names are unique"); + Check.Eq(MagItemInfoCatalog.TextColorFromRgb(MagItemInfoCatalog.TextColorRgb("#EE921E")), "#EE921E", "the colour picker round-trips"); + + // The settings map (metas: rasetsetting / ragetsetting). + var mapSettings = new LegacyUiSettings(); + var e = ExpressionTests.Engine(settings: mapSettings); + e.Evaluate("rasetsetting[ItemInfoTextColor, allegiance]"); + Check.Eq(mapSettings.ItemInfoSettings.TextColor, "#EE921E", "set by name through the map"); + Check.Eq(e.Evaluate("ragetsetting[ItemInfoTextColor]"), "#EE921E", "map reads it"); + e.Evaluate("rasetsetting[ItemInfoTextColor, default]"); + Check.Eq(mapSettings.ItemInfoSettings.TextColor, "", "default through the map"); + } + + private static void Command() + { + Bot bot = World(); + bot.Cmd("color", "allegiance"); + Check.Eq(bot.S.ItemInfoSettings.TextColor, "#EE921E", "/ra iteminfo color allegiance"); + Check.True(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi] Item info text colour: Allegiance (orange) #EE921E in RynthCore's chat", StringComparison.Ordinal)), + "replies with the colour: " + string.Join(" | ", FakeHost.Chat)); + + FakeHost.Chat.Clear(); + bot.Cmd("colour", "#12ab34"); + Check.Eq(bot.S.ItemInfoSettings.TextColor, "#12AB34", "/ra iteminfo colour #12ab34"); + Check.True(FakeHost.Chat.Any(c => c.Contains("text colour: #12AB34")), "replies: " + string.Join(" | ", FakeHost.Chat)); + + FakeHost.Chat.Clear(); + bot.Cmd("color"); + Check.Eq(bot.S.ItemInfoSettings.TextColor, "#12AB34", "no argument changes nothing"); + Check.True(FakeHost.Chat.Any(c => c.Contains("text colour: #12AB34")), "and says the colour now"); + + FakeHost.Chat.Clear(); + bot.Cmd("color", "plaid"); + Check.Eq(bot.S.ItemInfoSettings.TextColor, "#12AB34", "a bad word changes nothing"); + Check.True(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi] Usage: /ra iteminfo color default|allegiance|", StringComparison.Ordinal)), + "and gets the usage: " + string.Join(" | ", FakeHost.Chat)); + + FakeHost.Chat.Clear(); + bot.Cmd("color", "default"); + Check.Eq(bot.S.ItemInfoSettings.TextColor, "", "/ra iteminfo color default"); + Check.True(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi] Item info text colour: the chat type's own colour.", StringComparison.Ordinal)), + "replies: " + string.Join(" | ", FakeHost.Chat)); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs index 2a2c49e..f84be43 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; +using System.Text.Json; using System.Threading; using RynthCore.Loot; using RynthCore.Plugin.RynthAi; @@ -38,6 +39,8 @@ internal static class ItemToolTests r.Add("chest looter: combat/busy holds every send, then the run stops after the cap", ChestHoldsThenStops); r.Add("chest looter: can't start without a chest, a key, a loaded near chest; Stop always works and ends the loot session", ChestStartRefusalsAndStop); r.Add("chest looter: a key that never runs out is cut off at MaxCycles", ChestMaxCycles); + r.Add("chest looter: the re-lock wait is the 'Chest re-lock wait (s)' setting, clamped 5..600; a change applies to the wait running", ChestRelockSetting); + r.Add("chest looter: after a short re-lock wait the asks follow it (never under 5 s apart), bounded; a long wait still ends when the chest reads locked", ChestRelockProbes); // Quick give state machine r.Add("quick give: one give at a time, each after the last landed, paced; done when none is left", GiveOneAtATime); r.Add("quick give: a refused item is left out; three refusals in a row stop it", GiveRefusals); @@ -49,6 +52,8 @@ internal static class ItemToolTests r.Add("item tool: Quick give hands over exactly the picked item to the picked NPC, never worn gear or other names", PluginQuickGive); r.Add("item tool: Quick give starts only from the panel or a typed line, never from a meta, a script or a remote line; stop works from anywhere", PluginGiveTrust); r.Add("item tool: Quick give targets are players or NPCs only", PluginGiveTargets); + r.Add("item tool: /ra itemtool relock sets, clamps and saves the re-lock wait and always answers with the value; refused before the profile loads", PluginRelockCommand); + r.Add("item tool: the re-lock wait is saved in the profile and loaded (old profiles: 125 s), sent to the engine and left alone by an engine without it", RelockSavedAndLoaded); } // ── Fake environments ──────────────────────────────────────────────────── @@ -420,6 +425,92 @@ internal static class ItemToolTests Check.True(said.Contains($"{ChestKeyLooter.MaxCycles} cycles"), "says why: " + said.Substring(Math.Max(0, said.Length - 200))); } + /// Runs one cycle on two same-named keys and returns how long after the open the second key went. + private static long NextKeyAfterOpen(int relockSec, Action? duringWait = null) + { + var env = NewChest(out var ck); + env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12); + Serve(env, ck); + env.AutoLootMs = 1000; + ck.RelockWaitSec = relockSec; + ck.Start(out _); + env.Run(5000, () => env.LootStarts > 0); + env.Run(3000, () => ck.State == ChestKeyLooter.Phase.Waiting); + Check.Eq(ck.State, ChestKeyLooter.Phase.Waiting, $"waiting for the re-lock ({relockSec} s)"); + long openedAt = env.OpenedAt; + int sent = env.Sent.Count; + duringWait?.Invoke(env, ck); + env.Run(700_000, () => env.Sent.Count > sent); + Check.True(env.Sent.Count > sent, $"the next key goes after the wait ({relockSec} s)"); + return env.T - openedAt; + } + + private static void ChestRelockSetting() + { + // The setting, clamped. + NewChest(out var c0); + Check.Eq(c0.RelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "default 125 s (the wait before the setting)"); + Check.Eq(ChestKeyLooter.RegenWaitMs, 125_000L, "the default is the old wait"); + c0.RelockWaitSec = 1; + Check.Eq(c0.RelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "1 s is raised to the least, 5 s"); + c0.RelockWaitSec = -40; + Check.Eq(c0.RelockWaitSec, 5, "a negative value too"); + c0.RelockWaitSec = 100_000; + Check.Eq(c0.RelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "100000 s is cut to the most, 600 s"); + Check.Eq(ChestKeyLooter.ClampRelockWaitSec(45), 45, "in range: kept"); + + // The wait uses it: the next key goes that long after the open, not 125 s. + long at = NextKeyAfterOpen(20); + Check.True(at >= 20_000 && at < 22_000, $"20 s: the next key ~20 s after the open ({at} ms)"); + at = NextKeyAfterOpen(ChestKeyLooter.DefaultRelockWaitSec); + Check.True(at >= 125_000 && at < 127_000, $"default: ~125 s after the open, as before ({at} ms)"); + at = NextKeyAfterOpen(5); + Check.True(at >= 5_000 && at < 7_000, $"5 s: ~5 s after the open ({at} ms)"); + at = NextKeyAfterOpen(1); + Check.True(at >= 5_000, $"1 s is used as 5 s ({at} ms)"); + + // Changed while the wait runs (the panel, mid-run): the running wait follows. + at = NextKeyAfterOpen(ChestKeyLooter.DefaultRelockWaitSec, (env, ck) => { env.Run(10_000); ck.RelockWaitSec = 30; }); + Check.True(at >= 30_000 && at < 32_000, $"125 -> 30 s during the wait: the key goes ~30 s after the open ({at} ms)"); + at = NextKeyAfterOpen(20, (env, ck) => { env.Run(5_000); ck.RelockWaitSec = 60; }); + Check.True(at >= 60_000 && at < 62_000, $"20 -> 60 s during the wait: it waits the longer time ({at} ms)"); + } + + private static void ChestRelockProbes() + { + foreach (int sec in new[] { 20, 5, ChestKeyLooter.DefaultRelockWaitSec }) + { + var env = NewChest(out var ck); + env.Unlimited = true; + env.AutoLootMs = 1000; + ck.RelockWaitSec = sec; + bool unlocked = false; + var keyAt = new List(); + env.OnKey = _ => { keyAt.Add(env.T); return unlocked ? ChestKeyLooter.ErrLockAlreadyUnlocked : 0u; }; // the chest never re-locks + ck.Start(out _); + env.Run(3000, () => env.LootStarts > 0); + unlocked = true; + env.Run(2_000_000, () => !ck.Running); + Check.False(ck.Running, $"{sec} s: gave up on a chest that never re-locks"); + long every = Math.Clamp(sec * 1000L, ChestKeyLooter.MinProbeMs, ChestKeyLooter.ProbeMs); + int limit = (int)((ChestKeyLooter.MaxProbes * ChestKeyLooter.ProbeMs + every - 1) / every); + Check.Eq(ck.ProbeLimit, limit, $"{sec} s: the asks fit in {ChestKeyLooter.MaxProbes * ChestKeyLooter.ProbeMs / 1000} s"); + Check.Eq(keyAt.Count, 1 + limit + 1, $"{sec} s: bounded: the first use, the one after the wait, one per ask"); + for (int i = 2; i < keyAt.Count; i++) + Check.True(keyAt[i] - keyAt[i - 1] >= every, $"{sec} s: ask {i} came {keyAt[i] - keyAt[i - 1]} ms after the last (at least {every})"); + Check.True(keyAt.Zip(keyAt.Skip(1), (a, b) => b - a).All(d => d >= ChestKeyLooter.MinProbeMs), $"{sec} s: never two key uses under 5 s apart"); + Check.Eq(env.Sent.Count(s => s == "open"), 1, $"{sec} s: the empty chest is not opened again"); + Check.True(Said(env).Contains("hasn't re-locked"), $"{sec} s: says why: " + Said(env)); + } + Check.Eq(new ChestKeyLooter(new ChestEnv()).ProbeLimit, ChestKeyLooter.MaxProbes, "the default wait asks MaxProbes times, as before"); + + // A long wait still ends when the client reads the chest locked again (ACE's Reset sends Locked=true). + long at = NextKeyAfterOpen(ChestKeyLooter.MaxRelockWaitSec, (env, _) => env.Locked = true); + Check.True(at >= ChestKeyLooter.MinRelockMs && at < ChestKeyLooter.MinRelockMs + 2000, $"600 s, the chest reads locked: the key goes at ~{ChestKeyLooter.MinRelockMs / 1000} s ({at} ms)"); + at = NextKeyAfterOpen(ChestKeyLooter.MaxRelockWaitSec, (env, _) => env.Locked = false); + Check.True(at >= 600_000, $"600 s, the chest reads unlocked: the whole wait ({at} ms)"); + } + // ── Quick give state machine ───────────────────────────────────────────── private sealed class GiveEnv : IQuickGiveEnv @@ -914,4 +1005,103 @@ internal static class ItemToolTests Check.True(Chat().Contains("giving every 'Mana Mote'") && Chat().Contains("to Some Player"), "the start line names the player: " + Chat()); bot.Cmd("stop"); bot.Tick(); } + + // ── Chest re-lock wait (the setting) ───────────────────────────────────── + + private static void PluginRelockCommand() + { + BaseWorld(); + var bot = MakeBot("itemtool-relock.json"); + Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "a new profile: 125 s"); + + string Run(string words) + { + FakeHost.Chat.Clear(); + bot.Cmd(words); + bot.Tick(); + return Chat(); + } + + string said = Run("relock 30"); + Check.Eq(bot.S.ChestRelockWaitSec, 30, "relock 30 sets 30 s"); + Check.True(said.Contains("re-lock wait = 30 s"), "answers with the value now: " + said); + Check.Eq(bot.Get("_chestKey").RelockWaitSec, 30, "the looter has it"); + + said = Run("relock 2"); + Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "2 s is raised to 5 s"); + Check.True(said.Contains("re-lock wait = 5 s") && said.Contains("the least is 5 s"), "says it was clamped: " + said); + + said = Run("chest relock 9999"); + Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "'chest relock' works too; 9999 is cut to 600"); + Check.True(said.Contains("re-lock wait = 600 s") && said.Contains("the most is 600 s"), "says it was clamped: " + said); + + said = Run("relock 45s"); + Check.Eq(bot.S.ChestRelockWaitSec, 45, "'45s' is read as 45"); + + said = Run("relock soon"); + Check.Eq(bot.S.ChestRelockWaitSec, 45, "not a number: unchanged"); + Check.True(said.Contains("'soon' isn't a number") && said.Contains("still 45 s") && said.Contains("/ra itemtool relock "), "says why, the value and the usage: " + said); + + said = Run("relock"); + Check.True(said.Contains("re-lock wait = 45 s") && said.Contains("5-600 s, default 125"), "no number: says the value and the range: " + said); + Check.Eq(bot.S.ChestRelockWaitSec, 45, "and changes nothing"); + + // The panel reads it. + string json = bot.P.BuildItemToolJson(); + Check.True(json.Contains("\"relockSec\":45") && json.Contains("\"relockMin\":5") && json.Contains("\"relockMax\":600") && json.Contains("\"relockReady\":true"), + "the Item Tool panel's data carries the setting: " + json); + + // The wait the running looter uses is the setting's (the tick hands it over). + bot.S.ChestRelockWaitSec = 77; + bot.Tick(); + Check.Eq(bot.Get("_chestKey").RelockWaitSec, 77, "a change made elsewhere (meta, engine) reaches the looter on the next tick"); + + // Before the character's profile loads nothing lands on the defaults. + var dash = bot.Get("_dashboard"); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, false); + said = Run("relock 40"); + Check.Eq(bot.S.ChestRelockWaitSec, 77, "refused before the profile loads"); + Check.True(said.Contains("isn't loaded yet") && said.Contains("unchanged"), "and says so: " + said); + Check.True(bot.P.BuildItemToolJson().Contains("\"relockReady\":false"), "the panel greys the control meanwhile"); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true); + } + + private static void RelockSavedAndLoaded() + { + // The profile file (LegacyUiSettings as JSON): saved and read back; an older profile reads 125. + var saved = JsonSerializer.Deserialize( + JsonSerializer.Serialize(new LegacyUiSettings { ChestRelockWaitSec = 40 }, RynthAiJsonContext.Default.LegacyUiSettings), + RynthAiJsonContext.Default.LegacyUiSettings); + Check.Eq(saved?.ChestRelockWaitSec, 40, "40 s is saved and loaded"); + var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.Eq(old?.ChestRelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "a profile saved before the setting: 125 s"); + + // A profile load or switch (CopySettings, the hand-written field list) copies it, clamped. + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { saved!, dst }); + Check.Eq(dst.ChestRelockWaitSec, 40, "a profile with 40 s loads 40 s"); + copy.Invoke(null, new object[] { old!, dst }); + Check.Eq(dst.ChestRelockWaitSec, 125, "an old profile loads 125 s"); + var edited = JsonSerializer.Deserialize("{\"ChestRelockWaitSec\":0}", RynthAiJsonContext.Default.LegacyUiSettings)!; + copy.Invoke(null, new object[] { edited, dst }); + Check.Eq(dst.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "a hand-edited 0 loads as 5 s"); + + // The engine's settings payload: carries it; an engine that has no row for it leaves it alone. + var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(payload != null && payload.ChestRelockWaitSec == null, "an engine's payload without it has no value"); + var s = new LegacyUiSettings { ChestRelockWaitSec = 33 }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true); // a stand-in with its profile in memory + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); // BuildSettingsJson reads its crafting state + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.Eq(sent?.ChestRelockWaitSec, 33, "sent to the engine"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.Eq(s.ChestRelockWaitSec, 33, "a save without the field leaves it"); + dash.ApplySettingsJson("{\"ChestRelockWaitSec\":9999}"); + Check.Eq(s.ChestRelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "a save with it is clamped (600 s)"); + dash.ApplySettingsJson("{\"ChestRelockWaitSec\":20}"); + Check.Eq(s.ChestRelockWaitSec, 20, "and applied"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/KitUsedUpTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/KitUsedUpTests.cs new file mode 100644 index 0000000..71736e7 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/KitUsedUpTests.cs @@ -0,0 +1,217 @@ +using System; +using System.Linq; +using System.Threading; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// A kit its own result line calls used up ("... Your Treated Healing Kit is used up.", ACE +// Healer.DoHealing) is skipped by every kit pick (BuffManager.KitUsedUp.cs). The picks read the client's +// live pack walk, which drops the removed kit, but reuses a walk for up to 1 s, and the next kit goes out +// 700 ms after the line: inside that reuse the used-up kit was picked again (checked on main: the same +// rig picks Kit1). These rigs freeze the walk's clock (WorldObjectCache.WalkClock), so the walk is never +// refreshed and only the skip can keep the used-up kit out. Without GetContainerContents there is no walk +// at all, and the skip does not end. +internal static class KitUsedUpTests +{ + private const uint Player = 0x500000C1; + private const uint GoneListed = 0x80088BDA; // the stack the Consumables rule was added from, long gone + private const uint Kit1 = 0x80073C1B; + private const uint Kit2 = 0x80073C1A; + private const uint Gem = 0x80073C19; // something else carried, so the walk is never empty + private const uint StamKit1 = 0x80073C18, StamKit2 = 0x80073C17; + private const string KitName = "Treated Healing Kit"; + + public static void Register(Runner r) + { + r.Add("kit used up: its result line skips that kit inside the pack walk's reuse; the next kit goes (rule and pack picks)", UsedUpLineNextKit); + r.Add("kit used up: a line with uses left keeps the kit (control)", UsesLeftKeepsKit); + r.Add("kit used up: a line naming another kit marks nothing; naming the kit in flight marks it", OtherKitLineIgnored); + r.Add("kit used up: with the pack walk the skip ends after 3 s (the BuffManager clock)", SkipExpires); + r.Add("kit used up: without GetContainerContents the skip does not end (no walk ever drops the kit)", NoWalkSkipLasts); + r.Add("kit used up: a stamina kit's used-up line skips it for the next stamina kit", StaminaKitUsedUp); + } + + private static BuffManager Rig(bool withRule, string kit1Name = KitName, bool walk = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.ContentsCalls = walk; // the client's pack walk (GetContainerContents) + FakeHost.CombatModeValue = CombatMode.Melee; + FakeHost.Names[Kit1] = kit1Name; + FakeHost.Names[Kit2] = KitName; + FakeHost.Names[Gem] = "Sapphire"; + FakeHost.Containers[Kit1] = Player; + FakeHost.Containers[Kit2] = Player; + FakeHost.Containers[Gem] = Player; + FakeHost.Skills[(Player, 33)] = (10, 1); // Life Magic untrained: kits are the only heal + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false, + KitMinSuccessPct = 0, PeaceModeForKits = false, + }; + if (withRule) + s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)GoneListed), Name = KitName, Type = "HealthKit" }); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + b.SetCharacterSkills(skills); + b.SetWorldObjectCache(Frozen(FakeHost.MakeCache(host, Player, new[] { Kit1, Kit2, Gem }))); + return b; + } + + /// The walk's reuse clock stopped: the first walk is reused for the whole test. + private static WorldObjectCache Frozen(WorldObjectCache cache) + { + var frozen = new DateTime(2026, 1, 1, 12, 0, 0); + cache.WalkClock = () => frozen; + return cache; + } + + private static uint LastKit() => FakeHost.UsesOn.Count == 0 ? 0 : FakeHost.UsesOn[^1].Source; + + /// The server removed the kit: the client deletes it (no pack, no name); the cache never hears. + private static void Gone(uint id) { FakeHost.Containers.Remove(id); FakeHost.Names.Remove(id); } + + /// The kit's result line, then past KitLandGraceMs (real clock): the kit wait ends. + private static void ResultLine(BuffManager b, string line) + { + b.OnChatWindowText(line, 0); + Thread.Sleep(750); + Check.False(b.KitPending(), "the result line and 700 ms: the kit wait ends"); + } + + private static void UsedUpLineNextKit() + { + foreach (bool withRule in new[] { true, false }) + { + string how = withRule ? "Consumables rule" : "best pack kit"; + var b = Rig(withRule); + Check.True(b.CheckVitals(), $"{how}: 40% under Heal At 60%: acts"); + Check.Eq(LastKit(), Kit1, $"{how}: Kit1 first (the walk is read now)"); + Gone(Kit1); + ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up."); + Check.Eq(b.KitsUsedUp, 1, $"{how}: the kit in flight is marked used up"); + Check.True(b.CheckVitals(), $"{how}: acts again"); + Check.Eq(LastKit(), Kit2, $"{how}: inside the walk's reuse the used-up kit is skipped: Kit2"); + Check.True(FakeHost.Logs.Any(l => l.Contains("0x80073C1B", StringComparison.Ordinal) && l.Contains("is used up", StringComparison.Ordinal)), + $"{how}: logged with the id"); + } + } + + private static void UsesLeftKeepsKit() + { + var b = Rig(withRule: true); + Check.True(b.CheckVitals(), "acts"); + Check.Eq(LastKit(), Kit1, "Kit1"); + ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} has 3 uses left."); + Check.Eq(b.KitsUsedUp, 0, "uses left: nothing marked"); + Check.True(b.CheckVitals(), "acts again"); + Check.Eq(LastKit(), Kit1, "the same kit again"); + } + + // A late line from a kit that timed out can land while the next kit is in flight. + private static void OtherKitLineIgnored() + { + const string Adept = "Adept Healing Kit"; // ranked ahead of Treated: the pack pick takes it + var b = Rig(withRule: false, kit1Name: Adept); + Check.True(b.CheckVitals(), "acts"); + Check.Eq(LastKit(), Kit1, "the Adept kit is in flight"); + ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up."); + Check.Eq(b.KitsUsedUp, 0, "the line names the Treated kit, not the one in flight: nothing marked"); + Check.True(FakeHost.Logs.Any(l => l.Contains("ignored", StringComparison.Ordinal)), "logged as ignored"); + Check.True(b.CheckVitals(), "acts again"); + Check.Eq(LastKit(), Kit1, "the Adept kit is used again"); + ResultLine(b, $"You heal yourself for 12 Health points. Your {Adept} is used up."); + Check.Eq(b.KitsUsedUp, 1, "control: the line naming the kit in flight marks it"); + } + + private static void SkipExpires() + { + var b = Rig(withRule: true); + var t0 = new DateTime(2026, 1, 1, 12, 1, 0); + DateTime now = t0; + b.Clock = () => now; + b.CheckVitals(); + b.OnChatWindowText($"You heal yourself for 12 Health points. Your {KitName} is used up.", 0); + Check.True(b.KitUsedUp(unchecked((int)Kit1)), "marked"); + now = t0.AddMilliseconds(2900); + Check.True(b.KitUsedUp(unchecked((int)Kit1)), "2.9 s later: still skipped"); + now = t0.AddMilliseconds(3000); // 3 s as a literal: the test must not follow the constant + Check.False(b.KitUsedUp(unchecked((int)Kit1)), "3 s: no longer skipped (the walk has dropped a removed kit by now)"); + Check.False(b.KitUsedUp(unchecked((int)Kit2)), "another kit was never skipped"); + } + + // No GetContainerContents: the inventory is the object cache's, which keeps the removed kit. A skip + // that ended at 3 s would pick it again for good. + private static void NoWalkSkipLasts() + { + var b = Rig(withRule: true, walk: false); + var t0 = new DateTime(2026, 1, 1, 12, 2, 0); + DateTime now = t0; + b.Clock = () => now; + Check.True(b.CheckVitals(), "acts"); + Check.Eq(LastKit(), Kit1, "Kit1 first"); + Gone(Kit1); // the client deletes it; the cache still lists it + ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up."); + now = t0.AddMilliseconds(800); + Check.True(b.CheckVitals(), "acts again"); + Check.Eq(LastKit(), Kit2, "in the window: Kit2"); + ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} has 3 uses left."); + now = t0.AddMilliseconds(3200); + Check.True(b.CheckVitals(), "acts at +3.2 s"); + Check.Eq(LastKit(), Kit2, "past 3 s with no walk: still Kit2, never the used-up Kit1"); + Check.True(FakeHost.Logs.Any(l => l.Contains("from now on", StringComparison.Ordinal)), "logged as a lasting skip"); + } + + private static void StaminaKitUsedUp() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.ContentsCalls = true; + FakeHost.CombatModeValue = CombatMode.NonCombat; + FakeHost.Names[StamKit1] = "Greater Stamina Kit"; + FakeHost.Names[StamKit2] = "Stamina Kit"; + FakeHost.Names[Gem] = "Sapphire"; + FakeHost.Containers[StamKit1] = Player; + FakeHost.Containers[StamKit2] = Player; + FakeHost.Containers[Gem] = Player; + FakeHost.Skills[(Player, 6)] = (300, 2); // Healing + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings + { + IsMacroRunning = true, PeaceModeForKits = false, UseKitsInMagicMode = true, + KitMinSuccessPct = 0, StaminaKitMinSuccessPct = 0, + }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.SetCharacterSkills(skills); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 1000, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + b.SetCharacterSkills(skills); + b.SetWorldObjectCache(Frozen(FakeHost.MakeCache(host, Player, new[] { StamKit1, StamKit2, Gem }))); + var attempt = typeof(BuffManager).GetMethod("AttemptStaminaKitUse", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, Type.EmptyTypes)!; + Check.True((bool)attempt.Invoke(b, null)!, "the stamina kit goes out"); + Check.Eq(LastKit(), StamKit1, "the Greater one first"); + Gone(StamKit1); + b.OnChatWindowText("You heal yourself for 300 Stamina points. Your Greater Stamina Kit is used up.", 0); + Thread.Sleep(750); + Check.False(b.KitPending(), "the wait ends"); + Check.True((bool)attempt.Invoke(b, null)!, "the next stamina kit goes out"); + Check.Eq(LastKit(), StamKit2, "inside the walk's reuse: the used-up Greater kit is skipped"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootByNameTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootByNameTests.cs new file mode 100644 index 0000000..401fd02 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootByNameTests.cs @@ -0,0 +1,135 @@ +using System; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Loot by name (2026-11-02): the list, how a name matches, the file, and the attempt bookkeeping that keeps a +// chest from being opened over and over or an unreachable item from being chased forever. +internal static class LootByNameTests +{ + public static void Register(Runner r) + { + r.Add("loot by name: a plain name is the whole name, ignoring case; * makes it a part", Matching); + r.Add("loot by name: the list adds, removes, refuses duplicates and empties; the radius is clamped", ListEdits); + r.Add("loot by name: the settings string round-trips, tidies what was typed, and an empty one is an empty list", SettingsString); + r.Add("loot by name: a use is tried a few times, a gap apart, then the object is left alone for a while", Attempts); + r.Add("loot by name: an opened object stays finished until it is gone, then a new one is looted again", DoneUntilGone); + r.Add("meta options: /vt opt set pickupmacrooff (and lootchestsmacrooff) turn Pickup with macro off on and off", PickupMacroOffOption); + } + + private static void Matching() + { + Check.True(LootByNameList.Matches("Unearthed Cache", "Unearthed Cache"), "exact"); + Check.True(LootByNameList.Matches("unearthed cache", "Unearthed Cache"), "case"); + Check.False(LootByNameList.Matches("Cache", "Unearthed Cache"), "a plain word is not part of a longer name"); + Check.True(LootByNameList.Matches("*cache*", "Unearthed Cache"), "contains"); + Check.True(LootByNameList.Matches("Unearthed*", "Unearthed Cache"), "starts with"); + Check.True(LootByNameList.Matches("*Cache", "Unearthed Cache"), "ends with"); + Check.False(LootByNameList.Matches("*", "Unearthed Cache"), "a lone * matches nothing"); + Check.False(LootByNameList.Matches("**", "Unearthed Cache"), "** matches nothing"); + Check.False(LootByNameList.Matches("", "Unearthed Cache"), "empty pattern"); + Check.False(LootByNameList.Matches("Unearthed Cache", ""), "empty name"); + } + + private static void ListEdits() + { + var l = new LootByNameList(); + Check.True(l.IsEmpty, "starts empty"); + Check.True(l.Add(" \"Unearthed Cache\" "), "added, quotes and spaces trimmed"); + Check.False(l.Add("unearthed cache"), "a duplicate in another case is refused"); + Check.False(l.Add(" "), "blank refused"); + Check.Eq(l.Names.Count, 1, "one name"); + Check.True(l.MatchesAny("Unearthed Cache"), "matches"); + Check.False(l.MatchesAny("Chest"), "other names don't"); + Check.True(l.Remove("UNEARTHED CACHE"), "removed ignoring case"); + Check.False(l.Remove("Unearthed Cache"), "removing it again says no"); + for (int i = 0; i < LootByNameList.MaxNames; i++) l.Add("Thing " + i); + Check.False(l.Add("One too many"), "the list is full"); + l.Clear(); + Check.True(l.IsEmpty, "cleared"); + l.SetRadius(5000); + Check.Near(l.Radius, LootByNameList.MaxRadius, 0.001, "radius capped"); + l.SetRadius(-4); + Check.Near(l.Radius, LootByNameList.MinRadius, 0.001, "radius floored"); + } + + private static void SettingsString() + { + var l = new LootByNameList(); + l.Add("Unearthed Cache"); + l.Add("*Doubloon*"); + l.SetRadius(45); + string saved = l.ToSettingString(); + Check.Eq(saved, "Unearthed Cache | *Doubloon*", "how the settings keep the list"); + var back = LootByNameList.Parse(saved, 45); + Check.Eq(back.Names.Count, 2, "two names back"); + Check.True(back.MatchesAny("Marae Lassel Doubloon"), "the wildcard came back"); + Check.Near(back.Radius, 45, 0.001, "the radius is what was given"); + + Check.Eq(LootByNameList.Normalize(" a |b|| A | \"c\" "), "a | b | c", "blanks, repeats (any case) and quotes tidied, order kept"); + Check.True(LootByNameList.Parse("", 30).IsEmpty, "an empty string is an empty list"); + Check.True(LootByNameList.Parse(null, 30).IsEmpty, "so is null"); + Check.Near(LootByNameList.Parse("x", 0).Radius, LootByNameList.DefaultRadius, 0.001, "a zero radius means the default"); + Check.Near(LootByNameList.Parse("x", 9999).Radius, LootByNameList.MaxRadius, 0.001, "a huge radius is capped"); + } + + private static void Attempts() + { + var t = new LootNameTracker(); + const int id = 77; + long now = 1000; + Check.True(t.CanUse(id, now), "first use is allowed"); + t.NoteUse(id, now); + Check.False(t.CanUse(id, now + 1000), "not again inside the gap (the client is walking there)"); + for (int i = 2; i <= LootNameTracker.MaxUses; i++) + { + now += LootNameTracker.UseGapMs; + Check.True(t.CanUse(id, now), $"use {i} after the gap"); + t.NoteUse(id, now); + } + now += LootNameTracker.UseGapMs; + Check.False(t.CanUse(id, now), "the budget is spent"); + Check.True(t.Exhausted(id, now), "exhausted once the last gap has passed"); + t.GiveUp(id, now); + Check.True(t.IsBlocked(id, now + 1000), "left alone"); + Check.False(t.CanUse(id, now + 1000), "no use while left alone"); + Check.False(t.IsBlocked(id, now + LootNameTracker.GiveUpMs + 1), "tried again after the wait"); + Check.True(t.CanUse(id, now + LootNameTracker.GiveUpMs + 1), "with a fresh budget"); + } + + private static void DoneUntilGone() + { + var t = new LootNameTracker(); + t.NoteUse(5, 0); + t.MarkDone(5); + Check.True(t.IsBlocked(5, 999_999), "finished stays finished"); + Check.False(t.CanUse(5, 999_999), "and is not used again"); + t.Prune(id => id != 5); // it left the world + Check.False(t.IsBlocked(5, 999_999), "forgotten once gone"); + Check.True(t.CanUse(5, 999_999), "the same id coming back is looted again"); + t.MarkDone(6); + t.Prune(id => true); + Check.True(t.IsBlocked(6, 0), "objects still there keep their state"); + } + + // A meta that loots a chest with Looting off (the Dreamweave dig's cache) turns this on and leaves it on. + private static void PickupMacroOffOption() + { + FakeHost.Reset(); + var host = FakeHost.Create(); + var settings = new LegacyUiSettings(); + var meta = new MetaManager(settings, host, new PlayerVitalsCache()); + Check.True(settings.LootChestsMacroOff, "on by default"); + meta.TryHandleVtCommand("/vt opt set pickupmacrooff false"); + Check.False(settings.LootChestsMacroOff, "the option turns it off"); + meta.TryHandleVtCommand("/vt opt set pickupmacrooff true"); + Check.True(settings.LootChestsMacroOff, "and on"); + meta.TryHandleVtCommand("/vt opt set lootchestsmacrooff false"); + Check.False(settings.LootChestsMacroOff, "the long name does the same"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootChatLineTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootChatLineTests.cs index e4e5cd5..fa7d5b4 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootChatLineTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootChatLineTests.cs @@ -42,8 +42,30 @@ internal static class LootChatLineTests r.Add("loot chat: pyreals, notes, comps and other stacks print the plain line only", StackablePlain); r.Add("loot chat: Describe looted items off prints the plain lines", SettingOffPlain); r.Add("loot chat: the settings survive a profile save and load, the settings map and /ra iteminfo loot", SettingsRoundTrip); + r.Add("loot chat: Info text colour colours the described line only, in its own chat type", DescribedLineInTextColor); } + // 2026-11-05: Item Info's "Info text colour" covers the described "Looted" line too; the plain + // lines (salvage by default, pyreals) are not item info and never ask for a colour. + private static void DescribedLineInTextColor() => Clocked(() => + { + List looted = LootCorpse(s => { s.TextColor = "#EE921E"; s.LootChatType = 18; }, pluginCommands: true); + string line = LineFor(looted, "Blunt Crossbow"); + int at = FakeHost.Chat.IndexOf(line); + var asks = Enumerable.Range(0, FakeHost.PluginCommands.Count).Where(i => FakeHost.PluginCommands[i].Plugin == "RynthCore.Chat").ToList(); + Check.Eq(asks.Count, 1, "one colour asked for (the described keeper): " + string.Join(" | ", FakeHost.PluginCommands)); + if (asks.Count == 1) + { + Check.Eq(FakeHost.PluginCommands[asks[0]], ("RynthCore.Chat", "nextcolor", "#EE921E"), "the colour"); + Check.Eq(FakeHost.PluginCommandChatCounts[asks[0]], at, "asked for just before the line is written"); + } + Check.Eq(FakeHost.ChatTypes[at], 18, "the line keeps its loot chat type"); + Check.True(line.Contains("(rule \"Keep bows\"): Gold"), "and its text: " + line); + + looted = LootCorpse(pluginCommands: true); + Check.False(FakeHost.PluginCommands.Any(c => c.Plugin == "RynthCore.Chat"), "no colour set: nothing asked (as before)"); + }); + private static long _now; private static void Clocked(Action body) @@ -146,9 +168,10 @@ internal static class LootChatLineTests } /// Opens the corpse and loots it, each item landing in the main pack as soon as its move goes out. - private static List LootCorpse(Action? configure = null) + private static List LootCorpse(Action? configure = null, bool pluginCommands = false) { World(); + FakeHost.PluginCommandCalls = pluginCommands; var host = FakeHost.Create(Player); var bot = new Bot(host); configure?.Invoke(bot.S.ItemInfoSettings); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs index a0c5b8c..11b8aa2 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs @@ -52,6 +52,10 @@ internal static class LootCorpseTests r.Add("boost loot: our kill holds the next target until its corpse is looted (one kill, one loot)", BoostLootOneKillOneLoot); r.Add("boost loot: the wait ends after BoostLootKillWaitMs, for a close monster, and with Boost Loot off", BoostLootHoldLimits); r.Add("boost loot: looting the kill's corpse ends the wait; an older corpse does not", BoostLootWaitEndsOnKillCorpse); + r.Add("death wait (11-08): Looting on, our kill holds the next target for the learned death + 1 s; Looting gets the tick", DeathWaitUsesLearnedTime); + r.Add("death wait (11-08): not learned yet: 2.5 s + 1 s; the corpse's coming is timed and learned", DeathWaitDefaultAndLearns); + r.Add("death wait (11-08): looting the kill's corpse ends it at once; a corpse the rules don't take ends it soon after it came", DeathWaitEndsOnLoot); + r.Add("death wait (11-08): no corpse in the time: it carries on; a close attacker is fought; Looting off changes nothing", DeathWaitLimits); r.Add("monster ignore: a close Priority 0 monster neither holds combat nor starves the corpse", IgnoredMonsterDoesNotHoldLoot); r.Add("loot gate (R-20261025 727b): a predicted kill still alive holds the corpse; after its window combat has it again", PredictedKillHoldsCorpse); r.Add("loot gate (R-20261025 727b): the kill notice, health 0 or a hit after the swap settle a predicted kill at once", PredictedKillSettled); @@ -607,6 +611,180 @@ internal static class LootCorpseTests Check.False((bool)bot.Call("BoostLootHoldsNewTarget")!, "so combat goes on at once"); } + // ── The death wait (2026-11-08, Tom: the bot ran off from its kill, then turned round and ran back + // when the corpse came after the death animation) ── + + private const string Elemental = "Ancient Water Elemental"; + + /// BoostWorld with Boost Loot off and combat's hold wired to both holds, on a clock the test moves. + private static Bot DeathWorld(float monsterMeters, out CombatManager combat, Func clock) + { + RynthAiPlugin.CorpseClock = clock; + var bot = BoostWorld(monsterMeters, withCorpse: false, out combat, boost: false); + combat.HoldNewTarget = () => (bool)bot.Call("LootHoldsNewTarget")!; + combat.HoldNewTargetWhy = () => (string)bot.Call("LootHoldWhy")!; + return bot; + } + + private static void RestoreCorpseClock() => RynthAiPlugin.CorpseClock = static () => Environment.TickCount64; + + private static BotActivity Arbiter(Bot bot, CombatManager combat) + { + bool wantLoot = bot.HasLootWork(); + var inputs = new ArbiterInputs(true, false, combat.HasEngageableTarget, wantLoot, false, true, + combatEngaged: combat.IsUnderCloseAttack, deathWait: wantLoot && bot.Get("_deathWaitHeld")); + return ActivityArbiter.Decide(in inputs); + } + + private static void DeathWaitUsesLearnedTime() + { + long now = 1_000_000; + try + { + var bot = DeathWorld(15f, out var combat, () => now); + bot.P.XpTableForTests.RecordDeath(Elemental, 1500); + bot.Call("StartDeathWait", Elemental); + Check.Eq(bot.Get("_deathWaitMs"), 2500L, "the learned 1.5 s and 1 s more"); + Check.True(FakeHost.Logs.Any(l => l.Contains("waiting up to 2.5 s for the corpse of 'Ancient Water Elemental'") && l.Contains("learned over 1 kill")), + "said once, plainly: " + FakeHost.Logs.LastOrDefault()); + combat.HandleCombatTrigger(); + Check.Eq(combat.activeTargetId, 0, "the next monster (15 m) is not locked while the corpse comes"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] next target waits: the kill's corpse comes first")), "combat says why"); + Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "Looting has the tick (no nav, no hunt walk)"); + now += 2400; + Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "still at 2.4 s"); + now += 200; + Check.Eq(Arbiter(bot, combat), BotActivity.Combat, "at 2.6 s, no corpse: it carries on"); + combat.HandleCombatTrigger(); + Check.Eq(combat.activeTargetId, unchecked((int)Monster), "and the next monster is locked"); + } + finally { RestoreCorpseClock(); } + } + + private static void DeathWaitDefaultAndLearns() + { + long now = 2_000_000; + try + { + var bot = DeathWorld(15f, out var combat, () => now); + bot.Set("_loginComplete", true); + string? killed = (string?)bot.Call("NoteMonsterStatsKill", $"You killed {Elemental}!"); + Check.Eq(killed, Elemental, "the kill notice names it"); + bot.Call("StartDeathWait", killed!); + Check.Eq(bot.Get("_deathWaitMs"), RynthAiPlugin.DeathWaitDefaultMs + RynthAiPlugin.DeathWaitExtraMs, "not learned: 2.5 s + 1 s"); + Check.True(FakeHost.Logs.Any(l => l.Contains("isn't learned yet")), "and says so"); + now += 2100; + bot.Cache.OnCreateObject(Corpse); + bot.Cache.Tick(); + bot.Call("NoteCorpseCreated", Corpse); + Check.Eq(bot.Get("_deathCorpseId"), unchecked((int)Corpse), "the kill's corpse is known"); + Check.Near(bot.P.XpTableForTests.DeathMs(Elemental) ?? 0, 2100, 1e-9, "its death learned: 2.1 s"); + Check.Eq(bot.P.MonsterStatsForTests.Get(Elemental)!.CorpseKills, 1, "and on the session's row"); + Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "the corpse is here and lootable: Looting"); + bot.Set("_targetCorpseId", unchecked((int)Corpse)); // the looter claims it + now += 5000; // past the 3.5 s: the corpse is being looted, so it still holds + Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "while its corpse is claimed the wait goes on"); + } + finally { RestoreCorpseClock(); } + } + + private static void DeathWaitEndsOnLoot() + { + long now = 3_000_000; + try + { + var bot = DeathWorld(15f, out var combat, () => now); + bot.Call("StartDeathWait", Elemental); + now += 1500; + bot.Cache.OnCreateObject(Corpse); + bot.Cache.Tick(); + bot.Call("NoteCorpseCreated", Corpse); + bot.HasLootWork(); + bot.Call("MarkCorpseCompleted", unchecked((int)Corpse)); + Check.Eq(bot.Get("_deathWaitAt"), 0L, "looted: the wait is over at once"); + Check.True(FakeHost.Logs.Any(l => l.Contains("done waiting for the corpse of 'Ancient Water Elemental' after 1.5 s: its corpse is looted")), + "said once: " + FakeHost.Logs.LastOrDefault()); + combat.HandleCombatTrigger(); + Check.Eq(combat.activeTargetId, unchecked((int)Monster), "and combat goes on"); + + // A corpse the rules don't take (another player's kill, My Kills Only): no longer than its coming and the look. + var other = DeathWorld(15f, out var combat2, () => now); + FakeHost.Strings[(Corpse, LongDescKey)] = "Killed by Someone Else."; + other.Call("StartDeathWait", Elemental); + now += 1500; + other.Cache.OnCreateObject(Corpse); + other.Cache.Tick(); + other.Call("NoteCorpseCreated", Corpse); + Check.Eq(Arbiter(other, combat2), BotActivity.Looting, "just came: the loot rules get their look"); + now += RynthAiPlugin.DeathWaitDecideMs + 1; + Check.Eq(Arbiter(other, combat2), BotActivity.Combat, "not ours: it carries on"); + Check.True(FakeHost.Logs.Any(l => l.Contains("the loot rules don't take it")), "and says why"); + + // Ours and lootable, but the looter leaves it for the fight (monsters in range): no stand-off. + // 2026-11-08: the wait held combat's next target while looting waited for combat; the + // character stood 7.8 s, then the whole loot held it (16 s for a 1.2 s death). + var standoff = DeathWorld(15f, out var combat3, () => now); + FakeHost.Strings.Remove((Corpse, LongDescKey)); + standoff.Call("StartDeathWait", Elemental); + now += 1200; + standoff.Cache.OnCreateObject(Corpse); + standoff.Cache.Tick(); + standoff.Call("NoteCorpseCreated", Corpse); + Check.Eq(Arbiter(standoff, combat3), BotActivity.Looting, "just came: the looter gets its moment to claim it"); + Check.True(standoff.Get>("_lootableInRange").Contains(unchecked((int)Corpse)), "it is lootable in range"); + Check.Eq(standoff.Get("_targetCorpseId"), 0, "but not claimed"); + now += RynthAiPlugin.DeathWaitDecideMs + 1; + Check.Eq(Arbiter(standoff, combat3), BotActivity.Combat, "unclaimed a second after it came: the fight goes on"); + combat3.HandleCombatTrigger(); + Check.Eq(combat3.activeTargetId, unchecked((int)Monster), "and the next monster is locked"); + Check.True(FakeHost.Logs.Any(l => l.Contains("the looter leaves it for the fight")), "says why: " + FakeHost.Logs.LastOrDefault()); + } + finally { RestoreCorpseClock(); } + } + + private static void DeathWaitLimits() + { + long now = 4_000_000; + try + { + // No corpse ever: the wait ends at its time, once. + var bot = DeathWorld(15f, out var combat, () => now); + bot.Call("StartDeathWait", Elemental); + Check.True((bool)bot.Call("LootHoldsNewTarget")!, "holding"); + now += RynthAiPlugin.DeathWaitDefaultMs + RynthAiPlugin.DeathWaitExtraMs; + Check.False((bool)bot.Call("LootHoldsNewTarget")!, "past the time: no hold"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("no corpse came in 3.5 s")), 1, "said once"); + combat.HandleCombatTrigger(); + Check.Eq(combat.activeTargetId, unchecked((int)Monster), "the next monster is locked"); + bot.HasLootWork(); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("done waiting")), 1, "and not again"); + + // A monster 2 m away is fought whatever the wait. + var close = DeathWorld(2f, out var combat2, () => now); + close.Call("StartDeathWait", Elemental); + combat2.HandleCombatTrigger(); + Check.Eq(combat2.activeTargetId, unchecked((int)Monster), "a monster at 2 m: locked"); + Check.Eq(Arbiter(close, combat2), BotActivity.Combat, "and fought"); + + // Looting off: nothing changes. + var off = DeathWorld(15f, out var combat3, () => now); + off.S.EnableLooting = false; + off.Call("StartDeathWait", Elemental); + Check.Eq(off.Get("_deathWaitAt"), 0L, "no wait"); + Check.False(off.HasLootWork(), "no loot work"); + combat3.HandleCombatTrigger(); + Check.Eq(combat3.activeTargetId, unchecked((int)Monster), "the next monster is locked at once"); + Check.Eq(Arbiter(off, combat3), BotActivity.Combat, "combat as before"); + + // Rare-only looting: as Boost Loot, nothing to wait for. + var rare = DeathWorld(15f, out _, () => now); + rare.S.LootOnlyRareCorpses = true; + rare.Call("StartDeathWait", Elemental); + Check.Eq(rare.Get("_deathWaitAt"), 0L, "Loot Only Rare Corpses: no wait"); + } + finally { RestoreCorpseClock(); } + } + private static void HeldByCombatLoggedOnce() { var bot = StarvationWorld(15f, out _); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootJumpTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootJumpTests.cs index 193c42f..58c9d37 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootJumpTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootJumpTests.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; @@ -24,6 +25,11 @@ internal static class LootJumpTests private const uint CorpseA = 0x80263100; private const uint GemA = 0x80263101; private const uint GemA2 = 0x80263102; + private const uint GemA3 = 0x80263103; + private const uint PackStack = 0x80263120; + private const uint KeyMaxStack = 11, KeyStack = 12; + private const uint CorpseB = 0x80263110; + private const uint GemB = 0x80263111; private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800; private const uint LongDescKey = 16; private const string Me = "Test Looter"; @@ -36,6 +42,29 @@ internal static class LootJumpTests r.Add("jump loot: a corpse's only match jumps too (one tap jump)", SingleItemJumps); r.Add("jump loot: the setting off sends no jump", SettingOffNoJump); r.Add("jump loot: stamina of 5 or less sends no jump", LowStaminaNoJump); + r.Add("jump loot: health under Heal At sends no jump (the flight would hold the heal)", LowHealthNoJump); + r.Add("jump loot: a pickup answered with no bend-down releases the corpse at once; the next corpse is opened while still in the air", NoReturnNextCorpseInAir); + r.Add("jump loot: after a pickup answered with no bend-down, the next item goes out at once in the air with no second jump (not queued); after the landing the next one jumps again", NoReturnNextItemJumps); + r.Add("jump loot: a jump pickup answered only after a bend-down's time still waits for its Return before the corpse is released", SlowAnswerKeepsReturnWait); + r.Add("jump loot: a bend-down answer inside an earlier jump's flight ends it: the next item is queued behind that Return, with no jump", SlowAnswerEndsAirWindow); + r.Add("jump loot: a jump send's answer at 150 ms is confirmed then, and the next corpse opened then, not at 500 ms", JumpAnswerConfirmedOnArrival); + r.Add("jump loot: a jump send merged into a pack stack keeps the floor (the client's request slot stays held for a merged-away object)", JumpMergeKeepsAnswerFloor); + r.Add("jump loot: the no-bend-down window after an in-air send that rode an earlier jump is anchored to that jump", AirWindowAnchoredToTheInAirJump); + r.Add("jump loot: a fast refusal that is not 'too busy' (a code-0 save-failed) does not turn the no-bend-down call off", NonBusyRefusalKeepsNoMotion); + r.Add("jump loot: a send with no jump still waits PickupAnswerMinMs before its answer is believed", NoJumpKeepsAnswerFloor); + r.Add("jump loot: a jump send's weak sign (an unowned stack, no pack stack grown) still waits PickupAnswerMinMs", JumpWeakSignKeepsAnswerFloor); + r.Add("jump loot: a send with no jump answered at 100 ms still waits its Return before the next corpse", NoJumpFastAnswerWaitsReturn); + r.Add("jump loot: a jump send refused, then resent (no jump), answered at 100 ms still waits its Return", ResentFastAnswerWaitsReturn); + r.Add("jump loot: a move sent on a no-bend-down call and refused 'too busy' turns the call off: the next fast jump answer waits its Return", BusyRefusalTurnsNoMotionOff); + r.Add("jump loot: an open sent on a no-bend-down call and refused 'too busy' turns the call off too", BusyOpenTurnsNoMotionOff); + r.Add("jump loot: dropping the corpse claim (macro off) ends the no-bend-down window", ResetEndsAirWindow); + r.Add("jump loot: a pickup sent while still in the air from the last loot jump takes no second jump; after the landing the next one jumps", NoSecondJumpInTheAir); + r.Add("jump loot: the pickup's jump puts combat and buffs on hold until the landing (or the cap); loot never", JumpHoldsCombatNotLoot); + r.Add("jump loot: portal space and a death drop the combat hold (no landing is coming)", PortalAndDeathEndJumpHold); + r.Add("jump loot cadence: one move in flight at a time (the client's one inventory request), the next sent on the tick the answer shows", OneInFlightNextOnAnswerTick); + r.Add("jump loot: the flight budget lets an early in-air send through with no new jump", FlightBudgetLetsEarlySendThrough); + r.Add("jump loot: the flight budget holds a late in-air send until the landing, then jumps again", FlightBudgetHoldsLateSend); + r.Add("jump loot: ResetCurrentLootItem clears the flight hold's logged flag", ResetClearsFlightHoldLogged); } private static long _now; @@ -43,45 +72,81 @@ internal static class LootJumpTests private static void Clocked(Action body) { var old = RynthAiPlugin.CorpseClock; + var oldPace = ActionPacer.NowMs; _now = 50_000_000; RynthAiPlugin.CorpseClock = () => _now; + ActionPacer.NowMs = () => _now; // the loot jump's air hold (ActionPacer.LootJumpAirborne) on the same clock + ActionPacer.ForgetLootJump(); try { body(); } - finally { RynthAiPlugin.CorpseClock = old; } + finally { RynthAiPlugin.CorpseClock = old; ActionPacer.NowMs = oldPace; ActionPacer.ForgetLootJump(); } } - private static void Gem(uint id) + private static RynthAiPlugin _bot = null!; // the bot LootUntilFirstMove made + private static RynthCoreHost _host; // and its host + private static T Field(string name) => (T)typeof(RynthAiPlugin).GetField(name, Any)!.GetValue(_bot)!; + private static void SetField(string name, object v) => typeof(RynthAiPlugin).GetField(name, Any)!.SetValue(_bot, v); + + /// The character's height: up in the air, or back on the ground (ActionPacer's landing check reads it). + private static void Air(bool up) => FakeHost.PlayerPose = (Me0.Cell, Me0.X, Me0.Y, up ? Me0.Z + 1.0f : Me0.Z); + + private static void Gem(uint id, uint container = CorpseA) { FakeHost.Names[id] = "Black Opal"; FakeHost.ItemTypes[id] = ItemTypeGem; - FakeHost.Containers[id] = CorpseA; + FakeHost.Containers[id] = container; FakeHost.Appraised.Add(id); } - private static void World(bool secondGem) + private static void Corpse(uint id, float dx) + { + FakeHost.Names[id] = "Corpse of Olthoi Swarm Drone"; + FakeHost.ItemTypes[id] = ItemTypeContainer; + FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(id); + FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z); + } + + private static void World(bool secondGem, bool secondCorpse, bool serverGates, bool thirdGem = false, bool packStack = false) { FakeHost.Reset(); FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId FakeHost.TapJumpCalls = true; + FakeHost.ServerGates = serverGates; // GetCastBusyState: the client's motion queue + FakeHost.LastUseDoneCalls = serverGates; // GetLastUseDone: the open's answer + FakeHost.WeenieErrorCalls = true; // GetLastWeenieError: "You're too busy" FakeHost.Names[Player] = Me; FakeHost.Positions[Player] = Me0; FakeHost.PlayerPose = Me0; - FakeHost.Names[CorpseA] = "Corpse of Olthoi Swarm Drone"; - FakeHost.ItemTypes[CorpseA] = ItemTypeContainer; - FakeHost.Strings[(CorpseA, LongDescKey)] = $"Killed by {Me}."; - FakeHost.NotAttackable.Add(CorpseA); - FakeHost.Positions[CorpseA] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); + Corpse(CorpseA, 1.0f); Gem(GemA); if (secondGem) Gem(GemA2); + if (thirdGem) Gem(GemA3); + if (secondCorpse) + { + Corpse(CorpseB, 1.5f); + Gem(GemB, CorpseB); + } + if (packStack) + { + // GemA is a stack of 1, and the pack holds a same-name stack of 3 it can merge into. + FakeHost.Ints[(GemA, KeyMaxStack)] = 100; + FakeHost.Ints[(GemA, KeyStack)] = 1; + Gem(PackStack, Player); + FakeHost.Ints[(PackStack, KeyMaxStack)] = 100; + FakeHost.Ints[(PackStack, KeyStack)] = 3; + } } - /// Opens the corpse and ticks until the first pickup's move has gone out. - private static void LootUntilFirstMove(bool jumpEnabled, bool secondGem, uint stamina) + /// Opens the corpse and ticks until the first pickup's move has gone out. Returns the tick. + private static Action LootUntilFirstMove(bool jumpEnabled, bool secondGem, uint stamina, bool secondCorpse = false, bool serverGates = false, bool thirdGem = false, bool packStack = false, uint health = 100) { - World(secondGem); + World(secondGem, secondCorpse, serverGates, thirdGem, packStack); var host = FakeHost.Create(Player); + _host = host; var bot = new RynthAiPlugin(); + _bot = bot; var s = new LegacyUiSettings { IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0, @@ -98,7 +163,7 @@ internal static class LootJumpTests cache.SetPlayerId(Player); Set("_objectCache", cache); Set("_playerId", Player); - Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = stamina, MaxMana = 100, CurrentMana = 100 }); + Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = health, MaxStamina = 100, CurrentStamina = stamina, MaxMana = 100, CurrentMana = 100 }); string profile = Path.Combine(Program.TempRoot, "loot-jump-test.json"); var p = new LootProfile { Name = "gems" }; @@ -113,17 +178,512 @@ internal static class LootJumpTests Set("_activity", BotActivity.Looting); typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(bot, null); } - foreach (uint id in secondGem ? new[] { CorpseA, GemA, GemA2 } : new[] { CorpseA, GemA }) cache.OnCreateObject(id); - cache.Tick(); + var ids = new List { CorpseA, GemA }; + if (secondGem) ids.Add(GemA2); + if (thirdGem) ids.Add(GemA3); + if (packStack) ids.Add(PackStack); + if (secondCorpse) { ids.Add(CorpseB); ids.Add(GemB); } + foreach (uint id in ids) cache.OnCreateObject(id); + for (int i = 0; i < 50; i++) cache.Tick(); Tick(); Check.True(FakeHost.Uses.Contains(CorpseA), "the corpse is opened"); FakeHost.UseDone(0); FakeHost.GroundContainer = CorpseA; bot.OnViewObjectContents(CorpseA); + _openedAt = _now; for (int i = 0; i < 200 && FakeHost.ExternalMoves.Count == 0; i++) { _now += 20; Tick(); } Check.True(FakeHost.ExternalMoves.Count > 0, "a gem's move is sent"); + return Tick; } + private const long TickMs = 20; + + private static long _openedAt; // CorpseA's contents arrived (LootUntilFirstMove) + + /// + /// The latest tick the next corpse's open may go out after the last item's confirm at + /// : at once, except that a corpse emptied sooner than the + /// Loot Empty Corpse floor (max(200 ms, LootEmptyCorpseMs) from its open, a user setting, not + /// a landing wait) is completed only then; a tick or two of slack. + /// + private static long NextOpenDue(long confirmed) => Math.Max(confirmed, _openedAt + 200) + 3 * TickMs; + + private static bool Confirmed(uint id) => FakeHost.Logs.Any(l => l.Contains($"pickup confirmed for 0x{id:X8}")); + + /// Ticks (TickMs each) until or has passed. + private static void TickUntil(Action tick, Func done, long maxMs) + { + long end = _now + maxMs; + while (_now < end && !done()) { _now += TickMs; tick(); } + } + + private static void TickFor(Action tick, long ms) + { + long end = _now + ms; + while (_now < end) { _now += TickMs; tick(); } + } + + // ACE with allow_jump_loot (Player_Inventory.GetPickupMotion): the move reaches the server while + // the character is in the air, the pickup motion is Invalid, so the item moves at once (about the + // round trip) and EnqueuePickupDone has no Return to play (IsBusy clears at once). What the + // client's motion queue (GetCastBusyState) reads in the air is not known, so both readings are + // run: busy (the jump's own motion for the whole flight) and idle. + private static void NoReturnNextCorpseInAir() => Clocked(() => + { + foreach (int airQueue in new[] { 1, 0 }) + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true); + Check.Eq(FakeHost.ExternalMoves[0].Id, GemA, $"[air queue {airQueue}] corpse A's gem goes first"); + long sent = _now; + FakeHost.CastBusy = airQueue; + TickFor(tick, 100); + FakeHost.Containers[GemA] = Player; // the answer, no bend-down + TickUntil(tick, () => Confirmed(GemA), 1000); + Check.True(Confirmed(GemA), $"[air queue {airQueue}] the pickup is confirmed"); + long confirmed = _now; + TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1500); + Check.True(FakeHost.Uses.Contains(CorpseB), $"[air queue {airQueue}] the next corpse is opened"); + Check.True(_now <= NextOpenDue(confirmed), + $"[air queue {airQueue}] the next corpse is opened at the confirm, not after a landing / Return wait: {_now - confirmed} ms after the confirm, {_now - sent} ms after the send"); + } + }); + + // The second item goes out at once, still in the air, with no second jump (an air jump costs + // stamina on ACE and does nothing for the pickup); once the character has landed, the next one + // jumps again. + private static void NoReturnNextItemJumps() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true); + uint first = FakeHost.ExternalMoves[0].Id; + Check.Eq(FakeHost.TapJumps, 1, "the first pickup jumps"); + Air(up: true); + FakeHost.CastBusy = 1; // the jump's motion plays + TickFor(tick, 100); + FakeHost.Containers[first] = Player; // the answer, no bend-down + TickUntil(tick, () => Confirmed(first), 1000); + Check.True(Confirmed(first), "the first pickup is confirmed"); + long confirmed = _now; + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1500); + Check.Eq(FakeHost.ExternalMoves.Count, 2, "the second move is sent"); + uint second = FakeHost.ExternalMoves[1].Id; + Check.True(_now - confirmed <= 3 * TickMs, $"at the confirm, not after the landing: {_now - confirmed} ms"); + Check.Eq(FakeHost.TapJumps, 1, "no jump in the air: " + Order()); + Check.False(FakeHost.Logs.Any(l => l.Contains("queuing 0x")), "not queued behind a Return that ACE never plays for it"); + + // The second, sent in the air, answered with no bend-down; the character has landed by now. + Air(up: false); + TickFor(tick, ActionPacer.JumpLandMinMs); + FakeHost.Containers[second] = Player; + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 3, 1500); + Check.Eq(FakeHost.ExternalMoves.Count, 3, "the third move is sent"); + int at = FakeHost.Order.IndexOf($"move:{FakeHost.ExternalMoves[2].Id:X8}"); + Check.True(at > 0 && FakeHost.Order[at - 1] == "tapjump", "landed: the third jumps again: " + Order()); + Check.Eq(FakeHost.TapJumps, 2, "two jumps in all"); + }); + + // The jump went out, but the answer took a bend-down's time (the server turned the character + // first and it landed, so ACE played the pickup motion and its Return): that Return is waited out. + private static void SlowAnswerKeepsReturnWait() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true); + FakeHost.CastBusy = 1; + TickFor(tick, 800); + FakeHost.Containers[GemA] = Player; // answered after the bend-down; the Return plays + TickUntil(tick, () => Confirmed(GemA), 1000); + Check.True(Confirmed(GemA), "the pickup is confirmed"); + TickFor(tick, 600); + Check.False(FakeHost.Uses.Contains(CorpseB), "no next open while the Return plays"); + FakeHost.CastBusy = 0; + TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1000); + Check.True(FakeHost.Uses.Contains(CorpseB), "the next corpse is opened once the character stands still"); + }); + + // First pickup in the air with no bend-down; the second, sent at once, is answered only after a + // bend-down (the character had landed), so its Return plays: the third is queued behind that + // Return (ACE NextPickup) and gets no jump, which would disturb the queue - the first jump's + // flight window no longer counts. + private static void SlowAnswerEndsAirWindow() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true); + uint first = FakeHost.ExternalMoves[0].Id; + FakeHost.CastBusy = 1; + TickFor(tick, 100); + FakeHost.Containers[first] = Player; // no bend-down + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1000); + Check.Eq(FakeHost.ExternalMoves.Count, 2, "the second move goes out at the first's confirm"); + uint second = FakeHost.ExternalMoves[1].Id; + long secondSent = _now; + TickFor(tick, 700); + FakeHost.Containers[second] = Player; // answered after a bend-down: its Return plays + TickUntil(tick, () => Confirmed(second), 1000); + Check.True(Confirmed(second), "the second pickup is confirmed"); + Check.True(_now - secondSent < 1500 - 100, $"(still inside the first jump's flight window: {_now - secondSent} ms after the second send)"); + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 3, 300); + Check.Eq(FakeHost.ExternalMoves.Count, 3, "the third move goes out during the Return"); + uint third = FakeHost.ExternalMoves[2].Id; + int at = FakeHost.Order.IndexOf($"move:{third:X8}"); + Check.True(at > 0 && FakeHost.Order[at - 1] != "tapjump", "with no jump into the Return: " + Order()); + Check.True(FakeHost.Logs.Any(l => l.Contains($"queuing 0x{third:X8}")), "queued behind the second's Return"); + }); + + // -- The PickupAnswerMinMs floor -- + // The floor is ACE's pickup motion time. A jump send has no motion: its server-only answer + // (the item in a pack, a pack stack grown, the object gone from the client) is believed on + // arrival. Every other send, and a jump send's weak sign (an unowned stack the client still has), + // keep the floor. + + private const long AnswerAtMs = 150; + + /// The ms from to the tick the pickup of is confirmed (-1: never, in 1.5 s). + private static long ConfirmAfter(Action tick, uint id, long sent) + { + TickUntil(tick, () => Confirmed(id), 1500); + return Confirmed(id) ? _now - sent : -1; + } + + private static void JumpAnswerConfirmedOnArrival() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true); + long sent = _now; + TickFor(tick, AnswerAtMs - TickMs); + FakeHost.Containers[GemA] = Player; // ACE's answer, no bend-down + long confirmedAfter = ConfirmAfter(tick, GemA, sent); + Check.True(confirmedAfter >= 0 && confirmedAfter <= AnswerAtMs + TickMs, + $"confirmed on the tick the answer shows ({AnswerAtMs} ms), not at PickupAnswerMinMs: {confirmedAfter} ms after the send"); + long confirmed = _now; + TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1000); + Check.True(FakeHost.Uses.Contains(CorpseB) && _now <= NextOpenDue(confirmed), + $"the next corpse is opened then too (or at the empty-corpse floor, 200 ms from the open): {_now - sent} ms after the send, {_now - _openedAt} ms after the open"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no bend-down or Return to wait for")), "classed as a pickup with no bend-down"); + }); + + private static void JumpMergeKeepsAnswerFloor() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true, packStack: true); + Check.Eq(FakeHost.ExternalMoves[0].Id, GemA, "the corpse gem goes"); + long sent = _now; + TickFor(tick, AnswerAtMs - TickMs); + // ACE StackableMerge: the corpse item is removed (gone from the client) and the pack stack grows. + FakeHost.Containers.Remove(GemA); + FakeHost.Names.Remove(GemA); + FakeHost.Positions.Remove(GemA); + FakeHost.Ints[(PackStack, KeyStack)] = 4; + // The client's one-request slot is emptied only by an answer about that same object, and a + // merged-away object is gone (RynthCore ClientActionGates): the slot can stay held, and a move + // sent now would be dropped by the client. The floor is kept. + long confirmedAfter = ConfirmAfter(tick, GemA, sent); + Check.True(confirmedAfter >= RynthAiPlugin.PickupAnswerMinMs, $"a merge keeps the floor: confirmed {confirmedAfter} ms after the send"); + // (By the floor the gem is gone from the client, which names no stack: either merge wording.) + Check.True(FakeHost.Logs.Any(l => l.Contains("pickup confirmed") && l.Contains("merged into")), "as a merge into the pack stack: " + + (FakeHost.Logs.LastOrDefault(l => l.Contains("pickup confirmed")) ?? "(none)")); + }); + + // The no-bend-down window after a pickup is anchored to the JUMP (it ends JumpLandMaxMs after + // it), not to the send that confirmed: a second send that rode the first jump, in the air, must + // not stretch it. + private static void AirWindowAnchoredToTheInAirJump() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true); + long jumpAt = _now; + uint first = FakeHost.ExternalMoves[0].Id; + Air(up: true); + TickFor(tick, 100); + FakeHost.Containers[first] = Player; // no bend-down + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 500); + Check.Eq(FakeHost.ExternalMoves.Count, 2, "the second goes out in the air"); + Check.Eq(FakeHost.TapJumps, 1, "riding the first jump"); + uint second = FakeHost.ExternalMoves[1].Id; + long secondAt = _now; + TickFor(tick, 100); + FakeHost.Containers[second] = Player; // no bend-down + TickUntil(tick, () => Confirmed(second), 500); + Check.True(Confirmed(second), "the second is confirmed"); + Check.True(FakeHost.Logs.Count(l => l.Contains("no bend-down or Return to wait for")) == 2, "both as no-bend-down pickups"); + long until = Field("_jumpPickupAirUntil"); + Check.True(Math.Abs(until - (jumpAt + ActionPacer.JumpLandMaxMs)) <= TickMs, + $"the window ends JumpLandMaxMs after the jump: {until - jumpAt} ms from it (the second send was {secondAt - jumpAt} ms in)"); + }); + + // Only "You're too busy" (0x1D) proves the no-bend-down call wrong. A save-failed with + // no code (a full pack, or anything else) that comes fast is not that evidence. + private static void NonBusyRefusalKeepsNoMotion() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true); + uint first = FakeHost.ExternalMoves[0].Id; + TickFor(tick, 100 - TickMs); + FakeHost.Containers[first] = Player; // no bend-down: the window opens + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1000); + Check.True(Field("_jumpPickupAirUntil") > _now, "the window is open"); + uint second = FakeHost.ExternalMoves[1].Id; + Check.True(Field("_currentLootItemSentInAirWindow"), "the second went out in it"); + TickFor(tick, 100); + FakeHost.WeenieError(0, 0x00A0, second); // InventoryServerSaveFailed, no code, 100 ms after the send + TickFor(tick, 3 * TickMs); + Check.False(FakeHost.Logs.Any(l => l.Contains("the server played a bend-down after all")), "no distrust line"); + Check.Eq(Field("_jumpNoMotionOffUntil"), 0L, "the call stays on"); + }); + + private static void NoJumpKeepsAnswerFloor() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: false, secondGem: false, stamina: 100u, serverGates: true); + Check.Eq(FakeHost.TapJumps, 0, "no jump went out"); + long sent = _now; + TickFor(tick, AnswerAtMs - TickMs); + FakeHost.Containers[GemA] = Player; + long confirmedAfter = ConfirmAfter(tick, GemA, sent); + Check.True(confirmedAfter >= RynthAiPlugin.PickupAnswerMinMs, + $"not believed before PickupAnswerMinMs ({RynthAiPlugin.PickupAnswerMinMs} ms): confirmed {confirmedAfter} ms after the send"); + }); + + // -- What JumpPickupHadNoMotion must not take for a no-bend-down pickup -- + + /// + /// After the last item's confirm: the next corpse is not opened while the Return plays + /// (CastBusy 1 for ), and is opened once it ends. + /// + private static void NextOpenWaitsReturn(Action tick, uint item, long returnMs, string what) + { + TickUntil(tick, () => Confirmed(item), 1500); + Check.True(Confirmed(item), what + ": the pickup is confirmed"); + TickFor(tick, returnMs); + Check.False(FakeHost.Uses.Contains(CorpseB), what + ": no next open while the Return plays"); + FakeHost.CastBusy = 0; + TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1500); + Check.True(FakeHost.Uses.Contains(CorpseB), what + ": the next corpse is opened once the character stands still"); + } + + private static void NoJumpFastAnswerWaitsReturn() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: false, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true); + TickFor(tick, 100 - TickMs); + FakeHost.Containers[GemA] = Player; + FakeHost.CastBusy = 1; // its Return + NextOpenWaitsReturn(tick, GemA, 300, "no jump"); + }); + + private static void ResentFastAnswerWaitsReturn() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true); + Check.Eq(FakeHost.TapJumps, 1, "the first send jumps"); + TickFor(tick, 40); + FakeHost.WeenieError(0x1D); // YoureTooBusy + FakeHost.WeenieError(0, 0x00A0, GemA); // InventoryServerSaveFailed(item) + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1000); + Check.Eq(FakeHost.ExternalMoves.Count, 2, "resent"); + Check.Eq(FakeHost.TapJumps, 1, "the resend goes without a jump"); + TickFor(tick, 100 - TickMs); + FakeHost.Containers[GemA] = Player; + FakeHost.CastBusy = 1; + NextOpenWaitsReturn(tick, GemA, 300, "resent"); + }); + + // On a fast server a real bend-down can be 0.25-0.4 s, inside PickupAnswerMinMs. + // A move sent on the no-bend-down call and refused 'too busy' proves the call wrong: it is off. + private static void BusyRefusalTurnsNoMotionOff() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, secondCorpse: true, serverGates: true, thirdGem: true); + uint first = FakeHost.ExternalMoves[0].Id; + FakeHost.CastBusy = 1; // a fast real bend-down, then its Return + TickFor(tick, 300 - TickMs); + FakeHost.Containers[first] = Player; // answered at 300 ms: taken for no bend-down + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1000); + Check.True(FakeHost.Logs.Any(l => l.Contains("no bend-down or Return to wait for")), "the first is (wrongly) called no bend-down"); + uint second = FakeHost.ExternalMoves[1].Id; + TickFor(tick, 40); + FakeHost.WeenieError(0x1D); // the Return is playing: too busy + FakeHost.WeenieError(0, 0x00A0, second); + TickFor(tick, 2 * TickMs); + Check.True(FakeHost.Logs.Any(l => l.Contains("the server played a bend-down after all")), "the call is turned off"); + Check.Eq(Field("_jumpPickupAirUntil"), 0L, "and the window ended"); + + TickFor(tick, 400); + FakeHost.CastBusy = 0; // the Return ends: the refused move goes again + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 3, 1000); + Check.Eq(FakeHost.ExternalMoves[2].Id, second, "the refused move is resent"); + TickFor(tick, 150); + FakeHost.Containers[second] = Player; + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 4, 1500); + Check.Eq(FakeHost.ExternalMoves.Count, 4, "the third goes"); + uint third = FakeHost.ExternalMoves[3].Id; + int at = FakeHost.Order.IndexOf($"move:{third:X8}"); + Check.True(at > 0 && FakeHost.Order[at - 1] == "tapjump", "with a jump (landed by now): " + Order()); + + // Answered at 300 ms again: with the call off it waits its Return. + FakeHost.CastBusy = 1; + TickFor(tick, 300 - TickMs); + FakeHost.Containers[third] = Player; + NextOpenWaitsReturn(tick, third, 300, "after the call was turned off"); + }); + + private static void BusyOpenTurnsNoMotionOff() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true); + TickFor(tick, 300 - TickMs); + FakeHost.Containers[GemA] = Player; // taken for no bend-down + TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1000); + Check.True(FakeHost.Uses.Contains(CorpseB), "the next corpse is opened on the call"); + Check.True(Field("_openInAirWindowSeq") >= 0, "its answer is watched"); + FakeHost.UseDone(0x1D); // too busy: the Return was playing + TickFor(tick, 2 * TickMs); + Check.True(FakeHost.Logs.Any(l => l.Contains("the next corpse's open, sent on it, was refused as too busy")), "the call is turned off"); + Check.True(Field("_jumpNoMotionOffUntil") > _now, "for a while"); + }); + + // The fastest cadence there is. The acclient holds ONE pending inventory request and refuses + // every other move until the server's answer about that object ("You can only move or use one + // item at a time", RynthCore ClientActionGates), and on a FastTick character ACE cancels a pickup + // whose turn is still pending when the next one arrives (Player_Move2.CreateMoveToChain2 -> + // CheckMoveToParams -> ActionCancelled). So never two at once: the next goes on the very tick + // the last one's answer shows, with no tick lost in between. + private static void OneInFlightNextOnAnswerTick() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true); + Air(up: true); + var answered = new HashSet(); + int maxInFlight = 1; + for (int k = 0; k < 3; k++) + { + Check.Eq(FakeHost.ExternalMoves.Count, k + 1, $"move {k + 1} is out"); + uint id = FakeHost.ExternalMoves[k].Id; + for (int i = 0; i < 4; i++) + { + _now += TickMs; tick(); + maxInFlight = Math.Max(maxInFlight, FakeHost.ExternalMoves.Count - answered.Count); + } + Check.Eq(FakeHost.ExternalMoves.Count, k + 1, $"nothing more while move {k + 1} is unanswered"); + FakeHost.Containers[id] = Player; // the answer arrives + answered.Add(id); + _now += TickMs; tick(); // the one tick that sees it + Check.True(Confirmed(id), $"move {k + 1} confirmed on the tick its answer shows"); + if (k < 2) + Check.Eq(FakeHost.ExternalMoves.Count, k + 2, $"and move {k + 2} goes on that same tick"); + } + Check.Eq(maxInFlight, 1, "never two moves in flight"); + }); + + // Dropping the corpse claim ends the no-bend-down window and the open watch. + private static void ResetEndsAirWindow() => Clocked(() => + { + LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true); + SetField("_jumpPickupAirUntil", _now + 1000); + SetField("_openInAirWindowSeq", 3); + typeof(RynthAiPlugin).GetMethod("ResetCorpseTarget", Any)!.Invoke(_bot, null); + Check.Eq(Field("_jumpPickupAirUntil"), 0L, "the window is gone"); + Check.Eq(Field("_openInAirWindowSeq"), -1, "and the open watch"); + }); + + // A pickup sent while the character is still in the air from the last loot jump takes no second + // jump: the move arrives in the air anyway, and ACE HandleActionJump has no ground check, so an + // air jump only costs stamina. Once the character has landed, the next pickup jumps again. + private static void NoSecondJumpInTheAir() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true); + long jumpAt = _now; + uint first = FakeHost.ExternalMoves[0].Id; + Check.Eq(FakeHost.TapJumps, 1, "the first pickup jumps"); + Air(up: true); // and stays up: no landing is seen + TickFor(tick, 100); + FakeHost.Containers[first] = Player; // the answer + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, ActionPacer.JumpLandMaxMs); + Check.Eq(FakeHost.ExternalMoves.Count, 2, "the second move is sent"); + Check.True(_now - jumpAt < ActionPacer.JumpLandMaxMs, $"(inside the first jump's flight: {_now - jumpAt} ms after it)"); + Check.True(ActionPacer.LootJumpAirborne(_host, out _), "(still in the air at the second send)"); + Check.Eq(FakeHost.TapJumps, 1, "no second jump in the air: " + Order()); + + uint second = FakeHost.ExternalMoves[1].Id; + Air(up: false); // landed + TickFor(tick, ActionPacer.JumpLandMinMs); // the landing check looks from JumpLandMinMs on + FakeHost.Containers[second] = Player; + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 3, 3000); + Check.Eq(FakeHost.ExternalMoves.Count, 3, "the third move is sent"); + int at = FakeHost.Order.IndexOf($"move:{FakeHost.ExternalMoves[2].Id:X8}"); + Check.True(at > 0 && FakeHost.Order[at - 1] == "tapjump", "landed: the third jumps again: " + Order()); + Check.Eq(FakeHost.TapJumps, 2, "two jumps in all"); + }); + + // The loot half: the pickup's jump is what holds combat and buffs (ActionPacer); loot is not held. + // CombatHookTests has the combat half (Think sends no attack while it holds). + private static void JumpHoldsCombatNotLoot() => Clocked(() => + { + bool pacer = ActionPacer.Enabled; + try + { + LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true); + Check.Eq(FakeHost.TapJumps, 1, "the pickup jumped"); + Check.True(ActionPacer.LootJumpAirborne(_host, out _), "and the loot code noted the jump for combat and buffs"); + // The pacer from here on, on this clock, with nothing of other tests' left in it + // (CorpseCloseTests.PacerOn): only the jump can hold anything. + ActionPacer.Reset(); ActionPacer.Enabled = true; + MoveAudit.Reset(); MoveAudit.NowMs = () => _now; + UseAudit.NowMs = () => _now; + ActionPacer.NoteLootJump(_host); // (Reset dropped the pickup's; the same jump, noted again) + var host = _host; + Air(up: true); + Check.True(ActionPacer.LootJumpAirborne(host, out string why), "in the air after the pickup's jump: " + why); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff or heal waits"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal too (ACE refuses it in the air)"); + Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "loot does not"); + _now += ActionPacer.JumpLandMinMs; + Check.True(ActionPacer.LootJumpAirborne(host, out _), "still up at the height check"); + Air(up: false); + Check.False(ActionPacer.LootJumpAirborne(host, out _), "landed: the hold ends"); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the buff goes"); + + // The cap: a landing never seen still ends the hold at JumpLandMaxMs. + ActionPacer.NoteLootJump(host); + Air(up: true); + _now += ActionPacer.JumpLandMaxMs - 1; + Check.True(ActionPacer.LootJumpAirborne(host, out _), "up, under the cap"); + _now += 1; + Check.False(ActionPacer.LootJumpAirborne(host, out _), "the cap ends it"); + } + finally + { + ActionPacer.Enabled = pacer; ActionPacer.Reset(); + MoveAudit.Reset(); MoveAudit.NowMs = () => Environment.TickCount64; + UseAudit.NowMs = () => Environment.TickCount64; + } + }); + + // The plugin's portal-space and death paths drop the hold: no landing is coming to end it. + private static void PortalAndDeathEndJumpHold() => Clocked(() => + { + var oldVitals = FakeHost.Vitals; + try + { + LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true); + var host = _host; + const System.Reflection.BindingFlags Inst = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + + Air(up: true); + Check.True(ActionPacer.LootJumpAirborne(host, out _), "the pickup's jump holds combat"); + FakeHost.Portaling = true; + typeof(RynthAiPlugin).GetMethod("NotePortalForPacer", Inst)!.Invoke(_bot, null); + Check.False(ActionPacer.LootJumpAirborne(host, out _), "portal space ends the hold"); + FakeHost.Portaling = false; + typeof(RynthAiPlugin).GetMethod("NotePortalForPacer", Inst)!.Invoke(_bot, null); + + ActionPacer.NoteLootJump(host); + Check.True(ActionPacer.LootJumpAirborne(host, out _), "a second jump holds again"); + FakeHost.Vitals = (0, 100, 0, 100, 0, 100); + typeof(RynthAiPlugin).GetMethod("HoldForDeath", Inst)!.Invoke(_bot, null); + Check.False(ActionPacer.LootJumpAirborne(host, out _), "the death ends the hold"); + } + finally { FakeHost.Vitals = oldVitals; FakeHost.Portaling = false; Air(up: false); } + }); + + private static void JumpWeakSignKeepsAnswerFloor() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true, packStack: true); + Check.Eq(FakeHost.TapJumps, 1, "the jump went out"); + long sent = _now; + TickFor(tick, AnswerAtMs - TickMs); + FakeHost.Containers[GemA] = 0; // an unowned stack; the pack stack has not grown + long confirmedAfter = ConfirmAfter(tick, GemA, sent); + Check.True(confirmedAfter >= RynthAiPlugin.PickupAnswerMinMs, + $"a weak sign keeps the floor ({RynthAiPlugin.PickupAnswerMinMs} ms): confirmed {confirmedAfter} ms after the send"); + }); + private static string Order() => string.Join(",", FakeHost.Order); private static void TwoItemJumpsBeforeMove() => Clocked(() => @@ -154,4 +714,63 @@ internal static class LootJumpTests LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 5u); Check.Eq(FakeHost.TapJumps + FakeHost.Jumps, 0, "stamina 5: no jump: " + Order()); }); + + // The flight holds heals (ACE refuses them in the air), so health under Heal At (60 by + // default) picks up with a bend-down; at Heal At the jump goes. + private static void LowHealthNoJump() => Clocked(() => + { + LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, health: 59u); + Check.Eq(FakeHost.TapJumps + FakeHost.Jumps, 0, "health 59 (Heal At 60): no jump: " + Order()); + Check.False(ActionPacer.LootJumpAirborne(_host, out _), "nothing held for a landing"); + LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, health: 60u); + Check.Eq(FakeHost.TapJumps, 1, "health 60: the jump goes: " + Order()); + }); + + // The flight budget (RynthAiPlugin.LootJumpFlightBudgetMs): a send in the air with no fresh jump + // is predicted by jumpAge + the recent no-bend-down answer time. + private static void FlightBudgetLetsEarlySendThrough() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true); + uint first = FakeHost.ExternalMoves[0].Id; + Air(up: true); + TickFor(tick, 100); + FakeHost.Containers[first] = Player; // answered 100 ms in, no bend-down + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 500); + Check.Eq(FakeHost.ExternalMoves.Count, 2, "the next send goes out at the confirm: " + Order()); + Check.Eq(FakeHost.TapJumps, 1, "in the air, with no new jump"); + Check.False(FakeHost.Logs.Any(l => l.Contains("holding 0x")), "no hold logged"); + }); + + private static void FlightBudgetHoldsLateSend() => Clocked(() => + { + var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true); + uint first = FakeHost.ExternalMoves[0].Id; + Air(up: true); + TickFor(tick, 460); + FakeHost.Containers[first] = Player; // answered ~480 ms in, still no bend-down (under the 500 ms mark) + TickUntil(tick, () => Confirmed(first), 300); + Check.True(Confirmed(first), "the first is confirmed"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no bend-down or Return to wait for")), "as a no-bend-down pickup"); + // jumpAge ~500 plus an answer that took ~480 ms is over the budget: the next one waits for the landing. + TickFor(tick, 400); + Check.Eq(FakeHost.ExternalMoves.Count, 1, "no send into the rest of the flight: " + Order()); + Check.Eq(FakeHost.TapJumps, 1, "no jump yet"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("holding 0x")), 1, "the hold is logged once"); + string hold = FakeHost.Logs.FirstOrDefault(l => l.Contains("holding 0x")) ?? "(none)"; + Check.True(hold.Contains("ms into the flight") && hold.Contains("takes about 4"), "naming jumpAge and the expected answer: " + hold); + Air(up: false); // landed + TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1500); + Check.Eq(FakeHost.ExternalMoves.Count, 2, "after the landing the next goes"); + int at = FakeHost.Order.IndexOf($"move:{FakeHost.ExternalMoves[1].Id:X8}"); + Check.True(at > 0 && FakeHost.Order[at - 1] == "tapjump", "with a fresh jump: " + Order()); + Check.Eq(FakeHost.TapJumps, 2, "two jumps in all"); + }); + + private static void ResetClearsFlightHoldLogged() => Clocked(() => + { + LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true); + SetField("_flightHoldLogged", true); + typeof(RynthAiPlugin).GetMethod("ResetCurrentLootItem", Any)!.Invoke(_bot, null); + Check.False(Field("_flightHoldLogged"), "hold-logged flag cleared"); + }); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs index 9b66c68..b57691f 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs @@ -40,10 +40,43 @@ internal static class ManaStoneChoiceTests r.Add("mana tapping: a stone that failed two drains stays parked though it reads empty", FailedStoneStaysParked); r.Add("mana tapping: in a fight the drain waits (holding no loot, taking no second item); after it, the drain goes", DrainWaitsForFight); r.Add("mana stones: in a fight, worn gear that runs low is still refilled (armor without mana drops its spells)", RefillInFight); + r.Add("eternal charge: tapping is ignored while it is in the pack, and applies again when it leaves", EternalIgnoresTapping); + r.Add("eternal charge: a use with no answer is tried again in 20 s, not 5 minutes", EternalRetriesSoon); } private const uint ChargeA = 0x80400031, ChargeB = 0x80400032, ChargeC = 0x80400033; private const string ManaCharge = "Great Mana Charge"; + private const string EternalCharge = "Eternal Mana Charge"; + + private static void EternalIgnoresTapping() + { + using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (ChargeA, null) }, ringToDrain: true, maceMana: 5000, contents: true, + before: _ => FakeHost.Names[ChargeA] = EternalCharge); + rig.Run(3000); + Check.True(rig.M.HasEternalChargeCached(), "the charge is seen"); + Check.Eq(rig.OnRing.Count, 0, "no drain, with an empty stone and an item waiting"); + Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "nothing looted to tap"); + Check.False(rig.M.HoldsLootForDrain(), "the looter isn't held"); + Check.True(rig.S.EnableManaTapping, "the setting itself is left alone"); + + rig.Destroy(ChargeA); + // The pack walk keeps its answer for a real second, and this test's clock runs faster than that. + System.Threading.Thread.Sleep(1100); + rig.Run(3000); + Check.False(rig.M.HasEternalChargeCached(), "the charge is gone"); + Check.Eq(rig.OnRing.Count, 1, "tapping applies again: the item is drained"); + } + + private static void EternalRetriesSoon() + { + using var rig = new Rig(tapping: false, new (uint, int?)[] { (ChargeA, null) }, stoneName: EternalCharge, maceMana: 0); + rig.Run(1000); + Check.Eq(rig.OnPlayer.Count, 1, "the charge goes on the gear"); + rig.Run(9000); // no answer: the action times out at 8 s + Check.Eq(rig.OnPlayer.Count, 1, "parked after the timeout"); + rig.Run(21_000); + Check.Eq(rig.OnPlayer.Count, 2, "tried again within 20 s of the timeout"); + } private const string NeedMore = "The Mana Stone gives 1,000 points of mana to the following items: Khanda-handled Mace.\nYou need 2,000 more mana to fully charge your items."; // 2026-10-11 report: armor ran dry overnight with Mana Charges in the pack. The prime suspect diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MeleeStallTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MeleeStallTests.cs index ad0946d..cbfd101 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MeleeStallTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MeleeStallTests.cs @@ -25,10 +25,53 @@ internal static class MeleeStallTests r.Add("ghost: skipped until the server updates or creates it, it moves, or the landblock changes", GhostTrackerClears); r.Add("ghost: combat skips a marked ghost, counts it in the lock line, and takes it back when the server updates it", GhostSkippedByCombat); r.Add("melee interval: the first swing at a new target doesn't wait out the old 1000 ms", PhysicalNewTargetInterval); + r.Add("melee reach: no closer after the re-issue = out of reach, left longer each time", ReachVerdict); + r.Add("melee reach: walking closer, next to it, or another target is not out of reach", ReachWorking); + r.Add("melee reach: after 5 in a row with no swing the ladder gets its turn (a wedged client); a swing starts over", ReachGivesWayToLadder); } private static readonly DateTime T0 = new(2026, 10, 12, 20, 47, 35); + private static void ReachVerdict() + { + var w = new MeleeReachWatch(); + w.NoteReissue(1, 4.5); + Check.True(w.CantReach(1, 4.6, DateTime.MinValue), "3 s later still 4.6 m off (the 2026-11-06 Olthoi behind a wall)"); + Check.Eq(w.NoteFailure(1, T0), 60, "first time: 60 s"); + w.NoteReissue(1, 4.5); + Check.True(w.CantReach(1, 4.5, DateTime.MinValue), "again"); + Check.Eq(w.NoteFailure(1, T0), 120, "second time: longer"); + Check.Eq(w.NoteFailure(1, T0), 240, "third"); + Check.Eq(w.NoteFailure(1, T0), 300, "capped at 5 minutes"); + w.Forget(1); + Check.Eq(w.NoteFailure(1, T0), 60, "forgotten: from the start"); + } + + private static void ReachWorking() + { + var w = new MeleeReachWatch(); + Check.False(w.CantReach(1, 4.5, DateTime.MinValue), "no re-issue yet: nothing measured"); + w.NoteReissue(1, 9.0); + Check.False(w.CantReach(1, 5.0, DateTime.MinValue), "closed 4 m: the walk is working"); + Check.False(w.CantReach(2, 9.0, DateTime.MinValue), "another target than the one measured"); + w.NoteReissue(1, 1.8); + Check.False(w.CantReach(1, 1.8, DateTime.MinValue), "next to it: a stall here isn't about walking, the ladder keeps it"); + } + + private static void ReachGivesWayToLadder() + { + var w = new MeleeReachWatch(); + for (int id = 1; id <= MeleeReachWatch.MaxStreak; id++) + { + w.NoteReissue(id, 4.5); + Check.True(w.CantReach(id, 4.5, DateTime.MinValue), $"target {id} of the streak"); + w.NoteFailure(id, T0); + } + w.NoteReissue(9, 4.5); + Check.False(w.CantReach(9, 4.5, DateTime.MinValue), "5 in a row and nothing swung: maybe the client, the ladder goes on"); + Check.True(w.CantReach(9, 4.5, T0.AddSeconds(1)), "a swing since: that streak is over"); + } + private static void EarlyStepWhenQuiet() { // Quiet (the caller's read: attacks sent, nothing animating, standing still). diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaResumeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaResumeTests.cs new file mode 100644 index 0000000..7f4a757 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaResumeTests.cs @@ -0,0 +1,294 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; +using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType; +using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Resume Meta After Reload (2026-11-07, Meta/MetaResume.cs). Tom: the meta should "restart in that state so +// Drakkon doesn't recall back every time", and "there might be some variables set in default of other +// states". A hot reload is modelled as what it is: the old MetaManager's runtime exported, then a NEW +// LegacyUiSettings + MetaManager built the way OnLoginComplete builds them (state Default, macro off, the +// meta's rules freshly loaded, no route), and the runtime restored into it. +internal static class MetaResumeTests +{ + private static readonly DateTime T0 = new(2026, 11, 7, 20, 0, 0); + + public static void Register(Runner r) + { + r.Add("meta resume: without it, a reload starts Default again and recalls (the reported problem)", WithoutResumeRecalls); + r.Add("meta resume: a reload carries on in the state, with Default's variables, no second recall, the route at its waypoint", ResumeCarriesOn); + r.Add("meta resume: after resuming, the meta runs on as before (timers continue, later states enter normally)", ResumedMetaRunsOn); + r.Add("meta resume: call stack, watchdog and dictionaries come back", StackWatchdogDicts); + r.Add("meta resume: stopwatches come back with their time (a map cooldown on a stopwatch fires again)", Stopwatches); + r.Add("meta resume: a state entered but not yet applied is entered afresh", EntryPending); + r.Add("meta resume: the file round-trips anything a variable holds; a torn file is nothing", FileFormat); + r.Add("meta resume: only this client, this character, recently, with the same meta", WhyNotChecks); + } + + private static List Loop() => new() + { + "uTank2 NAV 1.2", "1", "4", + "0", "10", "20", "0", "0", + "0", "10.1", "20", "0", "0", + "0", "10.1", "20.1", "0", "0", + "0", "10", "20.1", "0", "0", + }; + + // A meta shaped like the reported one: Default sets the run up and recalls, then the hunt runs a route. + private static List Meta() => new() + { + new() { State = "Default", Condition = C.Always, Action = A.ExpressionAction, ActionData = "setvar[mode, hunt]" }, + new() { State = "Default", Condition = C.Always, Action = A.ChatCommand, ActionData = "/lifestone" }, + new() { State = "Default", Condition = C.SecondsInState_GE, ConditionData = "5", Action = A.SetMetaState, ActionData = "Hunt" }, + new() { State = "Hunt", Condition = C.Always, Action = A.EmbeddedNavRoute, ActionData = "Loop" }, + new() { State = "Hunt", Condition = C.Expression, ConditionData = "getvar[mode]==`hunt`", Action = A.ExpressionAction, ActionData = "setvar[seen, getvar[seen]+1]" }, + new() { State = "Hunt", Condition = C.SecondsInState_GE, ConditionData = "100", Action = A.SetMetaState, ActionData = "Default" }, + }; + + private sealed class Client + { + public LegacyUiSettings S = null!; + public MetaManager M = null!; + public DateTime Now = T0; + private readonly RynthCoreHost _host; + + public Client(RynthCoreHost host) { _host = host; Login(running: true); } + + /// What OnLoginComplete builds: a new settings object and manager, Default, the meta loaded. + public void Login(bool running) + { + S = new LegacyUiSettings { IsMacroRunning = running, EnableMeta = true, CurrentState = "Default" }; + S.MetaRules = Meta(); + S.EmbeddedNavs["Loop"] = Loop(); + S.CurrentMetaPath = @"C:\Games\RynthSuite\RynthAi\MetaFiles\Hunt.af"; + M = new MetaManager(S, _host, new PlayerVitalsCache()) { Clock = () => Now }; + // Stopwatches on the same fake clock. A new copy's tick count has nothing to do with the old one's. + long reloadBase = ++_logins * 7_000_000L; + M.Expressions.TickMs = () => reloadBase + (long)(Now - T0).TotalMilliseconds; + } + + private int _logins; + + public void Tick(double seconds = 0) { Now = Now.AddSeconds(seconds); M.Think(); } + + public MetaResumeState Export() + { + var s = new MetaResumeState { ProcessId = 1, ProcessStartUtcTicks = 2, CharacterId = 3, SavedUtcTicks = T0.Ticks }; + M.ExportRuntime(s); + // Through the file format, as the plugin does. + Check.True(MetaResumeStore.TryParse(MetaResumeStore.Serialize(s), out MetaResumeState back), "the save parses"); + return back; + } + + public string Var(string name) => M.Expressions.Variables.TryGetValue(name, out string? v) ? v : "(unset)"; + } + + private static int Recalls() => FakeHost.ChatCommands.Count(c => c == "/lifestone"); + + /// Runs Default, moves to Hunt, loads the route and walks it to waypoint 2. + private static Client Hunting() + { + FakeHost.Reset(); + var c = new Client(FakeHost.Create(playerId: 0x50000A01)); + c.Tick(); // Default: mode=hunt, /lifestone + c.Tick(6); // 5 s in Default: -> Hunt + c.Tick(); // Hunt: route loaded, seen=1 + c.S.ActiveNavIndex = 2; // nav walked on + c.Tick(3); + Check.Eq(c.S.CurrentState, "Hunt", "hunting"); + Check.Eq(Recalls(), 1, "one recall at the start"); + Check.Eq(c.Var("seen"), "1", "Hunt's rule ran once"); + return c; + } + + private static void WithoutResumeRecalls() + { + Client c = Hunting(); + c.Login(running: true); // a reload without resume: Default again + c.Tick(); + Check.Eq(c.S.CurrentState, "Default", "back in Default"); + Check.Eq(Recalls(), 2, "and it recalls again"); + Check.Eq(c.S.CurrentRoute.Points.Count, 0, "the route is gone until Hunt loads it again"); + } + + private static void ResumeCarriesOn() + { + Client c = Hunting(); + int pointsBefore = c.S.CurrentRoute.Points.Count; + Check.Eq(pointsBefore, 4, "the route has its four waypoints"); + MetaResumeState saved = c.Export(); + c.Login(running: false); // the new copy: Default, macro off (Start Macro On Login off) + c.M.RestoreRuntime(saved); + for (int i = 0; i < 5; i++) c.Tick(1); + + Check.Eq(c.S.CurrentState, "Hunt", "still hunting"); + Check.True(c.S.IsMacroRunning, "the macro runs as it did"); + Check.Eq(Recalls(), 1, "no second recall"); + Check.Eq(c.Var("mode"), "hunt", "Default's variable is there"); + Check.Eq(c.Var("seen"), "1", "Hunt's rules that had fired don't fire again"); + Check.Eq(c.S.CurrentRoute.Points.Count, pointsBefore, "the route is back"); + Check.Eq(c.S.ActiveNavIndex, 2, "at the same waypoint"); + Check.Eq(c.S.CurrentNavPath, "", "the same route"); + Check.True(c.S.EnableNavigation, "nav on"); + } + + private static void ResumedMetaRunsOn() + { + Client c = Hunting(); // 3 s into Hunt + MetaResumeState saved = c.Export(); + Check.True(saved.SecondsInState >= 3 && saved.SecondsInState < 4, "seconds in state saved: " + saved.SecondsInState.ToString(CultureInfo.InvariantCulture)); + c.Login(running: false); + c.M.RestoreRuntime(saved); + c.Tick(90); + Check.Eq(c.S.CurrentState, "Hunt", "93 s in: still Hunt"); + c.Tick(8); // 101 s in Hunt, counting from before the reload + Check.Eq(c.S.CurrentState, "Default", "the 100 s timer counted across the reload"); + c.Tick(); + Check.Eq(Recalls(), 2, "entering Default for real runs it as always"); + } + + // 2026-11-07: a reload kept $MapSW ("SW:4") but not the stopwatch, which then read 0 s for ever, so the + // meta's "testvar[MapSW]==0||stopwatchelapsedseconds[$MapSW]>=$MapCool" never held and a treasure map + // sat in the pack unused. + private static void Stopwatches() + { + Client c = Hunting(); + string Eval(string e) => c.M.Expressions.Evaluate(e).ToString() ?? ""; + const string Cooldown = "testvar[MapSW]==0||stopwatchelapsedseconds[$MapSW]>=30"; + Eval("setvar[MapSW, stopwatchcreate[]];stopwatchstart[$MapSW]"); + Eval("setvar[Held, stopwatchcreate[]];stopwatchstart[$Held]"); + Eval("setvar[Idle, stopwatchcreate[]]"); + c.Tick(4); + Eval("stopwatchstop[$Held]"); + c.Tick(6); // MapSW 10 s, Held stopped at 4 s, Idle never started + Check.Eq(Eval("stopwatchelapsedseconds[$MapSW]"), "10", "10 s before the reload"); + Check.Eq(Eval(Cooldown), "0", "map cooldown still running"); + + MetaResumeState saved = c.Export(); + Check.Eq(saved.Stopwatches.Count, 3, "three stopwatches saved"); + c.Login(running: false); + Check.Eq(Eval("stopwatchelapsedseconds[$MapSW]"), "0", "(a new copy knows no stopwatches)"); + c.M.RestoreRuntime(saved); + + Check.Eq(Eval("stopwatchelapsedseconds[$MapSW]"), "10", "the stopwatch is back at 10 s"); + Check.Eq(Eval("stopwatchelapsedseconds[$Held]"), "4", "a stopped one keeps its time"); + Check.Eq(Eval("stopwatchelapsedseconds[$Idle]"), "0", "one never started is still at 0"); + c.Tick(21); + Check.Eq(Eval("stopwatchelapsedseconds[$MapSW]"), "31", "it runs on after the reload"); + Check.Eq(Eval("stopwatchelapsedseconds[$Held]"), "4", "the stopped one doesn't"); + Check.Eq(Eval(Cooldown), "1", "the map cooldown ends (it never did before)"); + Eval("stopwatchstart[$Held]"); + c.Tick(2); + Check.Eq(Eval("stopwatchelapsedseconds[$Held]"), "6", "a restored stopwatch starts again from its time"); + string fresh = Eval("stopwatchcreate[]"); + Check.True(!saved.Stopwatches.ContainsKey(fresh), "a new stopwatch never reuses a saved handle: " + fresh); + + string text = MetaResumeStore.Serialize(saved); + Check.False(MetaResumeStore.TryParse(text.Replace("sw=SW%3A0|", "sw=SW%3A0|x"), out _), "a bad stopwatch time is nothing"); + Check.True(MetaResumeStore.TryParse(text.Replace("sw=", "zz="), out MetaResumeState old), "an older save without stopwatches still parses"); + Check.Eq(old.Stopwatches.Count, 0, "(and has none)"); + } + + private static void StackWatchdogDicts() + { + FakeHost.Reset(); + var c = new Client(FakeHost.Create(playerId: 0x50000A01)); + c.S.MetaRules = new List + { + new() { State = "Default", Condition = C.Always, Action = A.ExpressionAction, ActionData = "setvar[d, dictcreate[]]" }, + new() { State = "Default", Condition = C.Always, Action = A.ExpressionAction, ActionData = "dictadditem[getvar[d], loot, 7]" }, + new() { State = "Default", Condition = C.Always, Action = A.CallMetaState, ActionData = "Buff" }, + new() { State = "Buff", Condition = C.Always, Action = A.SetWatchdog, ActionData = "Stuck;5;60" }, + new() { State = "Buff", Condition = C.SecondsInState_GE, ConditionData = "30", Action = A.ReturnFromCall }, + }; + c.Tick(); + c.Tick(); + c.Tick(2); + Check.Eq(c.S.CurrentState, "Buff", "called into Buff"); + MetaResumeState saved = c.Export(); + Check.Eq(saved.CallStack.Count, 1, "one call deep"); + Check.True(saved.WatchdogActive, "watchdog armed: " + saved.WatchdogState); + + var rules = c.S.MetaRules; + c.Login(running: false); + c.S.MetaRules = rules.Select(r => new MetaRule { State = r.State, Condition = r.Condition, ConditionData = r.ConditionData, Action = r.Action, ActionData = r.ActionData }).ToList(); + c.M.RestoreRuntime(saved); + Check.Eq(c.M.Expressions.Evaluate("dictgetitem[getvar[d], loot]").ToString(), "7", "the dictionary behind the handle is back"); + c.Tick(29); + Check.Eq(c.S.CurrentState, "Default", "the Return pops the restored stack"); + } + + private static void EntryPending() + { + Client c = Hunting(); + c.M.Expressions.Evaluate("setmetastate[Default]"); // asked for, not applied by a tick yet + MetaResumeState saved = c.Export(); + Check.True(saved.EntryPending, "pending entry saved"); + Check.Eq(saved.FiredRules.Count, 0, "the old state's fired marks aren't carried"); + c.Login(running: false); + c.M.RestoreRuntime(saved); + c.Tick(); + Check.Eq(c.S.CurrentState, "Default", "Default entered"); + Check.Eq(Recalls(), 2, "entered for real, as the tick would have"); + } + + private static void FileFormat() + { + var s = new MetaResumeState + { + ProcessId = 4321, ProcessStartUtcTicks = 638_000_000_000_000_000, CharacterId = 0x50000A01, SavedUtcTicks = T0.Ticks, + MetaPath = @"C:\Metas\Odd|name,with:colons.af", RulesSignature = "6:ABCDEF", MacroRunning = true, + State = "Hunt | 2", SecondsInState = 12.5, SecondsInStateP = 40.25, EntryPending = false, + WatchdogActive = true, WatchdogState = "Stuck", WatchdogMeters = 5, WatchdogSeconds = 60, WatchdogSecondsLeft = 41.5, + NextDictId = 9, NavPath = "", NavIndex = 3, NavEnabled = true, + }; + s.CallStack.Add(("Default", 3.5)); + s.CallStack.Add(("Buff", null)); + s.FiredRules.AddRange(new[] { 0, 4, 7 }); + s.Variables["note"] = "line one\nline two | with, commas: and ="; + s.Variables["empty"] = ""; + s.Dicts["D:3"] = new Dictionary { ["k:1"] = "v,1", ["k2"] = "" }; + s.RouteLines.AddRange(Loop()); + + string text = MetaResumeStore.Serialize(s); + Check.True(MetaResumeStore.TryParse(text, out MetaResumeState b), "parses"); + Check.Eq(b.MetaPath, s.MetaPath, "path"); + Check.Eq(b.State, s.State, "state"); + Check.Eq(b.Variables["note"], s.Variables["note"], "a variable with newlines and separators"); + Check.Eq(b.Variables["empty"], "", "an empty variable"); + Check.Eq(b.Dicts["D:3"]["k:1"], "v,1", "a dictionary"); + Check.Eq(string.Join(";", b.CallStack.Select(x => x.State + "=" + (x.PSeconds?.ToString(CultureInfo.InvariantCulture) ?? "-"))), "Default=3.5;Buff=-", "call stack, bottom first"); + Check.Eq(string.Join(",", b.FiredRules), "0,4,7", "fired rules"); + Check.Eq(b.RouteLines.Count, s.RouteLines.Count, "route lines"); + Check.Eq(b.WatchdogSecondsLeft, 41.5, "watchdog time left"); + Check.False(MetaResumeStore.TryParse(text.Replace("end=1\n", ""), out _), "a torn file (no end) is nothing"); + Check.False(MetaResumeStore.TryParse("something else\n" + text, out _), "another header is nothing"); + Check.False(MetaResumeStore.TryParse(text.Replace("secs=12.5", "secs=abc"), out _), "a bad number is nothing"); + } + + private static void WhyNotChecks() + { + List rules = Meta(); + string sig = MetaResumeStore.Signature(rules); + var s = new MetaResumeState { ProcessId = 10, ProcessStartUtcTicks = 20, CharacterId = 30, SavedUtcTicks = T0.Ticks, MetaPath = @"C:\M\a.af", RulesSignature = sig }; + DateTime now = T0.AddMinutes(1); + Check.Null(MetaResumeStore.WhyNot(s, 10, 20, 30, @"c:\m\A.af", sig, now), "same client, character and meta (path case ignored)"); + Check.NotNull(MetaResumeStore.WhyNot(s, 11, 20, 30, @"C:\M\a.af", sig, now), "another client"); + Check.NotNull(MetaResumeStore.WhyNot(s, 10, 21, 30, @"C:\M\a.af", sig, now), "a restarted client with the same pid"); + Check.NotNull(MetaResumeStore.WhyNot(s, 10, 20, 31, @"C:\M\a.af", sig, now), "another character"); + Check.NotNull(MetaResumeStore.WhyNot(s, 10, 20, 30, @"C:\M\b.af", sig, now), "another meta"); + Check.NotNull(MetaResumeStore.WhyNot(s, 10, 20, 30, @"C:\M\a.af", sig, T0.AddMinutes(11)), "too old"); + rules[1].ActionData = "/recall"; + Check.NotNull(MetaResumeStore.WhyNot(s, 10, 20, 30, @"C:\M\a.af", MetaResumeStore.Signature(rules), now), "the meta's rules were edited"); + Check.Eq(MetaResumeStore.Signature(Meta()), sig, "the same rules sign the same"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MissileAmmoSwapTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MissileAmmoSwapTests.cs new file mode 100644 index 0000000..b590990 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MissileAmmoSwapTests.cs @@ -0,0 +1,658 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.CreatureData; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The owner's report, 2026-11-07: "if you swap from bow to crossbow, it unwields your bow and your +// infinite arrows and wields your crossbow, but not your infinite quarrels. So you dry fire." +// Servers make their own infinite ammo: a single item that doesn't stack, UnlimitedUse (known once +// appraised), names with no arrow/quarrel in them, sometimes no AmmoType at all. Combat wielded the +// new ammo only right after its own launcher swap (30 s, and only when a fitting stack was found when +// the swap began); any other empty quiver was left to ammo crafting, which knows ammo by name only. +// +// The fights here run against a small simulated ACE (Player_Inventory.CheckWeaponCollision): a +// launcher is refused while ammo of another type (or of none) is on, ammo is refused when both it +// and the launcher in hand have a type and they differ, taking ammo off in Missile mode drops to +// peace, and Missile mode is refused with a launcher and nothing it can shoot. +internal static class MissileAmmoSwapTests +{ + private const uint Player = 0x50000F01; + private const uint Monster = 0x80001F01; + private const uint Wcid = 515151; + private const uint Bow = 0x80000F01, Crossbow = 0x80000F02, Axe = 0x80000F03, Wand = 0x80000F04; + private const uint InfArrows = 0x80000F11, InfQuarrels = 0x80000F12, DeadlyQuarrels = 0x80000F13, Arrows = 0x80000F14; + private const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000, MissileSlot = 0x00400000, AmmoSlot = 0x00800000, + HeldSlot = 0x01000000, TwoHandedSlot = 0x02000000; + private const int MainSlots = MeleeSlot | MissileSlot | HeldSlot | TwoHandedSlot; + private static int I(uint id) => unchecked((int)id); + + public static void Register(Runner r) + { + r.Add("missile ammo (owner 2026-11-07): the rules - infinite, ammo of no type, the pick order", Rules); + r.Add("missile ammo: the owner's report - bow + infinite arrows -> crossbow: arrows off, crossbow on, infinite quarrels on, then Missile", OwnersReport); + r.Add("missile ammo: infinite ammo of no AmmoType and an odd name: off before the crossbow, the crossbow's own goes on (not the bow's)", UntypedInfinite); + r.Add("missile ammo: UnlimitedUse on a stack (read after the appraisal) beats a better finite stack", UnlimitedUseWins); + r.Add("missile ammo: a crossbow in hand with an empty quiver that combat didn't swap gets its quarrels (was left to crafting)", EmptyQuiverNotOurSwap); + r.Add("missile ammo: the ammo still goes on when the crossbow lands after the 30 s swap window", AfterTheWindow); + r.Add("missile ammo: arrows on with a crossbow in hand - no shot; the arrows off, then quarrels", WrongAmmoInHand); + r.Add("missile ammo: no ammo the launcher can shoot - one chat line, no wield, no shot; quarrels found later go on", NoAmmoSaysOnce); + r.Add("missile ammo: bow -> thrown weapon puts the arrows away first and wields no ammo for it; back to the bow, the arrows go on", ThrownWeapon); + r.Add("missile ammo: Fast Weapon Swap from the wand (a monster while healing): arrows off, the crossbow, then quarrels, then Missile", FastSwapFromWand); + r.Add("missile ammo: weapons back after heals puts the bow back with its arrows in the pack: they go on when the fight starts (Fast Weapon Swap on and off)", WeaponsBackAfterHeals); + r.Add("missile ammo: a launcher named for bolts is not its own ammo (no dry fire)", LauncherNotItsOwnAmmo); + r.Add("missile crafting: a crossbow not named so, with its odd-named quarrels on, is left alone (no arrows at it)", CraftingKnowsTypes); + r.Add("missile crafting: odd-named quarrels in the pack are wielded for that crossbow", CraftingWieldsOddNamed); + } + + // ── Pure rules ──────────────────────────────────────────────────────────── + + private static void Rules() + { + Check.True(MissileAmmo.LooksInfinite(true, 50, 250, "Arrow"), "UnlimitedUse: infinite, stack or not"); + Check.True(MissileAmmo.LooksInfinite(false, 0, 0, "Stormcaller's Sheaf"), "a single item with no stack: infinite"); + Check.True(MissileAmmo.LooksInfinite(false, 1, 1, "Sheaf"), "a stack of 1 that can't grow: infinite"); + Check.False(MissileAmmo.LooksInfinite(false, 1, 250, "Arrow"), "the last arrow of a stack is not infinite"); + Check.True(MissileAmmo.LooksInfinite(false, 40, 250, "Infinite Deadly Prismatic Arrow"), "named so"); + + Check.True(MissileAmmo.CanShoot(2, 2), "quarrels in a crossbow"); + Check.True(MissileAmmo.CanShoot(2, 0), "ammo of no type: the server lets it on with any launcher"); + Check.False(MissileAmmo.CanShoot(2, 1), "arrows in a crossbow: no"); + Check.False(MissileAmmo.CanShoot(0, 0), "no launcher type: no"); + Check.False(MissileAmmo.Fits(2, 0), "but ammo of no type must come off before a launcher is wielded"); + + var rank = MissileAmmo.RankBy("", null); + var deadly = new AmmoCandidate(1, "Deadly Quarrel", 2, "Pierce", false, 300, -1, false); + var inf = new AmmoCandidate(2, "Stormcaller's Sheaf", 2, "", false, 1, -1, false, Infinite: true); + var untypedInf = new AmmoCandidate(3, "Quiver of Echoes", 0, "", false, 1, -1, false, Infinite: true); + var untypedInf2 = new AmmoCandidate(4, "Sylvan Volley", 0, "", false, 1, -1, false, Infinite: true); + var arrows = new AmmoCandidate(5, "Arrow", 1, "", false, 1, -1, false); + Check.Eq(MissileAmmo.Choose(2, "", new List { deadly, inf }, rank)?.Id, 2, "infinite beats a better finite stack (it never runs out)"); + Check.Eq(MissileAmmo.Choose(2, "", new List { deadly, inf with { Infinite = false } }, rank)?.Id, 1, "a single item flagged not infinite: quality decides as before"); + Check.Eq(MissileAmmo.Choose(2, "", new List { untypedInf, inf }, rank)?.Id, 2, "the launcher's own type before ammo of no type"); + Check.Eq(MissileAmmo.Choose(2, "", new List { arrows, untypedInf }, rank)?.Id, 3, "ammo of no type is still a pick"); + Check.Eq(MissileAmmo.Choose(2, "", new List { untypedInf2, untypedInf }, rank, demoteId: 4)?.Id, 3, "not the stack just taken off the other launcher"); + Check.Eq(MissileAmmo.Choose(2, "", new List { deadly with { ListIndex = 2 }, inf }, rank)?.Id, 1, "a listed stack still comes first"); + Check.Null(MissileAmmo.Choose(2, "", new List { arrows }, rank), "only arrows: nothing for a crossbow"); + } + + // ── The simulated server ──────────────────────────────────────────────────── + + private static int SlotOf(uint id) => FakeHost.Ints.TryGetValue((id, 9), out int s) ? s : 0; + private static int TypeOf(uint id) => FakeHost.Ints.TryGetValue((id, 50), out int t) ? t : 0; + private static bool On(uint id, int slot) => FakeHost.Equipped.TryGetValue(id, out uint at) && (at & slot) != 0; + private static uint InSlot(int slot) => FakeHost.Equipped.Where(kv => (kv.Value & slot) != 0).Select(kv => kv.Key).FirstOrDefault(); + private static bool IsThrown(uint id) => FakeHost.Ints.TryGetValue((id, 11), out int max) && max > 1 && SlotOf(id) == MissileSlot; + private static bool IsLauncher(uint id) => SlotOf(id) == MissileSlot && !IsThrown(id); + + private static void Wield(uint id, int slot) + { + FakeHost.Equipped[id] = (uint)slot; + FakeHost.Ints[(id, 10)] = slot; + EquippedState.Invalidate(); + } + + private static void Unwield(uint id) + { + FakeHost.Equipped.Remove(id); + FakeHost.Ints.Remove((id, 10)); + EquippedState.Invalidate(); + } + + /// The fake server's view: can the character shoot now (a launcher and ammo it takes, or a thrown weapon)? + private static bool ServerCanShoot() + { + uint main = InSlot(MissileSlot); + if (main == 0) return false; + if (IsThrown(main)) return true; + uint ammo = InSlot(AmmoSlot); + return ammo != 0 && (TypeOf(ammo) == 0 || TypeOf(main) == 0 || TypeOf(ammo) == TypeOf(main)); + } + + private sealed class Server + { + public double AnswerMs = 80, StanceMs = 400; + /// Extra time before the server answers a use of this item (a slow server). + public readonly Dictionary SlowUse = new(); + public readonly List Refusals = new(); + private readonly List<(double At, Action Do)> _due = new(); + private int _moves, _wields, _uses, _modes; + + public void Observe(double now) + { + while (FakeHost.CombatModeRequests.Count > _modes) + { + int mode = FakeHost.CombatModeRequests[_modes++]; + _due.Add((now + StanceMs, () => + { + // ACE: a launcher with nothing it can shoot can't enter Missile mode. + if (mode == CombatMode.Missile && !ServerCanShoot()) { Refusals.Add("Missile mode with nothing to shoot"); return; } + FakeHost.CombatModeValue = mode; + })); + } + while (FakeHost.Moves.Count > _moves) + { + uint id = FakeHost.Moves[_moves++].Id; + _due.Add((now + AnswerMs, () => + { + bool wasAmmo = On(id, AmmoSlot); + Unwield(id); + // ACE TryDequipObjectWithNetworking: ammo off in Missile mode drops to peace (a thrown weapon keeps Missile). + if (wasAmmo && FakeHost.CombatModeValue == CombatMode.Missile && !IsThrown(InSlot(MissileSlot))) + FakeHost.CombatModeValue = CombatMode.NonCombat; + })); + } + while (FakeHost.Wields.Count > _wields) + { + var w = FakeHost.Wields[_wields++]; + _due.Add((now + AnswerMs, () => TryWield(w.Id, (int)w.Mask, clientUse: false))); + } + while (FakeHost.Uses.Count > _uses) + { + uint id = FakeHost.Uses[_uses++]; + double extra = SlowUse.TryGetValue(id, out double x) ? x : 0; + _due.Add((now + AnswerMs * 2 + extra, () => TryWield(id, SlotOf(id), clientUse: true))); + } + } + + public void Answer(double now) + { + foreach (var d in _due.Where(d => d.At <= now).ToList()) { d.Do(); _due.Remove(d); } + } + + private void TryWield(uint id, int slot, bool clientUse) + { + if (slot == 0) return; + // The client's own use takes off what's in the way in the hands (never the ammo: ACE's check below). + if (clientUse && (slot & MainSlots) != 0) + foreach (uint other in FakeHost.Equipped.Where(kv => kv.Key != id && (kv.Value & MainSlots) != 0).Select(kv => kv.Key).ToList()) Unwield(other); + if (clientUse && slot == AmmoSlot && InSlot(AmmoSlot) is uint old && old != 0 && old != id) + Unwield(old); + if (slot == MissileSlot && IsLauncher(id)) + { + uint ammo = InSlot(AmmoSlot); + if (TypeOf(id) != 0 && ammo != 0 && TypeOf(ammo) != TypeOf(id)) { Refuse(id, $"launcher 0x{id:X8} with ammo 0x{ammo:X8} of type {TypeOf(ammo)} on"); return; } + } + if (slot == AmmoSlot) + { + uint main = InSlot(MissileSlot); + if (main != 0 && TypeOf(main) != 0 && TypeOf(id) != 0 && TypeOf(main) != TypeOf(id)) { Refuse(id, $"ammo 0x{id:X8} of type {TypeOf(id)} at launcher type {TypeOf(main)}"); return; } + } + if (slot == HeldSlot && FakeHost.Equipped.Any(kv => kv.Key != id && (kv.Value & (MeleeSlot | ShieldSlot | MissileSlot | TwoHandedSlot)) != 0)) + { Refuse(id, "a caster with a hand full"); return; } + if ((slot & MainSlots) != 0 && FakeHost.Equipped.Any(kv => kv.Key != id && (kv.Value & MainSlots) != 0)) + { Refuse(id, $"0x{id:X8} with the main hand full"); return; } + Wield(id, slot); + } + + private void Refuse(uint id, string why) + { + Refusals.Add(why); + FakeHost.WeenieError(0x0029, 0x00A0, id); + } + } + + // ── The rig ─────────────────────────────────────────────────────────────── + + private sealed class Sim : IDisposable + { + public readonly LegacyUiSettings S; + public readonly CombatManager C; + public readonly MonsterDamageStore Store = new(); + public readonly Server Sv = new(); + public readonly WeaponSwapGate Gate; + public readonly WorldObject Target = new(I(Monster), "Drudge Skulker", AcObjectClass.Monster); + public double SimMs; + private static readonly DateTime T0 = new(2026, 11, 7, 20, 0, 0); + public DateTime Now => T0.AddMilliseconds(SimMs); + public readonly List Trace = new(); + /// Times combat said "ready to attack" while the fake server had nothing to shoot. + public int DryReady; + private const BindingFlags NP = BindingFlags.Instance | BindingFlags.NonPublic; + private readonly MethodInfo _equip = typeof(CombatManager).GetMethod("EquipWeaponAndSetStance", NP)!; + private readonly MethodInfo _tickSwap = typeof(CombatManager).GetMethod("TickRearmSwap", NP)!; + + /// The items and what is on, before the host and cache read them. + public Sim(Action arrange, uint[] listed, int mode = CombatMode.Missile, bool fastSwap = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.WieldCalls = true; + FakeHost.EquippedCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.WeenieErrorCalls = true; + FakeHost.CombatModeValue = mode; + RynthClock.TestNow = () => Now; + EquippedState.Clock = () => (long)SimMs + 100_000; + ActionPacer.Enabled = false; + + Item(Bow, "Longbow", 0x100, MissileSlot, ammoType: 1); + Item(Crossbow, "Heavy Crossbow", 0x100, MissileSlot, ammoType: 2); + Item(Wand, "Wand", 0x8000, HeldSlot); + arrange(); + FakeHost.Wcids[Monster] = Wcid; + + S = new LegacyUiSettings { IsMacroRunning = true, FastWeaponSwap = fastSwap, PeaceModeWhenIdle = false, WieldUnlistedWandWhenNoneListed = false }; + S.ItemRules = listed.Select(i => new ItemRule { Id = I(i), Name = FakeHost.Names[i], Element = "", ElementSource = "", Action = "Weapon" }).ToList(); + var host = FakeHost.Create(Player); + var ids = new[] { Bow, Crossbow, Axe, Wand, InfArrows, InfQuarrels, DeadlyQuarrels, Arrows }.Where(FakeHost.Names.ContainsKey).ToList(); + var cache = FakeHost.MakeCache(host, Player, ids); + C = new CombatManager(host, S, cache); + C.SetPlayerId(Player); + C.SetDamageStores(null, Store); + C.CanCastOverride = _ => false; + C.OpenPackOverride = () => I(Player); + C.OffhandReadMs = 0; + C.SwapTracker.MinDwellMs = 0; + C.LastVitalCastAt = () => DateTime.MinValue; + C.BuffingWantsTick = () => false; + C.SwapBurstEnabled = () => false; + Gate = new WeaponSwapGate { MinIntervalMs = 0, NowMs = () => (long)SimMs + 100_000 }; + C.SetWeaponSwapGate(Gate); + typeof(CombatManager).GetField("_activeTargetId", NP)!.SetValue(C, I(Monster)); + } + + public void Dispose() + { + RynthClock.TestNow = null; + EquippedState.Clock = null; + EquippedState.Invalidate(); + ActionPacer.Enabled = false; + ActionPacer.Reset(); + } + + public static void Item(uint id, string name, uint itemType, int validSlots, int ammoType = 0, int stack = 0, int maxStack = 0) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = itemType; + FakeHost.Ints[(id, 9)] = validSlots; + if (ammoType != 0) FakeHost.Ints[(id, 50)] = ammoType; + if (stack != 0) FakeHost.Ints[(id, 12)] = stack; + if (maxStack != 0) FakeHost.Ints[(id, 11)] = maxStack; + } + + /// The Damage tab's weapon for this monster. + public void Wants(uint weapon) => Store.SetManualWeapon(Wcid, weapon); + + /// One plugin tick (25 ms): the server's answers, the hands-swap heartbeat, combat's equip. + public bool Tick() + { + Sv.Answer(SimMs); + _tickSwap.Invoke(C, null); + bool ready = (bool)_equip.Invoke(C, new object[] { Target, "Auto" })!; + if (ready && !ServerCanShoot()) DryReady++; + Sv.Observe(SimMs); + string line = $"mode={FakeHost.CombatModeValue} on={string.Join(",", FakeHost.Equipped.Keys.Select(k => FakeHost.Names[k]))} ready={ready}"; + if (Trace.Count == 0 || !Trace[^1].EndsWith(line, StringComparison.Ordinal)) Trace.Add($"{SimMs:0} {line}"); + SimMs += 25; + return ready; + } + + /// Ticks until combat is ready to attack in Missile mode (true) or pass. + public bool RunUntilShooting(double maxMs) + { + double end = SimMs + maxMs; + while (SimMs <= end) + if (Tick() && FakeHost.CombatModeValue == CombatMode.Missile) return true; + return false; + } + + public void Run(double ms) { double end = SimMs + ms; while (SimMs <= end) Tick(); } + + public string Why() => + Environment.NewLine + string.Join(Environment.NewLine, Trace.TakeLast(20)) + Environment.NewLine + + string.Join(Environment.NewLine, FakeHost.Logs.Where(l => l.Contains("[EquipDiag]")).TakeLast(20)) + + (Sv.Refusals.Count > 0 ? Environment.NewLine + "refused: " + string.Join("; ", Sv.Refusals) : ""); + } + + // ── The fights ──────────────────────────────────────────────────────────── + + /// Infinite ammo as a custom server makes it: one item, no stack, a name of its own, its AmmoType set. + private static void CustomInfinite() + { + Sim.Item(InfArrows, "Sylvan Volley", 0x100, AmmoSlot, ammoType: 1); + Sim.Item(InfQuarrels, "Stormcaller's Sheaf", 0x100, AmmoSlot, ammoType: 2); + Sim.Item(DeadlyQuarrels, "Deadly Quarrel", 0x100, AmmoSlot, ammoType: 2, stack: 80, maxStack: 250); + } + + private static void OwnersReport() + { + using var sim = new Sim(() => + { + CustomInfinite(); + Wield(Bow, MissileSlot); + Wield(InfArrows, AmmoSlot); + }, new[] { Bow, Crossbow }); + sim.Wants(Crossbow); + + Check.True(sim.RunUntilShooting(6000), "shooting with the crossbow within 6 s:" + sim.Why()); + Check.True(On(Crossbow, MissileSlot), "the crossbow in hand"); + Check.True(On(InfQuarrels, AmmoSlot), "the infinite quarrels on (over the Deadly finite ones):" + sim.Why()); + Check.False(On(InfArrows, AmmoSlot), "the infinite arrows off"); + Check.True(FakeHost.Moves.Count >= 1 && FakeHost.Moves[0].Id == InfArrows, "the arrows went into the pack first"); + int crossbowUse = FakeHost.Uses.IndexOf(Crossbow), quarrelUse = FakeHost.Uses.IndexOf(InfQuarrels); + Check.True(crossbowUse >= 0 && quarrelUse > crossbowUse, "the crossbow, then its quarrels: " + string.Join(",", FakeHost.Uses.Select(u => FakeHost.Names[u]))); + Check.False(FakeHost.Uses.Contains(DeadlyQuarrels), "the finite quarrels were never wielded"); + Check.Eq(sim.Sv.Refusals.Count, 0, "the server refused nothing: " + string.Join("; ", sim.Sv.Refusals)); + Check.Eq(sim.DryReady, 0, "never ready to shoot with nothing to shoot"); + Check.True(FakeHost.Logs.Any(l => l.Contains("ammo in:") && l.Contains("Stormcaller")), "the ammo landing is logged"); + Check.False(sim.C.AmmoSwapInProgress, "crafting may run again"); + } + + private static void UntypedInfinite() + { + using var sim = new Sim(() => + { + // Neither has an AmmoType or an ammo name: the ammunition slot is all that says what they are. + Sim.Item(InfArrows, "Sylvan Volley", 0x100, AmmoSlot); + Sim.Item(InfQuarrels, "Quiver of Echoes", 0x100, AmmoSlot); + Wield(Bow, MissileSlot); + Wield(InfArrows, AmmoSlot); + }, new[] { Bow, Crossbow }); + sim.Wants(Crossbow); + + var pack = sim.C.PackAmmo(); + Check.Eq(pack.Count, 2, "both are ammo (the ammunition slot), no name or AmmoType needed"); + Check.True(pack.All(a => a.Untyped && a.Infinite), "of no type, and infinite (single items)"); + + Check.True(sim.RunUntilShooting(6000), "shooting with the crossbow:" + sim.Why()); + Check.True(FakeHost.Moves.Any(m => m.Id == InfArrows), "the bow's ammo came off before the crossbow (ACE refuses a launcher with ammo of no type on)"); + Check.True(On(InfQuarrels, AmmoSlot), "the other one went on, not the one just taken off the bow:" + sim.Why()); + Check.False(FakeHost.Uses.Contains(InfArrows), "the bow's ammo was not put back on"); + Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused: " + string.Join("; ", sim.Sv.Refusals)); + Check.Eq(sim.DryReady, 0, "no dry fire"); + } + + private static void UnlimitedUseWins() + { + using var sim = new Sim(() => + { + Sim.Item(InfQuarrels, "Quarrel", 0x100, AmmoSlot, ammoType: 2, stack: 50, maxStack: 250); + Sim.Item(DeadlyQuarrels, "Deadly Quarrel", 0x100, AmmoSlot, ammoType: 2, stack: 80, maxStack: 250); + Wield(Crossbow, MissileSlot); + }, new[] { Crossbow }); + sim.Wants(Crossbow); + + var before = sim.C.PackAmmo(); + Check.False(before.Any(a => a.Infinite), "not appraised yet: two plain stacks"); + FakeHost.Bools[(InfQuarrels, 63)] = true; // the appraisal: UnlimitedUse + var after = sim.C.PackAmmo(); + Check.True(after.First(a => a.Id == I(InfQuarrels)).Infinite, "UnlimitedUse read: infinite"); + + Check.True(sim.RunUntilShooting(4000), "shooting:" + sim.Why()); + Check.True(On(InfQuarrels, AmmoSlot), "the UnlimitedUse quarrels went on, over the Deadly ones"); + } + + private static void EmptyQuiverNotOurSwap() + { + using var sim = new Sim(() => + { + CustomInfinite(); + Wield(Crossbow, MissileSlot); // put in hand by the player, or a meta: no ammo on + }, new[] { Bow, Crossbow }, mode: CombatMode.NonCombat); + sim.Wants(Crossbow); + + Check.True(sim.RunUntilShooting(4000), "shooting:" + sim.Why()); + Check.True(On(InfQuarrels, AmmoSlot), "combat wielded the quarrels itself"); + Check.Eq(FakeHost.Uses.Count(u => u == InfQuarrels), 1, "once"); + Check.Eq(FakeHost.CombatModeRequests.FirstOrDefault(), CombatMode.Missile, "Missile asked for only after the ammo"); + Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused: " + string.Join("; ", sim.Sv.Refusals)); + Check.Eq(sim.DryReady, 0, "no dry fire"); + Check.True(FakeHost.Logs.Any(l => l.Contains("none it can shoot was on")), "the log says why"); + } + + private static void AfterTheWindow() + { + using var sim = new Sim(() => + { + CustomInfinite(); + Wield(Bow, MissileSlot); + Wield(InfArrows, AmmoSlot); + }, new[] { Bow, Crossbow }); + sim.Wants(Crossbow); + // The server holds the crossbow's wield for 31 s (slow, not refusing: no resend meanwhile). + sim.Sv.SlowUse[Crossbow] = 31_000; + sim.C.SwapTracker.ResolveMs = 60_000; + + Check.True(RunUntil(sim, () => FakeHost.Uses.Contains(Crossbow), 4000), "the crossbow wield goes out:" + sim.Why()); + Check.True(RunUntil(sim, () => On(Crossbow, MissileSlot), 33_000), "the crossbow lands 31 s later:" + sim.Why()); + var until = (DateTime)typeof(CombatManager).GetField("_ammoFollowUpUntil", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(sim.C)!; + Check.True(until < sim.Now, "the 30 s swap window is over"); + Check.Eq(FakeHost.Uses.Count(u => u == InfQuarrels), 0, "no quarrels before the crossbow landed"); + Check.True(sim.RunUntilShooting(4000), "its quarrels still go on, and it shoots:" + sim.Why()); + Check.True(On(InfQuarrels, AmmoSlot), "the infinite quarrels"); + Check.Eq(sim.DryReady, 0, "no dry fire"); + } + + private static bool RunUntil(Sim sim, Func until, double maxMs) + { + double end = sim.SimMs + maxMs; + while (sim.SimMs <= end) { sim.Tick(); if (until()) return true; } + return false; + } + + private static void WrongAmmoInHand() + { + using var sim = new Sim(() => + { + CustomInfinite(); + Wield(Crossbow, MissileSlot); + Wield(InfArrows, AmmoSlot); // a hand swap on a server that let it be + }, new[] { Bow, Crossbow }, mode: CombatMode.NonCombat); + sim.Wants(Crossbow); + + var has = typeof(CombatManager).GetMethod("HasWieldedAmmo", BindingFlags.Instance | BindingFlags.NonPublic)!; + Check.False((bool)has.Invoke(sim.C, null)!, "arrows with a crossbow in hand are not ammo to shoot (a dry fire before)"); + + Check.True(sim.RunUntilShooting(5000), "shooting:" + sim.Why()); + Check.True(FakeHost.Moves.Any(m => m.Id == InfArrows), "the arrows into the pack"); + Check.True(On(InfQuarrels, AmmoSlot), "then the quarrels"); + Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused: " + string.Join("; ", sim.Sv.Refusals)); + Check.Eq(sim.DryReady, 0, "no dry fire"); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Missile), 1, "one Missile request, after the quarrels"); + } + + private static void NoAmmoSaysOnce() + { + using var sim = new Sim(() => + { + Sim.Item(Arrows, "Arrow", 0x100, AmmoSlot, ammoType: 1, stack: 100, maxStack: 250); + Wield(Crossbow, MissileSlot); + }, new[] { Crossbow }, mode: CombatMode.NonCombat); + sim.Wants(Crossbow); + sim.S.EnableMissileCrafting = false; + + sim.Run(3000); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("No quarrels for Heavy Crossbow")), 1, "said in chat once: " + string.Join(" | ", FakeHost.Chat)); + Check.Eq(FakeHost.Uses.Count, 0, "no wield (arrows don't fit a crossbow)"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Missile request"); + Check.Eq(sim.DryReady, 0, "never ready to shoot"); + Check.Eq(sim.C.LastCombatSkipReason, "no-ammo", "the hold is the no-ammo one (not a stall)"); + + // Quarrels turn up (looted, bought, given): they go on. + Sim.Item(InfQuarrels, "Stormcaller's Sheaf", 0x100, AmmoSlot, ammoType: 2); + var cache = (WorldObjectCache)typeof(CombatManager).GetField("_worldFilter", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(sim.C)!; + _ = cache[I(InfQuarrels)]; + ForceRescan(cache); + Check.True(sim.RunUntilShooting(4000), "the new quarrels go on and it shoots:" + sim.Why()); + Check.True(On(InfQuarrels, AmmoSlot), "on"); + + // Gone again: said again, once. + Unwield(InfQuarrels); + FakeHost.Names.Remove(InfQuarrels); + FakeHost.Ints.Remove((InfQuarrels, 9)); + FakeHost.Ints.Remove((InfQuarrels, 50)); + ForceRescan(cache); + sim.Run(2000); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("No quarrels for Heavy Crossbow")), 2, "said again after it ran out, once"); + } + + private static void ForceRescan(WorldObjectCache cache) => + typeof(WorldObjectCache).GetField("_lastDirectInventoryScan", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(cache, DateTime.MinValue); + + private static void ThrownWeapon() + { + using var sim = new Sim(() => + { + Sim.Item(Arrows, "Arrow", 0x100, AmmoSlot, ammoType: 1, stack: 100, maxStack: 250); + Sim.Item(Axe, "Throwing Axe", 0x100, MissileSlot, stack: 30, maxStack: 50); + Wield(Bow, MissileSlot); + Wield(Arrows, AmmoSlot); + }, new[] { Bow, Axe }); + sim.Wants(Axe); + + Check.True(sim.RunUntilShooting(5000), "throwing with the axe:" + sim.Why()); + Check.True(On(Axe, MissileSlot), "the axe in hand"); + Check.False(On(Arrows, AmmoSlot), "the arrows are not left on"); + Check.True(FakeHost.Moves.Any(m => m.Id == Arrows), "the arrows went into the pack"); + Check.True(FakeHost.Uses.IndexOf(Axe) >= 0, "the axe was wielded"); + Check.False(FakeHost.Uses.Contains(Arrows), "no ammo wielded for the thrown weapon"); + Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused: " + string.Join("; ", sim.Sv.Refusals)); + Check.Eq(sim.DryReady, 0, "no dry fire"); + + // Back to the bow: the arrows go on after it. + sim.Wants(Bow); + Check.True(RunUntil(sim, () => On(Bow, MissileSlot) && On(Arrows, AmmoSlot), 5000), "the bow and its arrows:" + sim.Why()); + Check.True(sim.RunUntilShooting(3000), "shooting with the bow again:" + sim.Why()); + Check.True(FakeHost.Uses.LastIndexOf(Arrows) > FakeHost.Uses.LastIndexOf(Bow), "the bow, then the arrows"); + Check.Eq(sim.DryReady, 0, "no dry fire"); + } + + private static void FastSwapFromWand() + { + using var sim = new Sim(() => + { + CustomInfinite(); + Wield(Wand, HeldSlot); // healing: the wand in hand, the bow's arrows still on + Wield(InfArrows, AmmoSlot); + }, new[] { Bow, Crossbow }, mode: CombatMode.Magic); + sim.Wants(Crossbow); + + Check.True(sim.RunUntilShooting(6000), "shooting with the crossbow:" + sim.Why()); + Check.True(FakeHost.Logs.Any(l => l.Contains("weapons for the fight")), "Fast Weapon Swap's hands swap ran:" + sim.Why()); + Check.True(FakeHost.Moves.Any(m => m.Id == InfArrows), "the arrows into the pack"); + Check.True(FakeHost.Moves.Any(m => m.Id == Wand), "the wand into the pack"); + Check.True(FakeHost.Wields.Any(w => w.Id == Crossbow && w.Mask == (uint)MissileSlot), "the crossbow wielded into the missile slot:" + sim.Why()); + Check.True(On(InfQuarrels, AmmoSlot), "then its infinite quarrels"); + Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused (no crossbow with the arrows on): " + string.Join("; ", sim.Sv.Refusals)); + Check.Eq(sim.DryReady, 0, "no dry fire"); + Check.Eq(sim.Gate.HeldBy, "", "the swap gate is free"); + } + + /// + /// A bow -> crossbow swap was cut short by a heal (the arrows already in the pack, the wand on), and + /// weapons back after heals put the last fight's bow back: that swap moves hands only, never ammo, + /// and no launcher swap of combat's armed an ammo step, so the bow stood with an empty quiver. + /// + private static void WeaponsBackAfterHeals() + { + foreach (bool fast in new[] { true, false }) + { + using var sim = new Sim(() => + { + Sim.Item(Arrows, "Arrow", 0x100, AmmoSlot, ammoType: 1, stack: 100, maxStack: 250); + Wield(Wand, HeldSlot); + }, new[] { Bow, Crossbow, Wand }, mode: CombatMode.Magic, fastSwap: fast); + const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic; + sim.S.RearmAfterVitals = true; + typeof(CombatManager).GetField("_fightMainId", F)!.SetValue(sim.C, I(Bow)); + DateTime heal = sim.Now.AddSeconds(-2); + sim.C.LastVitalCastAt = () => heal; + typeof(CombatManager).GetField("_activeTargetId", F)!.SetValue(sim.C, 0); + var step = typeof(CombatManager).GetMethod("RearmAfterVitalsStep", F)!; + var tick = typeof(CombatManager).GetMethod("TickRearmSwap", F)!; + for (int i = 0; i < 200 && !On(Bow, MissileSlot); i++) + { + sim.Sv.Answer(sim.SimMs); + tick.Invoke(sim.C, null); + step.Invoke(sim.C, null); + sim.Sv.Observe(sim.SimMs); + sim.SimMs += 25; + } + string label = fast ? "Fast Weapon Swap on" : "Fast Weapon Swap off"; + Check.True(On(Bow, MissileSlot), $"{label}: weapons back put the bow in hand:" + sim.Why()); + Check.False(On(Arrows, AmmoSlot), $"{label}: its arrows are still in the pack (weapons back moves hands only)"); + + // A monster: combat's equip finds the bow with nothing to shoot, and puts the arrows on. + typeof(CombatManager).GetField("_activeTargetId", F)!.SetValue(sim.C, I(Monster)); + sim.Wants(Bow); + Check.True(sim.RunUntilShooting(4000), $"{label}: shooting with the bow:" + sim.Why()); + Check.True(On(Arrows, AmmoSlot), $"{label}: the arrows went on"); + Check.Eq(sim.DryReady, 0, $"{label}: no dry fire"); + } + } + + private static void LauncherNotItsOwnAmmo() + { + using var sim = new Sim(() => + { + Sim.Item(Crossbow, "Thunderbolt Arbalest", 0x100, MissileSlot, ammoType: 2); + Wield(Crossbow, MissileSlot); + }, new[] { Crossbow }); + var has = typeof(CombatManager).GetMethod("HasWieldedAmmo", BindingFlags.Instance | BindingFlags.NonPublic)!; + Check.False((bool)has.Invoke(sim.C, null)!, "an empty quiver, whatever the launcher's name says"); + sim.Wants(Crossbow); + sim.Run(1500); + Check.Eq(sim.DryReady, 0, "no shot"); + } + + // ── Ammo crafting ───────────────────────────────────────────────────────── + + private static MissileCraftingManager CraftRig(bool sheafOn, out WorldObjectCache cache) + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.SalvageCalls = true; // GetObjectWielderInfo (answers from Wielded) + FakeHost.Names[Player] = "Archer"; + Sim.Item(Crossbow, "Siege Arbalest", 0x100, MissileSlot, ammoType: 2); // no "crossbow" in the name + Sim.Item(InfQuarrels, "Stormcaller's Sheaf", 0x100, AmmoSlot, ammoType: 2); + Sim.Item(Arrows, "Arrow", 0x100, AmmoSlot, ammoType: 1, stack: 100, maxStack: 250); + FakeHost.Wielded[Crossbow] = MissileSlot; + FakeHost.Containers[Arrows] = Player; + if (sheafOn) FakeHost.Wielded[InfQuarrels] = AmmoSlot; + else FakeHost.Containers[InfQuarrels] = Player; + var host = FakeHost.Create(Player); + cache = FakeHost.MakeCache(host, Player, new[] { Crossbow, InfQuarrels, Arrows }); + var cm = new MissileCraftingManager(host, new LegacyUiSettings { EnableMissileCrafting = true }); + cm.SetObjectCache(cache); + return cm; + } + + private static void CraftStep(MissileCraftingManager cm, WorldObjectCache cache) + { + const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic; + if (cm.State == MissileCraftingManager.CraftState.Idle) typeof(MissileCraftingManager).GetField("_lastAmmoCheck", F)!.SetValue(cm, DateTime.MinValue); + else typeof(MissileCraftingManager).GetField("_phaseStart", F)!.SetValue(cm, DateTime.Now.AddSeconds(-1)); + ForceRescan(cache); + EquippedState.Invalidate(); + cm.ProcessCrafting(); + } + + private static void CraftingKnowsTypes() + { + var cm = CraftRig(sheafOn: true, out var cache); + for (int i = 0; i < 3; i++) CraftStep(cm, cache); + Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "quarrels on: nothing to do"); + Check.Eq(FakeHost.Uses.Count, 0, "no arrows wielded at the arbalest (read as a bow by its name before)"); + Check.False(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no")), "no evaluation every 5 s"); + } + + private static void CraftingWieldsOddNamed() + { + var cm = CraftRig(sheafOn: false, out var cache); + for (int i = 0; i < 3 && !FakeHost.Uses.Any(); i++) CraftStep(cm, cache); + Check.True(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no Quarrel") && l.Contains("'Siege Arbalest'")), "the arbalest is a crossbow (its AmmoType): " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("MissileCraft")))); + Check.Eq(FakeHost.Uses.LastOrDefault(), InfQuarrels, "the odd-named quarrels are wielded, not the arrows"); + Check.True(cm.LastAmmoEquipAt != DateTime.MinValue, "the wield time is kept (combat waits a moment after it)"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MonsterStatsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterStatsTests.cs index 45d4ff3..8ae9c00 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MonsterStatsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterStatsTests.cs @@ -48,6 +48,239 @@ internal static class MonsterStatsTests r.Add("monster stats: /ra mstats prints a monster's numbers, lists, resets, and says why not with the usage", Command); r.Add("monster stats: the Monster Stats window is in RynthAi's manifest and passes the engine's parser", ManifestWindow); r.Add("monster stats: the window's view is published at login and while the window is on screen", WindowView); + r.Add("kill XP (11-08): a rise after the kill, a rise before it, a quest's rise ignored, two kills two rises", XpMatcher); + r.Add("kill XP (11-08): the session rows count XP and XP kills; the save keeps them and reads an older save", XpInRowsAndSave); + r.Add("kill XP (11-08): the learned table averages the last kills and round-trips through its file", XpTableRoundTrip); + r.Add("kill XP (11-08): through the plugin - kill notice + TotalExperience rise -> the row's xp/xk, /ra mstats, the learned table", XpPluginWiring); + r.Add("death time (11-08): a kill's corpse is timed; another monster's, a late one, or another object isn't", CorpseTimerPairs); + r.Add("death time (11-08): rows carry it (cd, cn, 'corpse after 2.1 s'); the save keeps it and reads older saves; the table keeps it", CorpseTimeInRowsAndTable); + } + + // ── Death animation (2026-11-08) ───────────────────────────────────── + + private static void CorpseTimerPairs() + { + Check.Eq(CorpseTimer.KilledName("Corpse of Drudge Skulker"), "Drudge Skulker", "the name in a corpse's"); + Check.Null(CorpseTimer.KilledName("Drudge Skulker"), "not a corpse"); + Check.Null(CorpseTimer.KilledName("Corpse of "), "no name"); + var t = new CorpseTimer(); + t.OnKill("Drudge Skulker", 1000); + Check.Null(t.OnCorpse("Corpse of Mosswart Worshipper", 2000), "another monster's corpse"); + Check.Null(t.OnCorpse("Black Opal", 2000), "not a corpse"); + Check.True(t.OnCorpse("Corpse of drudge skulker", 3100) is ("Drudge Skulker", 2100), "the kill's corpse 2.1 s later (any case)"); + Check.Eq(t.Waiting, 0, "and the kill is done"); + t.OnKill("Drudge Skulker", 10_000); + t.OnKill("Drudge Skulker", 10_200); // a ring: two of them + Check.True(t.OnCorpse("Corpse of Drudge Skulker", 12_000) is (_, 2000), "the first corpse to the first kill"); + Check.True(t.OnCorpse("Corpse of Drudge Skulker", 12_300) is (_, 2100), "the second to the second"); + t.OnKill("Drudge Skulker", 20_000); + Check.Null(t.OnCorpse("Corpse of Drudge Skulker", 20_000 + t.WindowMs + 1), "past the window: not its death"); + Check.Eq(t.Waiting, 0, "dropped"); + t.OnKill(" ", 1); + Check.Eq(t.Waiting, 0, "no name: nothing waits"); + } + + private static void CorpseTimeInRowsAndTable() + { + var s = new MonsterCombatStats(); + s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0, _ => "Drudge Skulker"); + s.OnCorpseTime("Drudge Skulker", 2000, T0); + s.OnCorpseTime("Drudge Skulker", 2200, T0); + MonsterStatsRow r = s.Get("Drudge Skulker")!; + Check.Eq((r.CorpseMs, r.CorpseKills), (4200L, 2), "summed and counted"); + Check.Near(r.CorpseAvgMs ?? 0, 2100, 1e-9, "2.1 s on average"); + string json = RynthAiPlugin.MonsterStatsJson(r); + Check.True(json.Contains("\"cd\":2100") && json.Contains("\"cn\":2"), "mstats has cd (ms) and cn: " + json); + Check.True(MonsterStatsText.ChatLines(r)[0].Contains("corpse after 2.1 s"), "/ra mstats: " + MonsterStatsText.ChatLines(r)[0]); + Check.True(MonsterStatsText.ListLine(r).Contains("corpse after 2.1 s"), "the list line"); + Check.True(MonsterStatsText.DetailRows(r).Any(d => d.Label == "Death" && d.Mine.Contains("corpse after 2.1 s")), "the window's detail"); + + var save = new MonsterStatsSave { ProcessId = 1, ProcessStartUtcTicks = 2, CharacterId = 3, SavedUtcTicks = T0.Ticks, SinceUtcTicks = T0.Ticks, Rows = s.Snapshot().ToList() }; + string text = MonsterStatsStore.Serialize(save); + Check.True(MonsterStatsStore.TryParse(text, out MonsterStatsSave back) && back.Rows.Single() == r, "the save keeps it"); + string withXpOnly = string.Join("\n", text.Split('\n').Select(l => l.StartsWith("m=") ? string.Join("\t", l.Split('\t').Take(18)) : l)); + Check.True(MonsterStatsStore.TryParse(withXpOnly, out MonsterStatsSave mid) && mid.Rows.Single().CorpseKills == 0, "a save with XP but no corpse times reads"); + + string dir = TempDir("ms-deathtable"); + try + { + var t = new MonsterXpTable(); + t.SetCharacter(dir); + t.RecordDeath("Drudge Skulker", 2000); + t.RecordDeath("Drudge Skulker", 2400); + t.Record("Drudge Skulker", 500); + Check.Near(t.DeathMs("Drudge Skulker") ?? 0, 2200, 1e-9, "learned death"); + Check.Null(t.DeathMs("Mosswart"), "none known"); + t.SaveIfDirty(); + var next = new MonsterXpTable(); + next.SetCharacter(dir); + Check.True(next.DeathMs("Drudge Skulker") is double dm && Math.Abs(dm - 2200) < 1 && next.DeathsTimed("Drudge Skulker") == 2 + && next.XpPerKill("Drudge Skulker") == 500, "both kept across logins in one file"); + } + finally + { + try { Directory.Delete(dir, true); } catch { } + } + } + + // ── Experience per kill (2026-11-08) ───────────────────────────────── + + private static void XpMatcher() + { + var m = new KillXpMatcher(); + Check.Eq(m.OnTotal(1_000_000, T0).Count, 0, "the first value read is the starting point"); + Check.Eq(m.OnTotal(1_000_000, T0.AddSeconds(0.1)).Count, 0, "no change"); + + // A rise after the kill. + Check.Eq(m.OnKill("Drudge Skulker", T0.AddSeconds(1)).Count, 0, "a kill waits for its rise"); + var got = m.OnTotal(1_000_500, T0.AddSeconds(1.4)); + Check.True(got.Count == 1 && got[0].Name == "Drudge Skulker" && got[0].Xp == 500, "the rise 0.4 s later is its XP"); + + // A rise before the kill notice (the server's order can be either). + Check.Eq(m.OnTotal(1_001_300, T0.AddSeconds(5)).Count, 0, "a rise waits for a kill"); + got = m.OnKill("Mosswart Worshipper", T0.AddSeconds(5.6)); + Check.True(got.Count == 1 && got[0].Name == "Mosswart Worshipper" && got[0].Xp == 800, "the kill 0.6 s later takes it"); + + // A quest's rise: no kill near it. + Check.Eq(m.OnTotal(1_101_300, T0.AddSeconds(10)).Count, 0, "a quest turn-in"); + Check.Eq(m.OnTotal(1_101_300, T0.AddSeconds(11.5)).Count, 0, "waited past RiseWaitSec"); + Check.Eq(m.WaitingRises, 0, "and dropped"); + Check.Eq(m.OnKill("Drudge Skulker", T0.AddSeconds(12)).Count, 0, "a later kill doesn't take the quest's XP"); + + // That kill gave nothing seen: past KillWaitSec it goes, and a later rise isn't its. + Check.Eq(m.OnTotal(1_101_300, T0.AddSeconds(15.5)).Count, 0, "no rise in KillWaitSec"); + Check.Eq(m.WaitingKills, 0, "the kill stopped waiting"); + Check.Eq(m.OnTotal(1_102_000, T0.AddSeconds(16)).Count, 0, "a rise after that is no kill's"); + + // Two kills (a ring spell), two rises. + m.OnKill("Drudge Skulker", T0.AddSeconds(20)); + m.OnKill("Drudge Ravener", T0.AddSeconds(20.1)); + var a = m.OnTotal(1_102_400, T0.AddSeconds(20.3)); + var b = m.OnTotal(1_103_100, T0.AddSeconds(20.5)); + Check.True(a.Count == 1 && a[0].Name == "Drudge Skulker" && a[0].Xp == 400, "the first rise to the first kill"); + Check.True(b.Count == 1 && b[0].Name == "Drudge Ravener" && b[0].Xp == 700, "the second to the second"); + + // A lower total (another character): a new starting point, no rise. + Check.Eq(m.OnTotal(50, T0.AddSeconds(30)).Count, 0, "lower: starts over"); + m.OnKill("Drudge Skulker", T0.AddSeconds(31)); + Check.True(m.OnTotal(80, T0.AddSeconds(31.2)) is { Count: 1 } r && r[0].Xp == 30, "and counts from there"); + m.Reset(); + Check.Eq(m.OnTotal(999, T0.AddSeconds(40)).Count, 0, "after a reset the first value is the start again"); + Check.Eq(m.OnKill(" ", T0).Count + m.WaitingKills, 0, "no name: nothing waits"); + } + + private static void XpInRowsAndSave() + { + var s = new MonsterCombatStats(); + s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0, _ => "Drudge Skulker"); + s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0); + s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0); + int v = s.Version; + s.OnKillXp("Drudge Skulker", 1_000_000, T0); + s.OnKillXp("Drudge Skulker", 1_469_134, T0); + s.OnKillXp("Drudge Skulker", 0, T0); // nothing + Check.True(s.Version > v, "the version moves"); + MonsterStatsRow r = s.Get("Drudge Skulker")!; + Check.Eq((r.Kills, r.Xp, r.XpKills), (3, 2_469_134L, 2), "3 kills, 2 with XP seen"); + Check.Near(r.XpPerKill ?? 0, 1_234_567, 1e-9, "XP/kill over the kills with XP seen"); + Check.Null(new MonsterStatsRow("x", 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0).XpPerKill, "none seen: no XP/kill"); + + string json = RynthAiPlugin.MonsterStatsJson(r); + Check.True(json.Contains("\"xp\":2469134") && json.Contains("\"xk\":2"), "mstats has xp and xk: " + json); + Check.True(MonsterStatsText.ChatLines(r)[0].Contains("XP/kill 1,234,567"), "/ra mstats: " + MonsterStatsText.ChatLines(r)[0]); + Check.True(MonsterStatsText.ListLine(r).Contains("XP/kill 1,234,567"), "the list line: " + MonsterStatsText.ListLine(r)); + Check.Eq(MonsterStatsText.XpCell(r), "1,234,567", "the window's cell"); + Check.True(MonsterStatsText.DetailRows(r).Any(d => d.Label == "XP" && d.Mine.Contains("XP/kill 1,234,567")), "the window's detail"); + + var save = new MonsterStatsSave { ProcessId = 1, ProcessStartUtcTicks = 2, CharacterId = 3, SavedUtcTicks = T0.Ticks, SinceUtcTicks = T0.Ticks, Rows = s.Snapshot().ToList() }; + string text = MonsterStatsStore.Serialize(save); + Check.True(MonsterStatsStore.TryParse(text, out MonsterStatsSave back) && back.Rows.Single() == r, "the save keeps XP and XP kills"); + // A save from before 11-08: 16 fields a row. + string older = string.Join("\n", text.Split('\n').Select(l => l.StartsWith("m=") ? string.Join("\t", l.Split('\t').Take(16)) : l)); + Check.True(MonsterStatsStore.TryParse(older, out MonsterStatsSave old) && old.Rows.Single().Kills == 3 && old.Rows.Single().XpKills == 0, + "an older save reads, with no XP"); + var loaded = new MonsterCombatStats(); + loaded.Load(back.Rows); + Check.Eq(loaded.Get("Drudge Skulker")!.Xp, 2_469_134L, "Load keeps the XP"); + } + + private static void XpTableRoundTrip() + { + string dir = TempDir("ms-xptable"); + try + { + var t = new MonsterXpTable(); + t.Record("Drudge Skulker", 1000); // no character yet: kept in memory + t.SaveIfDirty(); + Check.False(Directory.Exists(dir), "no character, no file"); + t.SetCharacter(dir); + Check.Eq(t.FilePath, Path.Combine(dir, MonsterXpTable.FileName), "next to the character's settings: " + t.FilePath); + Check.Null(t.XpPerKill("Drudge Skulker"), "a character's table starts from its file (none yet)"); + t.Record("Drudge Skulker", 1000); + t.Record("Drudge Skulker", 2000); + Check.Near(t.XpPerKill("drudge skulker") ?? 0, 1500, 1e-9, "the first kills count fully (any case)"); + for (int i = 0; i < 200; i++) t.Record("Olthoi Slayer", 100); + for (int i = 0; i < 100; i++) t.Record("Olthoi Slayer", 300); + Check.Near(t.XpPerKill("Olthoi Slayer") ?? 0, 300, 3, "follows the last ~20 kills (a new level, a bonus weekend)"); + t.Record("Zero", 0); + t.Record("", 50); + Check.Eq(t.Count, 2, "no zero XP or empty name"); + t.SaveIfDirty(); + Check.True(File.Exists(t.FilePath), "saved"); + + var next = new MonsterXpTable(); // the next login + next.SetCharacter(dir); + Check.Near(next.XpPerKill("Drudge Skulker") ?? 0, 1500, 0.01, "loaded at login"); + Check.Eq(next.KillsCounted("Drudge Skulker"), 2, "with its count"); + Check.Eq(next.KillsCounted("Olthoi Slayer"), 300, "every kill counted"); + File.AppendAllText(next.FilePath, "X|Bad|abc|3\nY|later|1|2\nX|Neg|-5|3\n"); + var odd = new MonsterXpTable(); + odd.SetCharacter(dir); + Check.Eq(odd.Count, 2, "bad lines and a later version's lines are skipped"); + odd.SetCharacter(""); + Check.True(odd.Count == 0 && odd.FilePath.Length == 0, "detached: empty"); + } + finally + { + try { Directory.Delete(dir, true); } catch { } + } + } + + private static void XpPluginWiring() + { + string dir = TempDir("ms-xpwire"), charDir = TempDir("ms-xpchar"); + try + { + var rig = new Rig(dir); + rig.Call("SetXpTableCharacter", charDir); + FakeHost.Quads[(Player, 1)] = 5_000_000; + rig.Call("TickMonsterStats"); // the starting point + rig.Set("_currentCombatMode", CombatMode.Melee); + rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 30)); + rig.Call("NoteMonsterStatsKill", "You killed Drudge Skulker!"); + FakeHost.Quads[(Player, 1)] = 5_250_000; + rig.Call("TickMonsterStats"); + MonsterStatsRow r = rig.Stats.Get("Drudge Skulker")!; + Check.Eq((r.Kills, r.Xp, r.XpKills), (1, 250_000L, 1), "the kill's XP on its row"); + Check.Near(rig.P.XpPerKill("Drudge Skulker") ?? 0, 250_000, 1e-9, "and in the learned table"); + + FakeHost.Quads[(Player, 1)] = 5_400_000; // a quest: no kill + rig.Call("TickMonsterStats"); + Check.Eq(rig.Stats.Get("Drudge Skulker")!.Xp, 250_000L, "a rise with no kill isn't a monster's"); + + var lines = rig.Typed("/ra mstats Drudge Skulker"); + Check.True(lines.Count == 3 && lines[0].Text.Contains("XP/kill 250,000"), "/ra mstats says it: " + Show(lines)); + rig.Call("ShutdownMonsterStats"); + Check.True(File.Exists(Path.Combine(charDir, MonsterXpTable.FileName)), "the table is saved at unload"); + rig.Call("OnLogoutMonsterStats"); + Check.Eq(rig.Stats.Count, 0, "logout clears the session's rows"); + Check.Near(rig.P.XpPerKill("Drudge Skulker") ?? 0, 250_000, 1e-9, "the learned table stays"); + } + finally + { + try { Directory.Delete(dir, true); } catch { } + try { Directory.Delete(charDir, true); } catch { } + } } private static readonly DateTime T0 = new(2026, 10, 30, 12, 0, 0, DateTimeKind.Utc); @@ -734,7 +967,9 @@ internal static class MonsterStatsTests Check.Eq((I("sw"), I("ev"), I("sp"), I("rs"), I("ne")), (5, 1, 3, 1, 1), "your side: 3 hits + the killing blow, 1 evaded; 3 spells, 1 resisted, 1 no effect"); Check.Eq((I("at"), I("yev"), I("ysp"), I("yrs"), I("yne")), (2, 1, 2, 1, 0), "its side"); Check.Eq((I("k"), I("dd"), I("dt")), (1, 70, 16), "kill and damage (30 + 40 dealt, 7 + 9 taken)"); - Check.Eq(m.EnumerateObject().Count(), 13, "the thirteen fields"); + Check.Eq((I("xp"), I("xk")), (0, 0), "no XP seen yet (2026-11-08 fields)"); + Check.Eq((I("cd"), I("cn")), (0, 0), "no corpse timed yet (2026-11-08 fields)"); + Check.Eq(m.EnumerateObject().Count(), 17, "the seventeen fields"); } Check.False(rows["Mosswart Worshipper"].TryGetProperty("mstats", out _), "a monster without numbers has none"); Check.True(rows["Drudge Skulker"].TryGetProperty("key", out _) && rows["Drudge Skulker"].TryGetProperty("kills", out _), "the row's own fields are all still there"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NativeAttackTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NativeAttackTests.cs new file mode 100644 index 0000000..731667e --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NativeAttackTests.cs @@ -0,0 +1,228 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The native attack wedge (2026-11-06, DreamWeave, a melee character dual-wielding two Hand +// Wraps): a buff-wand swap came 0.5 s after a native attack, and from then on every native +// attack was queued by the client behind its attack-in-progress flag, which no AttackDone would +// ever clear (the client "attacked" in Peace, sending nothing). 37 minutes of no swings; +// turning Use Native Attack off fought at once. Now: +// * a stance change mid-fight: the first swing back is the regular attack (its AttackDone +// resets the client), native from the next one; +// * native attacks with no hit, miss or kill for 10 s: the regular attack for that fight, +// native again from the next target, logged once each way; the setting is never changed; +// * Use Native Attack off: nothing of this. +internal static class NativeAttackTests +{ + private const uint Player = 0x50000180; + private const uint Lb = 0x11BA0000; + private const uint Mob = 0x802307B1, Mob2 = 0x802307B2; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("native attack: a buff-wand swap mid-fight and back: the first swing back is the regular attack, then native again", SwapMidFightResets); + r.Add("native attack: a stance change long after the last swing (between fights): native straight away", SwapBetweenFightsStaysNative); + r.Add("native attack: 10 s of native attacks with no hit, miss or kill: the regular attack for this fight, native again next fight", StallFallsBackThenNativeNextFight); + r.Add("native attack: hits keep it native (the quiet clock starts over on every hit, miss or kill)", EvidenceKeepsNative); + r.Add("native attack off: regular attacks only, a swap changes nothing, nothing logged", NonNativeUnchanged); + } + + // ── A melee rig with native attack, ticked the way OnTick ticks it ──────── + + private sealed class Rig + { + public readonly LegacyUiSettings S; + public readonly CombatManager C; + + public Rig(bool native = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.AttackSendCalls = true; + FakeHost.NativeAttackCalls = true; + FakeHost.CancelAttackCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Place(Player, "Me", 96, 96, creature: false); + Place(Mob, "Drumtaken Kithless Siraluun", 96, 98.2f); + Place(Mob2, "Drumtaken Rabid Carenzi", 96, 99.8f); + FakeHost.PlayerPose = (Lb | 0x36, 96f, 96f, 0f); + FakeHost.HeadingDeg = 0; + S = new LegacyUiSettings + { + MonsterRange = 50, IsMacroRunning = true, EnableCombat = true, + UseNativeAttack = native, + MonsterRules = new List { new() { Name = "Default" } }, + }; + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Mob2 }); + C = new CombatManager(host, S, cache); + C.SetPlayerId(Player); + C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore()); + C.ScanNearbyTargets(); + } + + /// A combat tick (Combat has the arbiter's tick). The attack cadence runs on the + /// real clock, so it is reset. + public void Tick() + { + S.BotAction = "Combat"; + LastAttackCmd.SetValue(C, DateTime.MinValue); + C.OnHeartbeat(); + } + + /// A tick while buffing has it (the wand swap): combat only watches. + public void BuffTick(int mode) + { + FakeHost.CombatModeValue = mode; + S.BotAction = "Buffing"; + C.OnHeartbeat(); + } + + /// The wand swap BuffManager makes: Peace, Magic (casts), Peace, back to Melee. + public void WandSwapAndBack() + { + BuffTick(CombatMode.NonCombat); + BuffTick(CombatMode.Magic); + BuffTick(CombatMode.Magic); + BuffTick(CombatMode.NonCombat); + FakeHost.CombatModeValue = CombatMode.Melee; + } + + /// Ticks until an attack reaches the server; its kind ("native" / "melee"), or null. + public string? NextAttack() + { + int before = FakeHost.AttackCalls.Count; + for (int i = 0; i < 40 && FakeHost.AttackCalls.Count == before; i++) Tick(); + return FakeHost.AttackCalls.Count > before ? FakeHost.AttackCalls[^1].Kind : null; + } + + /// Moves one of the combat manager's private clocks back by . + public void Age(string field, double ms) + { + FieldInfo f = typeof(CombatManager).GetField(field, Any)!; + var t = (DateTime)f.GetValue(C)!; + f.SetValue(C, t.AddMilliseconds(-ms)); + } + + private static readonly FieldInfo LastAttackCmd = typeof(CombatManager).GetField("lastAttackCmd", Any)!; + } + + private static void Place(uint id, string name, float x, float y, bool creature = true) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x36, x, y, 0f); + if (creature) FakeHost.ItemTypes[id] = 0x10; + } + + private static int Logged(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal)); + + // ── 1. The swap mid-fight ───────────────────────────────────────────────── + + private static void SwapMidFightResets() + { + var rig = new Rig(); + Check.Eq(rig.NextAttack(), "native", "the fight starts native"); + Check.Eq(FakeHost.AttackCalls[^1].Target, Mob, "at the locked mob (selected for the client's pipeline)"); + Check.Eq(rig.NextAttack(), "native", "and stays native"); + + rig.WandSwapAndBack(); // 0.5 s after a native attack, as at 01:28:51 + Check.True(rig.C.NativeResetPending, "the stance left Melee right after a native attack: a reset is due"); + + Check.Eq(rig.NextAttack(), "melee", "the first swing back is the regular attack"); + Check.Eq(FakeHost.AttackCalls[^1].Target, Mob, "at the same mob"); + Check.Eq(Logged("goes out as the regular attack"), 1, "logged once"); + Check.False(rig.C.NativeResetPending, "one swing only"); + Check.Eq(rig.NextAttack(), "native", "then native again"); + Check.Eq(rig.NextAttack(), "native", "and stays native"); + Check.True(rig.S.UseNativeAttack, "the setting is untouched"); + Check.False(rig.C.NativeFallbackActive, "no fallback"); + } + + // ── 2. A stance change between fights ───────────────────────────────────── + + private static void SwapBetweenFightsStaysNative() + { + var rig = new Rig(); + Check.Eq(rig.NextAttack(), "native", "native"); + rig.Age("_lastNativeAttackAt", CombatManager.NativeResetWindowMs + 1000); // the last swing 6 s ago + rig.WandSwapAndBack(); + Check.False(rig.C.NativeResetPending, "no attack was in flight when the stance left: no reset"); + Check.Eq(rig.NextAttack(), "native", "native straight away"); + Check.Eq(Logged("[Combat] native attack"), 0, "nothing logged"); + } + + // ── 3. The safety net ───────────────────────────────────────────────────── + + private static void StallFallsBackThenNativeNextFight() + { + var rig = new Rig(); + for (int i = 0; i < CombatManager.NativeFallbackAttacks; i++) + Check.Eq(rig.NextAttack(), "native", $"native attack {i + 1}, no hit, miss or kill"); + Check.Eq((uint)rig.C.activeTargetId, Mob, "rig: the first mob is the target"); + + rig.Age("_nativeQuietSince", CombatManager.NativeFallbackMs + 500); // 10.5 s of them + rig.Age("_lastNativeAttackAt", 900); // the last one a cycle ago (no gap) + Check.Eq(rig.NextAttack(), "melee", "10 s with nothing: the regular attack"); + Check.True(rig.C.NativeFallbackActive, "for this fight"); + Check.Eq(Logged("native attack isn't landing"), 1, "logged"); + Check.True(FakeHost.Logs.Any(l => l.Contains("using the regular attack until the next fight")), "with what happens"); + Check.Eq(rig.NextAttack(), "melee", "the next swing at the same mob: regular"); + Check.Eq(rig.NextAttack(), "melee", "and the next"); + Check.Eq(Logged("native attack isn't landing"), 1, "logged once, not per swing"); + Check.True(rig.S.UseNativeAttack, "the setting is untouched"); + + // The fight ends (the mob gone), the next one starts: native again. + rig.C.MarkGhost(unchecked((int)Mob), "Drumtaken Kithless Siraluun", 900_000, "test: the fight is over"); + Thread.Sleep(80); // the scan runs at most every 50 ms + rig.C.ScanNearbyTargets(); + Check.Eq(rig.NextAttack(), "native", "the next fight: native again"); + Check.Eq((uint)rig.C.activeTargetId, Mob2, "at the next mob"); + Check.False(rig.C.NativeFallbackActive, "the fallback is over"); + Check.Eq(Logged("native attack again: a new fight"), 1, "logged"); + Check.Eq(rig.NextAttack(), "native", "and stays native (the quiet clock started over)"); + } + + private static void EvidenceKeepsNative() + { + var rig = new Rig(); + for (int i = 0; i < CombatManager.NativeFallbackAttacks + 2; i++) + Check.Eq(rig.NextAttack(), "native", $"native attack {i + 1}"); + rig.Age("_nativeQuietSince", CombatManager.NativeFallbackMs + 500); + rig.C.OnCombatDamage(120, 1, false, isAttacker: true); // a hit lands + Check.Eq(rig.NextAttack(), "native", "a hit since: still native"); + Check.False(rig.C.NativeFallbackActive, "no fallback"); + + // A long pause between native attacks (a loot run) starts the clock over too. + for (int i = 0; i < CombatManager.NativeFallbackAttacks; i++) rig.NextAttack(); + rig.Age("_nativeQuietSince", CombatManager.NativeFallbackMs + 500); + rig.Age("_lastNativeAttackAt", CombatManager.NativeQuietGapMs + 500); + Check.Eq(rig.NextAttack(), "native", "the last native attack 5.5 s ago: a new quiet clock, native"); + Check.Eq(Logged("native attack isn't landing"), 0, "never fell back"); + } + + // ── 4. Native attack off ────────────────────────────────────────────────── + + private static void NonNativeUnchanged() + { + var rig = new Rig(native: false); + Check.Eq(rig.NextAttack(), "melee", "regular"); + rig.WandSwapAndBack(); + Check.False(rig.C.NativeResetPending, "no reset pending"); + for (int i = 0; i < 6; i++) + Check.Eq(rig.NextAttack(), "melee", $"regular attack {i + 1}"); + Check.False(rig.C.NativeFallbackActive, "no fallback"); + Check.Eq(Logged("[Combat] native attack"), 0, "nothing logged"); + Check.False(FakeHost.AttackCalls.Any(a => a.Kind == "native"), "never a native attack"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavHeadingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavHeadingTests.cs new file mode 100644 index 0000000..42863ce --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavHeadingTests.cs @@ -0,0 +1,34 @@ +using System; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// /ra navheading walks round what's in the way (owner, 2026-11-06: "nav route is not navving around +// obstacles"): RynthNav's corners become a Once route, in nav coordinates, doorways kept. +internal static class NavHeadingTests +{ + public static void Register(Runner r) + { + r.Add("navheading: RynthNav's corners become a Once route in nav coordinates, doorways kept", CornersToRoute); + } + + private static double World(double navUnits) => (navUnits * 10.0 + 1019.5) * 24.0; + + private static void CornersToRoute() + { + var corners = new[] + { + new OutdoorHunt.Vec(World(56.0), World(42.4), 240.0), + new OutdoorHunt.Vec(World(56.1), World(42.5), 480.0, Door: true), + }; + var route = RynthAiPlugin.HeadingRoute(corners); + Check.True(route.RouteType == NavRouteType.Once, "a Once route"); + Check.True(route.Points.Count == 2, "one point per corner"); + Check.True(Math.Abs(route.Points[0].EW - 56.0) < 1e-9 && Math.Abs(route.Points[0].NS - 42.4) < 1e-9, "x is EW, y is NS"); + Check.True(Math.Abs(route.Points[1].Z - 2.0) < 1e-9, "z in 240-yard units"); + Check.True(!route.Points[0].Doorway && route.Points[1].Doorway, "doorway corners stay doorways"); + Check.True(route.Points[0].Type == NavPointType.Point, "plain points"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs index 347af23..6f07101 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs @@ -28,6 +28,219 @@ internal static class OutdoorHuntTests r.Add("hunt: a monster right beside it that combat doesn't take: stands, then leaves it out", RightHere); r.Add("hunt (test 10-23): in a building it walks back out the way it went in (the loops it made cut out)", WayBackOut); r.Add("hunt: in a building with no way in known, or the walks out ending still inside: it waits", IndoorsWaits); + r.Add("hunt pick (11-08): Nearest is the hunt as it was (the lone one 10 yd off, not the pack)", PickNearestUnchanged); + r.Add("hunt pick (11-08): Biggest pack goes to a 5-pack 80 yd off over a lone monster 10 yd off; logged", PickPackFar); + r.Add("hunt pick (11-08): a lone monster wins when the pack is very far", PickPackTooFar); + r.Add("hunt pick (11-08): Most XP prefers 2 high-XP monsters over 4 low-XP ones (Biggest pack the other way)", PickMostXp); + r.Add("hunt pick (11-08): Most XP with no XP learned falls back to the pack's size; an unknown name counts as the known average", PickXpUnknown); + r.Add("hunt pick (11-08): a higher Priority still comes first; paths only for the top few; the target is kept while walking", PickPriorityAndCost); + r.Add("hunt pick (11-08): /ra hunt pick answers with the choice, sets it, and says why not with the usage", PickCommand); + r.Add("hunt pick (11-08): OutdoorHuntPick round-trips (saved, copied, engine payload, clamped, an older engine leaves it)", PickSetting); + } + + // ── Pick (2026-11-08, Tom: "a setting to go for nearest spawn or most dense or highest experience") ── + + /// A pack of round (x, y), ids from , each within a few yd of the others. + private static List Pack(int firstId, int n, double x, double y, OutdoorHunt.Vec me, string? name = null, int priority = 1) + { + var list = new List(); + for (int i = 0; i < n; i++) + { + double a = i * 2 * Math.PI / Math.Max(1, n); + double px = x + (i == 0 ? 0 : 4 * Math.Cos(a)), py = y + (i == 0 ? 0 : 4 * Math.Sin(a)); + list.Add(C(firstId + i, px, py, me, priority, name)); + } + return list; + } + + private static List Sorted(IEnumerable c) => c.OrderBy(x => x.Distance).ToList(); + + private static void PickNearestUnchanged() + { + var me = V(1000, 1000); + var all = Sorted(Pack(10, 5, 1080, 1000, me).Append(C(1, 1010, 1000, me))); + var h = new OutdoorHunt(); + Check.Eq(h.Pick, OutdoorHunt.PickMode.Nearest, "Nearest by default"); + h.Start(T0, me); + var d = h.Tick(T0, me, true, all, new Nav().Path); + Check.Eq(d.TargetId, 1, "the lone one 10 yd away"); + Check.True(h.Note.StartsWith("next: 'Monster 1', a 10 yd walk"), "the same log line as before: " + h.Note); + } + + private static void PickPackFar() + { + var me = V(1000, 1000); + var all = Sorted(Pack(10, 5, 1080, 1000, me).Append(C(1, 1010, 1000, me))); + var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack }; + h.Start(T0, me); + var d = h.Tick(T0, me, true, all, new Nav().Path); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId >= 10 && d.TargetId < 15, $"to the pack, not the lone one ({d.Act} {d.TargetId})"); + var nearestOfPack = all.Where(c => c.Id >= 10).OrderBy(c => c.Distance).First(); + Check.Eq(d.TargetId, nearestOfPack.Id, "the pack's member with the shortest walk"); + Check.True(h.Note.Contains("pack of 5") && h.Note.Contains("yd walk"), "logged with the pack: " + h.Note); + } + + private static void PickPackTooFar() + { + var me = V(1000, 1000); + // 3 at 180 yd: 3 / (1 + 180/60) = 0.75; one at 10 yd: 1 / (1 + 10/60) = 0.86. + var all = Sorted(Pack(10, 3, 1180, 1000, me).Append(C(1, 1010, 1000, me))); + var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack }; + h.Start(T0, me); + var d = h.Tick(T0, me, true, all, new Nav().Path); + Check.Eq(d.TargetId, 1, "the lone one near beats a small pack far away"); + Check.True(h.Note.Contains("on its own"), "logged: " + h.Note); + // The same pack 80 yd off: 3 / 2.33 = 1.29 wins. + var near = Sorted(Pack(10, 3, 1080, 1000, me).Append(C(1, 1010, 1000, me))); + var h2 = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack }; + h2.Start(T0, me); + Check.True(h2.Tick(T0, me, true, near, new Nav().Path).TargetId >= 10, "and at 80 yd the pack wins"); + } + + private static Func Xp(params (string Name, double Xp)[] known) + { + var map = known.ToDictionary(k => k.Name, k => k.Xp); + return n => map.TryGetValue(n, out double v) ? v : null; + } + + private static void PickMostXp() + { + var me = V(1000, 1000); + var all = Sorted(Pack(10, 2, 1050, 1000, me, "Olthoi Slayer").Concat(Pack(20, 4, 1000, 1030, me, "Drudge Skulker"))); + var lookup = Xp(("Olthoi Slayer", 1000), ("Drudge Skulker", 100)); + var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Xp, XpLookup = lookup }; + h.Start(T0, me); + var d = h.Tick(T0, me, true, all, new Nav().Path); + Check.True(d.TargetId is 10 or 11, $"the 2 high-XP ones 50 yd off ({d.TargetId})"); + Check.True(h.Note.Contains("pack of 2") && h.Note.Contains("(2,000 XP)"), "logged with the pack's XP: " + h.Note); + var p = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack, XpLookup = lookup }; + p.Start(T0, me); + Check.True(p.Tick(T0, me, true, all, new Nav().Path).TargetId >= 20, "Biggest pack takes the 4 nearer ones"); + } + + private static void PickXpUnknown() + { + var me = V(1000, 1000); + var all = Sorted(Pack(10, 2, 1050, 1000, me, "Olthoi Slayer").Concat(Pack(20, 4, 1000, 1030, me, "Drudge Skulker"))); + var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Xp, XpLookup = _ => null }; + h.Start(T0, me); + Check.True(h.Tick(T0, me, true, all, new Nav().Path).TargetId >= 20, "nothing learned: by size, the 4"); + Check.True(h.Note.Contains("no XP learned yet"), "and says so: " + h.Note); + var none = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Xp }; // no lookup at all + none.Start(T0, me); + Check.True(none.Tick(T0, me, true, all, new Nav().Path).TargetId >= 20, "no lookup: by size too"); + // Only the Slayers known (1000): the Drudges count as that average, so 4 of them win. + var half = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Xp, XpLookup = Xp(("Olthoi Slayer", 1000)) }; + half.Start(T0, me); + Check.True(half.Tick(T0, me, true, all, new Nav().Path).TargetId >= 20, "an unknown name counts as the known average"); + } + + private static void PickPriorityAndCost() + { + var me = V(1000, 1000); + var all = Sorted(Pack(10, 5, 1020, 1000, me).Append(C(1, 1000, 1050, me, priority: 5))); + var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack }; + h.Start(T0, me); + var nav = new Nav(); + var d = h.Tick(T0, me, true, all, nav.Path); + Check.Eq(d.TargetId, 1, "Priority 5 on its own before a Priority 1 pack of 5"); + + // Twenty monsters about: paths for PickCandidates only. + var many = new List(); + for (int i = 0; i < 20; i++) many.Add(C(100 + i, 1000 + 5 * i, 1100, me)); + var cost = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack }; + cost.Start(T0, me); + var counted = new Nav(); + d = cost.Tick(T0, me, true, Sorted(many), counted.Path); + Check.Eq(counted.Calls, cost.PickCandidates, "a path for each of the top few only"); + int target = d.TargetId; + Check.True(target != 0, "one chosen"); + // Walking to it: kept, even with a bigger pack turning up. + var more = Sorted(many.Concat(Pack(200, 8, 1000, 1010, me))); + d = cost.Tick(T0.AddSeconds(2), me, false, more, counted.Path); + Check.True(d.Act == OutdoorHunt.Act.None && cost.TargetId == target, $"the target is kept while walking ({d.Act} {cost.TargetId})"); + } + + private static (RynthAiPlugin P, LegacyDashboardRenderer Dash, Action Ra, Func All) HuntRig() + { + const System.Reflection.BindingFlags Any = System.Reflection.BindingFlags.Instance + | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public; + RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset(); + var host = RynthCore.RynthAiHostTests.Fakes.FakeHost.Create(); + var p = new RynthAiPlugin(); + typeof(RynthCore.PluginCore.RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { RynthCore.RynthAiHostTests.Fakes.FakeHost.LastApi }); + var dash = new LegacyDashboardRenderer(host); + typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash); + var chat = RynthCore.RynthAiHostTests.Fakes.FakeHost.Chat; + void Ra(string line) + { + chat.Clear(); + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, new object[] { parts[1].ToLowerInvariant(), parts, 0 }); + } + return (p, dash, Ra, () => string.Join(" | ", chat)); + } + + private static void PickCommand() + { + var (_, dash, Ra, All) = HuntRig(); + Ra("/ra hunt pick"); + Check.True(All().Contains("Outdoor hunt pick: Nearest") && All().Contains(RynthAiPlugin.HuntPickUsage), "no word: the choice now and the usage: " + All()); + Ra("/ra hunt pick pack"); + Check.Eq(dash.Settings.OutdoorHuntPick, 1, "pack = 1"); + Check.True(All().Contains("set: Biggest pack"), "and says so: " + All()); + Ra("/ra hunt pick xp"); + Check.Eq(dash.Settings.OutdoorHuntPick, 2, "xp = 2"); + Check.True(All().Contains("set: Most XP"), "and says so: " + All()); + Ra("/ra hunt pick most dense"); + Check.Eq(dash.Settings.OutdoorHuntPick, 1, "Tom's words work too"); + Ra("/ra hunt pick fastest"); + Check.Eq(dash.Settings.OutdoorHuntPick, 1, "an unknown word changes nothing"); + Check.True(All().Contains("isn't one of nearest, pack or xp") && All().Contains("Biggest pack now") && All().Contains("Usage: /ra hunt pick"), + "why, what it is, the usage: " + All()); + Ra("/ra hunt pick nearest"); + Check.Eq(dash.Settings.OutdoorHuntPick, 0, "back to nearest"); + Ra("/ra hunt status"); + Check.True(All().Contains("Pick: Nearest"), "status says the pick: " + All()); + Ra("/ra hunt nonsense"); + Check.True(All().Contains(RynthAiPlugin.HuntPickUsage), "the usage lists it: " + All()); + } + + private static void PickSetting() + { + Check.Eq(new LegacyUiSettings().OutdoorHuntPick, 0, "Nearest by default"); + var ctx = RynthAiJsonContext.Default.LegacyUiSettings; + var saved = System.Text.Json.JsonSerializer.Deserialize( + System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { OutdoorHuntPick = 2 }, ctx), ctx)!; + Check.Eq(saved.OutdoorHuntPick, 2, "saved"); + var live = new LegacyUiSettings(); + typeof(LegacyDashboardRenderer).GetMethod("CopySettings", + System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)! + .Invoke(null, new object[] { saved, live }); + Check.Eq(live.OutdoorHuntPick, 2, "copied"); + var old = System.Text.Json.JsonSerializer.Deserialize("{\"OutdoorHuntRange\":70}", ctx)!; + Check.Eq(old.OutdoorHuntPick, 0, "a profile from before the setting: Nearest"); + + // The engine's face (SettingsBridgePayload): sent as "OutdoorHuntPick", applied, clamped. + var s = new LegacyUiSettings { OutdoorHuntPick = 1 }; + var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + const System.Reflection.BindingFlags F = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", F)!.SetValue(dash, true); + typeof(LegacyDashboardRenderer).GetField("_settings", F)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", F)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); + string json = dash.BuildSettingsJson(); + using (var doc = System.Text.Json.JsonDocument.Parse(json)) + Check.True(doc.RootElement.TryGetProperty("OutdoorHuntPick", out var pe) && pe.GetInt32() == 1, "sent to the engine as \"OutdoorHuntPick\""); + var sent = System.Text.Json.JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.SettingsBridgePayload)!; + Check.Eq(sent.OutdoorHuntPick, 1, "in the payload"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.Eq(s.OutdoorHuntPick, 1, "an engine without it leaves it alone"); + dash.ApplySettingsJson("{\"OutdoorHuntPick\":2}"); + Check.Eq(s.OutdoorHuntPick, 2, "applied: Most XP"); + dash.ApplySettingsJson("{\"OutdoorHuntPick\":9}"); + Check.Eq(s.OutdoorHuntPick, 2, "9 clamped to 2"); + dash.ApplySettingsJson("{\"OutdoorHuntPick\":-3}"); + Check.Eq(s.OutdoorHuntPick, 0, "-3 clamped to 0"); } private static void WallBetween() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PetSummonStopsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PetSummonStopsTests.cs new file mode 100644 index 0000000..7b4db2a --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PetSummonStopsTests.cs @@ -0,0 +1,333 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Summons stopped for the rest of the session (report 2026-11-06, release 2026.11.3.2: "after a +// time my character will stop summoning, he keeps fighting and looting", fixed only by restarting +// the game). Two ways PetManager waited forever, with no log line: +// * the client's gesture gate (CanCastNow) stuck closed: buffs and combat go on through +// CastGateWatchdog's override, the summon read the raw gate and never went; +// * a pet the client still shows (a ghost the server no longer has, or one whose delete the +// cache missed) read as "a pet is out" forever. +// Follow-up from the same player: "it thinks it's already summoned if you die", and it stopped +// while "rescanning inventory". A pet out at a death or a portal is left behind (the server drops +// it without telling a player who left), a read of 0 during a rescan refilled or parked a full +// essence, and an essence that vanished from the client was used instead of its successor. +internal static unsafe class PetSummonStopsTests +{ + private const uint Player = 0x50000D11; + private const uint Mob = 0x80310010; + private const uint Essence = 0x80310001; + private const uint Pet = 0x80310020; + private const uint Spirit = 0x80310002; + private const uint Essence2 = 0x80310004; // a same-named essence that replaces a vanished one + private const uint StructureKey = 92; // AcIntProperty.Structure + private const uint Lb = 0xA9B40000; + + private const string PetName = "Pet Tester's Fire Moar"; + + /// GetObjectServerAge answers (ms since the server's last message), -1 = no record. + private static readonly Dictionary ServerAges = new(); + + public static void Register(Runner r) + { + r.Add("pets: a gesture gate stuck closed holds the summon only 4 s, logged; a short gesture just waits", StuckGestureGate); + r.Add("pets: a pet the server has been silent about for 60 s is a ghost: a new pet is summoned", GhostPetIgnored); + r.Add("pets: a pet the client no longer has (missed delete) does not hold summons", MissedDeleteIgnored); + r.Add("pets: 'is already active' after a ghost summon trusts the quiet pet for 5 min", AlreadyActiveTrustsPet); + r.Add("pets: a death leaves the pet out behind: the next fight summons at once (before: never again)", DeathLeavesPetBehind); + r.Add("pets: a death mid-summon clears the summon state; the server's essence cooldown still holds", DeathMidSummon); + r.Add("pets: a portal leaves the pet out behind; 'is already active' brings it back", PortalLeavesPetBehind); + r.Add("pets: no server record for a pet for 60 s of watching (engine reload) is silence too", NoRecordIsSilence); + r.Add("pets: a read of 0 right after 50 (a rescan) summons; it does not refill or park the essence", RescanZeroRead); + r.Add("pets: empty read, no spirit, never confirmed by the server: tried once, parked only after 'not enough charges'", UnconfirmedEmptyTried); + r.Add("pets: an essence the client no longer has is not used; its same-named successor is", VanishedEssenceReplaced); + } + + // ── Rig ─────────────────────────────────────────────────────────────── + + private sealed class Rig : IDisposable + { + public long Now = 1_000_000; + public readonly LegacyUiSettings S = new() { SummonPets = true, MonsterRange = 20, CustomPetRange = 5, PetAutoRefill = true }; + public readonly PetManager Pets; + public readonly WorldObjectCache Cache; + + public Rig(bool gates = false, bool serverAge = false, bool pet = false, bool spirit = false, bool replacement = false, int charges = 50) + { + FakeHost.Reset(); + ServerAges.Clear(); + FakeHost.WeaponCalls = true; // UseObject (summon) + FakeHost.UseOnCalls = true; + FakeHost.ServerGates = gates; // GetCastBusyState (FakeHost.CastBusy) + if (serverAge) FakeHost.ConfigureApi = ServerAgeApi; + Place(Player, "Pet Tester", 96, 96, creature: false); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + Place(Mob, "Drudge Skulker", 96, 99, creature: true); // 3 m north + FakeHost.Names[Essence] = "Fire Moar Essence (50)"; + FakeHost.Containers[Essence] = Player; + FakeHost.Ints[(Essence, StructureKey)] = charges; + var known = new List { Mob, Essence }; + if (spirit) + { + FakeHost.Names[Spirit] = "Encapsulated Spirit"; + FakeHost.Containers[Spirit] = Player; + known.Add(Spirit); + } + if (replacement) + { + FakeHost.Names[Essence2] = "Fire Moar Essence (50)"; + FakeHost.Containers[Essence2] = Player; + FakeHost.Ints[(Essence2, StructureKey)] = 50; + known.Add(Essence2); + } + + var host = FakeHost.Create(Player); + Cache = FakeHost.MakeCache(host, Player, known); + S.IsMacroRunning = true; + S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence), Name = "Fire Moar Essence (50)", Type = "Pet" }); + var combat = new CombatManager(host, S, Cache); + combat.SetPlayerId(Player); + combat.ScanNearbyTargets(); + Check.True(combat.ScannedTargets.Count == 1, "rig: the monster is scanned"); + if (pet) + { + Place(Pet, PetName, 96, 97, creature: true); + _ = Cache[unchecked((int)Pet)]; // filed on the landscape as a creature + Check.True(Cache.GetLandscape().Any(w => w.Id == unchecked((int)Pet)), "rig: the pet is in the landscape cache"); + } + PetManager.Clock = () => Now; + Pets = new PetManager(host, S, Cache, combat, null); + } + + private static void Place(uint id, string name, float x, float y, bool creature) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f); + if (creature) FakeHost.ItemTypes[id] = 0x10; + } + + /// Runs the heartbeat for of fake time in 100 ms steps. + public void Run(long ms) + { + for (long t = 0; t < ms; t += 100) + { + Now += 100; + Pets.OnHeartbeat(0); + } + } + + public int Summons => FakeHost.Uses.Count(u => u == Essence); + public int Refills => FakeHost.UsesOn.Count(u => u.Source == Spirit); + + public static void SetCharges(int charges) => FakeHost.Ints[(Essence, StructureKey)] = charges; + + public void Dispose() + { + PetManager.Clock = static () => Environment.TickCount64; + FakeHost.ConfigureApi = null; + ServerAges.Clear(); + } + } + + private static void ServerAgeApi(ref RynthCoreApiNative api) + { + api.Version = Math.Max(api.Version, 83u); + api.GetObjectServerAgeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectServerAge; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetObjectServerAge(uint id) => ServerAges.TryGetValue(id, out int age) ? age : -1; + + private static bool Logged(string text) => FakeHost.Logs.Any(l => l.Contains(text, StringComparison.OrdinalIgnoreCase)); + + // ── Tests ───────────────────────────────────────────────────────────── + + private static void StuckGestureGate() + { + using (var rig = new Rig(gates: true)) + { + FakeHost.CastBusy = 1; // the gate never opens again + rig.Run(3_000); + Check.Eq(rig.Summons, 0, "inside 4 s the closed gate holds the summon (a gesture may be animating)"); + rig.Run(3_000); + Check.Eq(rig.Summons, 1, "closed past 4 s: taken as stuck, the summon goes (before: never again)"); + Check.True(Logged("taken as stuck"), "the stuck gate is logged"); + FakeHost.CastBusy = 0; + rig.Run(200); + Check.True(Logged("reads clear again"), "the gate opening again is logged"); + } + + using (var rig = new Rig(gates: true)) + { + FakeHost.CastBusy = 1; // a buff gesture + rig.Run(2_000); + Check.Eq(rig.Summons, 0, "a gesture animating: no summon"); + FakeHost.CastBusy = 0; + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "the gesture ended: the summon goes"); + Check.False(Logged("taken as stuck"), "a short gesture is not called stuck"); + } + + using (var rig = new Rig(gates: true)) + { + // Gestures back to back with the gate open in between, never 4 s closed in one go. + for (int i = 0; i < 6; i++) + { + FakeHost.CastBusy = 1; + rig.Run(900); + FakeHost.CastBusy = 0; + rig.Run(100); + FakeHost.CastBusy = 1; + } + Check.False(Logged("taken as stuck"), "a gate that opens between gestures is never called stuck"); + } + } + + private static void GhostPetIgnored() + { + using (var rig = new Rig(pet: true)) + { + rig.Run(5_000); + Check.Eq(rig.Summons, 0, "no server-age record (older engine): the pet counts as out, as before"); + } + + using (var rig = new Rig(serverAge: true, pet: true)) + { + ServerAges[Pet] = 2_000; + rig.Run(5_000); + Check.Eq(rig.Summons, 0, "the server talked about the pet 2 s ago: it is out, no second summon"); + ServerAges[Pet] = -1; + rig.Run(5_000); + Check.Eq(rig.Summons, 0, "no record for the pet says nothing: it is out"); + ServerAges[Pet] = 90_000; + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "silent for 90 s: a ghost, a new pet is summoned (before: never again)"); + Check.True(Logged("does not count as out") && Logged("0x80310020"), "the ghost is logged with its id"); + int lines = FakeHost.Logs.Count(l => l.Contains("does not count as out")); + rig.Run(10_000); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("does not count as out")), lines, "the ghost is logged once"); + } + } + + private static void MissedDeleteIgnored() + { + using var rig = new Rig(pet: true); + rig.Run(3_000); + Check.Eq(rig.Summons, 0, "the pet is out: no summon"); + FakeHost.Names.Remove(Pet); // the client deleted it; the cache never heard + FakeHost.Positions.Remove(Pet); + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "a pet the client no longer has does not hold summons"); + Check.True(Logged("client no longer has it"), "the missed delete is logged"); + } + + private static void AlreadyActiveTrustsPet() + { + using var rig = new Rig(serverAge: true, pet: true); + ServerAges[Pet] = 90_000; // quiet, so taken as a ghost + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "the quiet pet is taken as a ghost: one summon"); + rig.Pets.OnChatWindowText("Pet Tester's Fire Moar is already active."); + Check.True(Logged("already active"), "the server's answer is logged"); + rig.Run(4 * 60_000); + Check.Eq(rig.Summons, 1, "the server has the pet: no Use every 45 s on top of it for 5 min"); + rig.Run(90_000); + Check.Eq(rig.Summons, 2, "after 5 min the quiet pet is checked again"); + } + + private static void DeathLeavesPetBehind() + { + using var rig = new Rig(pet: true); // no server-age API: only the death says the pet is gone + rig.Run(3_000); + Check.Eq(rig.Summons, 0, "the pet is out: no summon"); + rig.Pets.OnPlayerDeath(); + Check.True(Logged("died: 1 pet(s) out are left behind"), "the death is logged with the pet left behind"); + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "after the death the first fight summons at once"); + Check.True(Logged("left behind)") && Logged("0x80310020"), "the left-behind pet is logged with its id"); + } + + private static void DeathMidSummon() + { + using var rig = new Rig(); + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "first summon"); + rig.Pets.OnPlayerDeath(); // in flight: no pet, no charge drop yet + Check.True(Logged("the summon state was cleared"), "the in-flight summon is dropped and logged"); + rig.Run(30_000); + Check.Eq(rig.Summons, 1, "the server's 45 s essence cooldown still holds after the death"); + rig.Run(16_000); + Check.Eq(rig.Summons, 2, "after the cooldown it summons again"); + } + + private static void PortalLeavesPetBehind() + { + using var rig = new Rig(pet: true); + rig.Run(2_000); + Check.Eq(rig.Summons, 0, "the pet is out: no summon"); + rig.Pets.OnPortal(); + Check.True(Logged("portal space: 1 pet(s) out are left behind"), "the portal is logged"); + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "after the portal the first fight summons"); + rig.Pets.OnChatWindowText("Pet Tester's Fire Moar is already active."); + rig.Run(4 * 60_000); + Check.Eq(rig.Summons, 1, "the server still has that pet: it counts as out again, no more Uses"); + } + + private static void NoRecordIsSilence() + { + using var rig = new Rig(serverAge: true, pet: true); + ServerAges[Pet] = -1; // an engine reload: no record for anything + rig.Run(50_000); + Check.Eq(rig.Summons, 0, "no record for 50 s: still taken as out"); + rig.Run(12_000); + Check.Eq(rig.Summons, 1, "no record for 60 s of watching: silence, a new pet is summoned"); + Check.True(Logged("s of watching"), "logged as silence"); + } + + private static void RescanZeroRead() + { + using var rig = new Rig(spirit: true); + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "50 charges: summon"); + Rig.SetCharges(0); // an inventory rescan: the property reads 0 for now + rig.Run(46_000); + Check.Eq(rig.Refills, 0, "no spirit spent on a read of 0 right after 50 (before: a refill)"); + Check.Eq(rig.Summons, 2, "it summons from the essence after the cooldown"); + Check.True(Logged("taken as a read in progress"), "the implausible read is logged"); + } + + private static void UnconfirmedEmptyTried() + { + using var rig = new Rig(charges: 0); // no spirit, the read says empty from the start + rig.Run(1_500); + Check.Eq(rig.Summons, 1, "the server never called it empty: one summon is tried (before: parked every 15 s, never tried)"); + Check.True(Logged("the server hasn't called it empty"), "the try is logged"); + rig.Pets.OnChatWindowText("Your summoning device does not have enough charges to function!"); + rig.Run(120_000); + Check.Eq(rig.Summons, 1, "confirmed empty: parked, no Use every 15 s"); + Rig.SetCharges(50); // refilled by hand + rig.Run(2_000); + Check.Eq(rig.Summons, 2, "charges again: it summons"); + } + + private static void VanishedEssenceReplaced() + { + using var rig = new Rig(replacement: true); + FakeHost.Names.Remove(Essence); // dropped on a corpse the client let go; the cache still has it + FakeHost.Containers.Remove(Essence); // (container reads 0, which read as "in the pack") + rig.Run(1_500); + Check.Eq(rig.Summons, 0, "the vanished essence is not used"); + Check.Eq(FakeHost.Uses.Count(u => u == Essence2), 1, "its same-named successor in the pack is"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/RingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/RingTests.cs new file mode 100644 index 0000000..0b5627f --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/RingTests.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// "It doesn't like to use rings even when set" (2026-11-06). A rule with Ring on casts a ring only +// when Min Ring Targets monsters are within Ring Range of the character and a ring of the cast's +// element is known; otherwise the rule's other shape. Nothing said which of those held a ring +// back, so a player saw bolts and no reason. Now the log says it (the count against the setting, +// Ring Range 0, or the ring that isn't known and why), for the cast itself only and never every +// attack. And a War caster whose rule says Nether (its bolts are Fire's) casts Fire's rings: they +// used to be looked up under Nether, which War has none of. +internal static class RingTests +{ + private const uint Player = 0x50000D01; + private const uint Lb = 0x5B480000; + private const int Target = unchecked((int)0x80000301); + + public static void Register(Runner r) + { + r.Add("rings: the count is the live monsters within Ring Range of the character (dead and unattackable left out)", LiveCount); + r.Add("rings: too few near is logged with the count and the setting, at most every 30 s per rule", NotDueLogged); + r.Add("rings: Ring Range 0 turns rings off and says so once", RingRangeZero); + r.Add("rings: a ring that isn't known says why (tier, rings tried), for the cast only, not element probes", NoRingKnownReason); + r.Add("rings: a War caster whose rule says Nether casts Fire's ring, as its bolts are Fire", WarCasterNetherRule); + } + + private static MonsterRule BoltRing(string name = "Default") => new() { Name = name, UseBolt = true, UseRing = true }; + + private static string NameOf(int id) => id == 0 ? "(none)" : SpellTable.ById(id)?.Name ?? $"#{id}"; + + private sealed class Rig + { + public readonly LegacyUiSettings S = new(); + public readonly CombatManager C; + public DateTime Now = new(2026, 11, 6, 12, 0, 0); + private uint _next = 0x80000301; + + /// A caster at combat tier knowing exactly , + /// with monsters at (north, east, up, health) metres from it; health null = never sent. + public Rig(int tier, string[] known, (double N, double E, double Up, float? Health, bool Attackable)[]? mobs = null, + (int Buffed, int Training)? war = null, (int Buffed, int Training)? voidMagic = null) + { + FakeHost.Reset(); + foreach (string n in known) + { + var rows = SpellTable.Named(n).ToList(); + Check.True(rows.Count > 0, $"test setup: '{n}' is in the spell data"); + foreach (var row in rows) FakeHost.Spellbook.Add((uint)row.Id); + } + int T(int k) => k <= tier ? 0 : 10000; // the tier reads the no-skills stub (250 buffed) + S.MinSkillLevelTier1 = 0; S.MinSkillLevelTier2 = T(2); S.MinSkillLevelTier3 = T(3); S.MinSkillLevelTier4 = T(4); + S.MinSkillLevelTier5 = T(5); S.MinSkillLevelTier6 = T(6); S.MinSkillLevelTier7 = T(7); S.MinSkillLevelTier8 = T(8); + S.RingRange = 5; S.MinRingTargets = 3; S.WallRange = 0; S.BlastRange = 0; + + FakeHost.Names[Player] = "Me"; + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + if (war is { } w) FakeHost.Skills[(Player, 34)] = w; + if (voidMagic is { } v) FakeHost.Skills[(Player, 43)] = v; + var ids = new List(); + var health = new Dictionary(); + foreach (var m in mobs ?? Array.Empty<(double, double, double, float?, bool)>()) + { + uint id = _next++; + FakeHost.Names[id] = "Drudge Skulker"; + FakeHost.Positions[id] = (Lb | 0x1C, (float)(96 + m.E), (float)(96 + m.N), (float)m.Up); + FakeHost.ItemTypes[id] = 0x10; // a creature + if (!m.Attackable) FakeHost.NotAttackable.Add(id); + if (m.Health is float h) health[id] = h; + ids.Add(id); + } + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, ids, health); + C = new CombatManager(host, S, cache); + C.SetPlayerId(Player); + if (war != null || voidMagic != null) + { + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + C.SetCharacterSkills(skills); + } + var sm = new SpellManager(host, S); + sm.InitializeNatively(); + sm.RefreshKnownSpells(); + C.SetSpellManager(sm); + C.TargetClock = () => Now; + } + + /// The cast itself (a target id, as AttackWithMagic passes it). + public (string Spell, string Shape) Cast(string element, MonsterRule rule) + { + int id = C.FindBestShapedSpell(element, rule, out _, out int shape, arcTargetId: Target); + return (NameOf(id), CombatManager.ShapeName(shape)); + } + + /// An element probe (no target), as Auto's weakness pick and the wand check ask. + public int Probe(string element, MonsterRule rule) => C.FindBestShapedSpell(element, rule, out _, out _); + } + + private static int Lines(string text) => FakeHost.Logs.Count(l => l.Contains(text)); + + // Three living, attackable monsters inside 5 m (one whose health was never sent, as ACE sends it + // only for the selected target; one partly above), and around them one at 6 m, a dead one and an + // unattackable one (an NPC) right next to the character: 3 count. + private static void LiveCount() + { + var mobs = new (double, double, double, float?, bool)[] + { + (2, 0, 0, 0.8f, true), + (0, 3, 0, null, true), + (3, 0, 4, 1f, true), // 3 north, 4 up: 5.0 m, on the edge (in) + (6, 0, 0, 1f, true), // out + (1, 0, 0, 0f, true), // dead + (0, 1, 0, 1f, false), // not attackable + }; + var known = new[] { "Frost Bolt VI", "Halo of Frost" }; + + var rig = new Rig(6, known, mobs); + rig.S.MinRingTargets = 3; + Check.Eq(rig.Cast("Cold", BoltRing()), ("Halo of Frost", "Ring"), "3 near, 3 needed: the ring"); + + rig = new Rig(6, known, mobs); + rig.S.MinRingTargets = 4; + Check.Eq(rig.Cast("Cold", BoltRing()), ("Frost Bolt VI", "Bolt"), "3 near, 4 needed: the bolt"); + Check.Eq(Lines("3 monsters within Ring Range 5 and Min Ring Targets is 4"), 1, "the log gives the count and the setting"); + + rig = new Rig(6, known, mobs); + rig.S.MinRingTargets = 3; rig.S.RingRange = 4; + Check.Eq(rig.Cast("Cold", BoltRing()).Shape, "Bolt", "Ring Range 4: the one at 5 m is out, 2 near"); + Check.Eq(Lines("2 monsters within Ring Range 4"), 1, "the count at Ring Range 4"); + } + + private static void NotDueLogged() + { + var rig = new Rig(6, new[] { "Frost Bolt VI", "Halo of Frost" }); + int near = 1; + rig.C.RingCountOverride = () => near; + rig.S.MinRingTargets = 3; + var rule = BoltRing("Drudge"); + + Check.Eq(rig.Cast("Cold", rule), ("Frost Bolt VI", "Bolt"), "1 near, 3 needed: the bolt"); + Check.Eq(Lines("rule 'Drudge' has Ring on: no ring yet, 1 monster within Ring Range 5 and Min Ring Targets is 3"), 1, "said, singular"); + for (int i = 0; i < 20; i++) { rig.Now = rig.Now.AddSeconds(1); rig.Cast("Cold", rule); } + Check.Eq(Lines("has Ring on: no ring yet"), 1, "not every attack: once in 20 s"); + rig.Now = rig.Now.AddSeconds(11); + near = 2; + rig.Cast("Cold", rule); + Check.Eq(Lines("has Ring on: no ring yet"), 2, "again after 30 s, with the new count"); + Check.Eq(Lines("2 monsters within Ring Range 5"), 1, "the new count"); + + near = 3; + Check.Eq(rig.Cast("Cold", rule), ("Halo of Frost", "Ring"), "3 near: the ring"); + Check.Eq(Lines("has Ring on: no ring yet"), 2, "a ring cast says nothing more (the cast line has shape=Ring)"); + + var other = BoltRing("Mosswart"); + near = 1; + rig.Cast("Cold", other); + Check.Eq(Lines("rule 'Mosswart' has Ring on: no ring yet"), 1, "per rule"); + + var noRing = new MonsterRule { Name = "Golem", UseBolt = true }; + rig.Cast("Cold", noRing); + Check.Eq(Lines("rule 'Golem'"), 0, "a rule without Ring says nothing about rings"); + + rig.Probe("Cold", BoltRing("Lugian")); + Check.Eq(Lines("rule 'Lugian'"), 0, "an element probe says nothing"); + } + + private static void RingRangeZero() + { + var rig = new Rig(6, new[] { "Frost Bolt VI", "Halo of Frost" }); + rig.C.RingCountOverride = () => 8; + rig.S.RingRange = 0; + Check.Eq(rig.Cast("Cold", BoltRing()), ("Frost Bolt VI", "Bolt"), "Ring Range 0: no ring, however many are near"); + rig.Now = rig.Now.AddMinutes(5); + rig.Cast("Cold", BoltRing()); + Check.Eq(Lines("has Ring on, but Ring Range is 0: rings are off"), 1, "said once"); + Check.Eq(rig.S.RingRange, 0, "the setting is left as it is"); + } + + private static void NoRingKnownReason() + { + // Tier 4: rings are level 5 and 7, so none is castable yet, known or not. + var low = new Rig(4, new[] { "Frost Bolt IV", "Halo of Frost" }); + low.C.RingCountOverride = () => 5; + Check.Eq(low.Cast("Cold", BoltRing()), ("Frost Bolt IV", "Bolt"), "tier 4: the bolt"); + Check.Eq(Lines("no Cold ring spell known (War Magic tier 4: rings are level 5 and 7)"), 1, "the log names the tier"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Ring spell not found for Cold (War Magic tier 4")), "and the chat"); + Check.Eq(Lines("has Ring on: no ring yet"), 0, "not a count problem: the count was met"); + + // Tier 6 knowing only the II (level 7): the rings tried, and that the II waits for tier 7. + var six = new Rig(6, new[] { "Frost Bolt VI", "Halo of Frost II" }); + six.C.RingCountOverride = () => 5; + Check.Eq(six.Cast("Cold", BoltRing()).Shape, "Bolt", "tier 6 with only the II: the bolt"); + Check.Eq(Lines("tried: Halo of Frost; Halo of Frost II is level 7"), 1, "the rings tried"); + + // Element probes (Auto's weakness pick asks every element) say nothing: the chat used to + // report "Ring spell not found for Slash" while the bot cast Cold. + var probe = new Rig(7, new[] { "Frost Bolt VI", "Halo of Frost II", "Whirling Blade VI" }); + probe.C.RingCountOverride = () => 5; + foreach (string e in new[] { "Slash", "Fire", "Acid", "Pierce", "Bludgeon", "Lightning" }) + probe.Probe(e, BoltRing()); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("Ring spell not found")), 0, "no chat from the probes"); + Check.Eq(Lines("ring spell known"), 0, "no log from the probes"); + Check.Eq(probe.Cast("Cold", BoltRing()), ("Halo of Frost II", "Ring"), "the cast's own element has its ring"); + Check.Eq(probe.Cast("Slash", BoltRing()).Shape, "Bolt", "a cast of Slash, no Slash ring: the bolt"); + Check.Eq(Lines("no Slash ring spell known (tried: Horizon's Blades II, Horizon's Blades)"), 1, "said for the cast"); + } + + private static void WarCasterNetherRule() + { + var known = new[] { "Flame Bolt VI", "Cassius' Ring of Fire II", "Nether Bolt VI", "Clouded Soul II" }; + var rig = new Rig(7, known, war: (400, 3), voidMagic: (10, 1)); + rig.C.RingCountOverride = () => 5; + Check.Eq(rig.Cast("Nether", BoltRing()), ("Cassius' Ring of Fire II", "Ring"), "War only, rule says Nether: Fire's ring"); + rig.C.RingCountOverride = () => 1; + Check.Eq(rig.Cast("Nether", BoltRing()), ("Flame Bolt VI", "Bolt"), "too few near: Fire's bolt, as before"); + + // Void trained: the Nether rule casts Void's ring, as before. + var both = new Rig(7, known, war: (400, 3), voidMagic: (400, 3)); + both.C.RingCountOverride = () => 5; + Check.Eq(both.Cast("Nether", BoltRing()), ("Clouded Soul II", "Ring"), "Void trained: Void's ring"); + + // War only, Nether rule, no fire ring known: the reason names Fire's rings. + var none = new Rig(7, new[] { "Flame Bolt VI" }, war: (400, 3), voidMagic: (10, 1)); + none.C.RingCountOverride = () => 5; + Check.Eq(none.Cast("Nether", BoltRing()), ("Flame Bolt VI", "Bolt"), "no fire ring known: the bolt"); + Check.Eq(Lines("no Nether ring spell known (tried: Cassius' Ring of Fire II, Cassius' Ring of Fire, Flame Ring)"), 1, "the rings tried are Fire's"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/SelfTestMetaTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/SelfTestMetaTests.cs index 26fec4a..62ec361 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/SelfTestMetaTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/SelfTestMetaTests.cs @@ -40,6 +40,9 @@ internal static class SelfTestMetaTests Check.Eq(bare.M.Expressions.Evaluate("ratargetcount[]"), "-1", "not wired: -1"); bare.M.SetCombatTargetCount(() => 3); Check.Eq(bare.M.Expressions.Evaluate("ratargetcount[]"), "3", "wired: combat's count"); + Check.Eq(bare.M.Expressions.Evaluate("ralastchestlooted[]"), "0", "ralastchestlooted[] not wired: 0"); + bare.M.SetLastChestLooted(() => 0x80061193u); + Check.Eq(bare.M.Expressions.Evaluate("ralastchestlooted[]"), "2147881363", "wired: the chest's id, as wobjectgetid[] gives it"); Run Beside(int targets) { diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/SessionBankProfileTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/SessionBankProfileTests.cs new file mode 100644 index 0000000..6280dba --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/SessionBankProfileTests.cs @@ -0,0 +1,146 @@ +using System.IO; +using System.Threading; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The session's luminance from the active server profile's bank value (SessionStatsTracker: RynthAi's +// Mini Remote stats, which RynthTracker shows; 2026-11-02). A server that keeps earned luminance in its +// bank where the client can't read it has its server plugin publish "bankLuminance" (a /b every minute); +// its rises are Lum/hr, a drop (spending) isn't negative, and ACECustom's own bank property (9005) wins +// when it is readable. Without the value nothing changes. +internal static class SessionBankProfileTests +{ + private const uint Player = 0x50000D02; + private const uint TotalXp = 1; + private const uint BankedLuminance = 9005; + private const string Tag = "[RynthAi] Mini Remote stats:"; + + public static void Register(Runner r) + { + r.Add("session stats: the server profile's bank luminance rises are Lum/hr, a drop isn't negative", BankRises); + r.Add("session stats: without a bank value in the profile, luminance stays as before", NoValue); + r.Add("session stats: ACECustom's bank property wins over the profile's bank value", PropertyWins); + r.Add("session stats: the profile's bank baseline carries over a reload", AcrossReload); + } + + private static string Folder(string name) + { + string dir = Path.Combine(Program.TempRoot, "session-bank", name); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + return dir; + } + + private static RynthCoreHost Create(double? bank) + { + FakeHost.Reset(); + FakeServerState.Reset(); + FakeServerState.Install(); + var host = FakeHost.Create(Player); + FakeHost.Quads[(Player, TotalXp)] = 1_000_000; + FakeServerState.StateJson = FakeServerState.State("testsrv", "Test Server", "RynthTestSrv", "Test World"); + SetBank(bank); + return host; + } + + private static void SetBank(double? bank) + => FakeServerState.ProfileJson = bank is double b + ? FakeServerState.Profile("testsrv", ("bankLuminance", b)) + : FakeServerState.Profile("testsrv", ("difficultyTier", 0)); + + private static SessionStatsTracker LogIn(RynthCoreHost host, string dir) + { + var t = new SessionStatsTracker(host, Tag, dir) { ProfileIntervalMs = 0 }; + t.OnLoginComplete(); + t.Tick(); + return t; + } + + /// The next poll (the tracker reads every 0.5 s on the real clock). + private static void NextPoll(SessionStatsTracker t) + { + Thread.Sleep(550); + t.Tick(); + } + + private static void BankRises() + { + try + { + var host = Create(1_000_000); + var t = LogIn(host, Folder("rises")); + Check.Eq(t.View.Lum, 0L, "the first reading is the baseline"); + SetBank(1_250_000); + NextPoll(t); + Check.Eq(t.View.Lum, 250_000L, "a rise is earned luminance"); + Check.True(t.View.LumPerHour > 0, "Lum/hr above 0"); + NextPoll(t); + Check.Eq(t.View.Lum, 250_000L, "the same reading again adds nothing"); + SetBank(200_000); // spent from the bank + NextPoll(t); + Check.Eq(t.View.Lum, 250_000L, "a drop isn't counted (nor negative)"); + SetBank(260_000); + NextPoll(t); + Check.Eq(t.View.Lum, 310_000L, "the next rise counts from the drop"); + Check.Eq(t.View.LumLast5Min, 310_000L, "and in the last five minutes"); + t.OnLogout(); + } + finally { FakeHost.Reset(); FakeServerState.Reset(); } + } + + private static void NoValue() + { + try + { + var host = Create(null); + FakeHost.Quads[(Player, 6)] = 5_000; // AvailableLuminance, as on retail ACE + var t = LogIn(host, Folder("none")); + FakeHost.Quads[(Player, 6)] = 7_000; + NextPoll(t); + Check.Eq(t.View.Lum, 2_000L, "the character's luminance counts as before"); + Check.False(t.View.PassUpTracked, "no bank is tracked"); + t.OnLogout(); + } + finally { FakeHost.Reset(); FakeServerState.Reset(); } + } + + private static void PropertyWins() + { + try + { + var host = Create(50); + FakeHost.Quads[(Player, BankedLuminance)] = 1_000_000; + var t = LogIn(host, Folder("property")); + SetBank(900_000); + FakeHost.Quads[(Player, BankedLuminance)] = 1_000_400; + NextPoll(t); + Check.Eq(t.View.Lum, 400L, "9005's rise counts, the profile's value is not used"); + t.OnLogout(); + } + finally { FakeHost.Reset(); FakeServerState.Reset(); } + } + + // A hot reload is a Shutdown (the save) and a new copy's OnLoginComplete (the restore). + private static void AcrossReload() + { + try + { + var host = Create(1_000_000); + string dir = Folder("reload"); + var a = LogIn(host, dir); + SetBank(1_100_000); + NextPoll(a); + Check.Eq(a.View.Lum, 100_000L, "before the reload"); + a.Shutdown(); + SetBank(1_150_000); // earned while the plugin was unloaded + var b = LogIn(host, dir); + NextPoll(b); + Check.Eq(b.View.Lum, 150_000L, "the gap's luminance counts once after the reload"); + b.OnLogout(); + } + finally { FakeHost.Reset(); FakeServerState.Reset(); } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ShieldBuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ShieldBuffTests.cs index 09f285f..f635f3d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ShieldBuffTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ShieldBuffTests.cs @@ -41,9 +41,18 @@ internal static class ShieldBuffTests r.Add("shield buffs: a shield being moved is not cast at until the move settles", MidSwapWaits); r.Add("shield buffs: renewed on the armor's timers (Rebuff With, Also Refresh Under, Force Rebuff)", RenewedLikeArmor); r.Add("shield buffs: a fizzle, a refusal or a late armor line at the shield leaves the armor alone", RefusalsLeaveArmor); - r.Add("shield buffs: casts at the shield with no answer, or 'cannot be cast on', rest shield buffing; the armor carries on", NoAnswerParks); + r.Add("shield buffs: casts at the shield with no answer rest shield buffing; 'cannot be cast on' skips that shield for good (kept, /ra buffs unbuffable clear); the armor carries on", NoAnswerParks); r.Add("shield buffs: the shield's timers are saved and loaded with the others", TimersSaved); r.Add("shield buffs: Buff the shield defaults on, loads, saves, copies, is in the settings map", Setting); + r.Add("shield buffs: a shield marked No buff gets nothing (rebuff batch, Force Rebuff, expiring), never makes buffing due; the armor as always", ExcludedShield); + r.Add("shield buffs: two shields listed, one marked No buff: the other is still buffed", ExcludedShieldOtherStillBuffed); + r.Add("shield buffs: cast lines naming a No buff shield (self-cast reaching it, late line, an in-flight cast) never make a rebuff due", ExcludedShieldCastLinesNeverDue); + r.Add("shield buffs: the kept shield choice is read again at once when an entry's No buff flips in place", ExcludedFlipInvalidatesShieldChoice); + r.Add("shield buffs: No buff on a weapon (non-shield) does nothing: the weapon auras as always", ExcludedWeaponDoesNothing); + r.Add("shield buffs: the Items bridge carries noBuff for every entry, applies it back for shields only, absent = unchanged, never saved", NoBuffPayloadContract); + r.Add("shield buffs: a No buff shield in the off hand: no shield is buffed, not one put away for the wand before", ExcludedWornBeatsStaleStow); + r.Add("shield buffs: a shield listed twice, one rule No buff: left alone, in either order", ExcludedAnyRuleEitherOrder); + r.Add("shield buffs: a VTank re-import keeps a shield's No buff", ReimportKeepsShieldExclusion); } // ── Rig ─────────────────────────────────────────────────────────────────── @@ -499,17 +508,37 @@ internal static class ShieldBuffTests Check.Eq(rig.Sm.UnresolvableSpellIds.Count, 0, "no spell blacklisted (it just went on the armor)"); Check.True(Armor.All(rig.HasArmor), "the armor got everything"); - // "cannot be cast on" (ACE IsInvalidTarget) parks it at once. + // "cannot be cast on" (ACE IsInvalidTarget): the shield takes no spells, never buffed again + // (2026-11-08, Tom: "if an item is deemed unbuffable it should just skip it altogether"). + string folder = Path.Combine(Program.TempRoot, "shieldbuff-unbuffable"); + Directory.CreateDirectory(folder); + foreach (string f in Directory.GetFiles(folder)) File.Delete(f); var invalid = new Rig(worn: true); + invalid.B.SetTimerPath(folder); invalid.PutAwayForWand(); Check.Eq(ToFirstShieldCast(invalid), "Impenetrability VI", "a cast at the shield"); invalid.B.OnChatWindowText("Impenetrability VI cannot be cast on Kite Shield.", 7); Check.Eq(invalid.B.PendingSpellId, 0, "it ends the cast"); + Check.Eq(invalid.B.UnbuffableShields.Count, 1, "the shield is marked as taking no spells"); invalid.EndRun(); - Check.False(invalid.B.NeedsAnyBuff(), "the shield rests"); + Check.False(invalid.B.NeedsAnyBuff(), "the shield never holds Buffing"); Check.Eq(invalid.CastAll().Count, 0, "nothing more at it"); invalid.B.ForceFullRebuff(); - Check.Eq(string.Join(", ", At(invalid.CastAll(), "Kite Shield")), ArmorAtPlayer, "Force Rebuff gives it a fresh try"); + Check.Eq(At(invalid.CastAll(), "Kite Shield").Count(), 0, "Force Rebuff doesn't try it again either"); + Check.True(File.ReadAllLines(Path.Combine(folder, "bufftimers.txt")).Any(l => l.StartsWith("unbuffable|", StringComparison.Ordinal)), "kept in bufftimers.txt"); + + // Kept across a reload; /ra buffs unbuffable clear forgets it and it is tried again. + var reloaded = new Rig(worn: true); + reloaded.PutAwayForWand(); + reloaded.B.SetTimerPath(folder); + Check.Eq(reloaded.B.UnbuffableShields.Count, 1, "loaded back"); + Check.Eq(At(reloaded.CastAll(), "Kite Shield").Count(), 0, "still skipped after the reload"); + var listed = reloaded.B.UnbuffableCommand(clear: false); + Check.True(listed.Any(l => l.Contains("Kite Shield", StringComparison.Ordinal)), "/ra buffs unbuffable lists it: " + string.Join(" | ", listed)); + reloaded.B.UnbuffableCommand(clear: true); + Check.Eq(reloaded.B.UnbuffableShields.Count, 0, "cleared"); + reloaded.B.ForceFullRebuff(); + Check.Eq(string.Join(", ", At(reloaded.CastAll(), "Kite Shield")), ArmorAtPlayer, "cleared: tried again"); // The same line with nothing aimed at a shield changes nothing. var other = new Rig(worn: true, listShield: false); @@ -537,6 +566,271 @@ internal static class ShieldBuffTests Check.Eq(again.CastAll().Count, 0, "nothing due after the reload"); } + // ── No buff (ItemRule.KeepBuffed off on a listed shield) ───────────────── + + private const string MarkedWhy = "the listed shield is marked No buff"; + + private static void ExcludeId(Rig rig, uint id) => rig.S.ItemRules.First(x => x.Id == unchecked((int)id)).KeepBuffed = false; + + private static void ExcludedShield() + { + // Control: the same rig, not marked, casts at the shield (StowedShieldBuffed has the detail). + var control = new Rig(worn: true); + control.PutAwayForWand(); + Check.Eq(At(control.CastAll(), "Kite Shield").Count(), Armor.Length, "control: the listed shield gets its armor spells"); + + // Put away for the wand and worn: left alone either way. + foreach (bool stowed in new[] { true, false }) + { + var rig = new Rig(worn: true); + ExcludeId(rig, Kite); + if (stowed) rig.PutAwayForWand(); + string how = stowed ? "put away for the wand" : "in the off hand"; + Check.Eq(rig.B.ShieldToBuff(out string where), 0, $"{how}: no shield to buff ({where})"); + Check.Eq(where, MarkedWhy, $"{how}: and the reason says why"); + var sent = rig.CastAll(); + Check.Eq(At(sent, "Kite Shield").Count(), 0, $"{how}: nothing aimed at the marked shield"); + Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", $"{how}: the character's buffs as always"); + Check.False(rig.B.NeedsAnyBuff(), $"{how}: nothing due after the run"); + + // Force Rebuff (and /ra buff, which runs it): still nothing at the shield. + rig.B.ForceFullRebuff(); + sent = rig.CastAll(); + Check.Eq(At(sent, "Kite Shield").Count(), 0, $"{how}: Force Rebuff casts nothing at it"); + Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", $"{how}: Force Rebuff still renews the character's"); + Check.False(rig.B.NeedsAnyBuff(), $"{how}: the run ends done"); + Check.False(FakeHost.Casts.Any(c => c.Target == Kite), $"{how}: no cast ever went at the shield"); + } + + // A shield timer from before it was marked running low makes nothing due. + var was = new Rig(worn: true); + was.PutAwayForWand(); + was.CastAll(); + Check.Eq(was.B.ShieldSpellCount, Armor.Length, "buffed before it was marked"); + was.SetShieldLeft("Flame Bane VI", 10); + Check.True(was.B.NeedsAnyBuff(), "control: its bane running out is due while it is buffed"); + ExcludeId(was, Kite); + was.S.ItemRules = new List(was.S.ItemRules); // the Items face saves a new list + Check.False(was.B.NeedsAnyBuff(), "marked: its expiring bane is not due"); + Check.Eq(was.CastAll().Count, 0, "and nothing is cast for it"); + + // Two shields listed, the worn one marked: the other (in a pack, not in use) is no target either. + var two = new Rig(worn: true); + two.List(Sword, Kite, Round); + ExcludeId(two, Kite); + Check.Eq(two.B.ShieldToBuff(out _), 0, "the worn shield marked, the other in a pack: none"); + Check.Eq(At(two.CastAll(), "Round Shield").Count(), 0, "nothing goes to the other shield instead"); + } + + private static void ExcludedShieldOtherStillBuffed() + { + // The Kite marked and in a pack, the Round worn: the Round is buffed. + var pin = new Rig(); + Wear(Round); + pin.List(Sword, Kite, Round); + ExcludeId(pin, Kite); + Check.Eq(pin.B.ShieldToBuff(out string where), unchecked((int)Round), "the other listed shield, worn: " + where); + var sent = pin.CastAll(); + Check.Eq(string.Join(", ", At(sent, "Round Shield")), ArmorAtPlayer, "the other shield gets the armor spells"); + Check.Eq(At(sent, "Kite Shield").Count(), 0, "nothing at the marked one"); + + // Both read as in hand, the marked Kite listed FIRST. Ignoring the flag the first listed + // (Kite) would be picked; with it, the Round is. + var both = new Rig(worn: true); + Wear(Round); + both.List(Sword, Kite, Round); + Check.Eq(both.B.ShieldToBuff(out _), unchecked((int)Kite), "control: nothing marked, the first listed in hand is picked"); + ExcludeId(both, Kite); + Check.Eq(both.B.ShieldToBuff(out where, fresh: true), unchecked((int)Round), "the Kite marked: the Round is picked (" + where + ")"); + sent = both.CastAll(); + Check.Eq(string.Join(", ", At(sent, "Round Shield")), ArmorAtPlayer, "and buffed"); + Check.Eq(At(sent, "Kite Shield").Count(), 0, "never the marked one"); + Check.False(both.B.NeedsAnyBuff(), "nothing due after the run"); + } + + private static void ExcludedShieldCastLinesNeverDue() + { + // 1. The self-cast reached the worn, marked shield ("You cast X on Kite Shield"): no timer + // is kept for it, so nothing on it can ever run low and make buffing due. + var self = new Rig(worn: true); + ExcludeId(self, Kite); + var sent = self.CastAll(alsoOnShield: _ => true); + Check.Eq(At(sent, "Kite Shield").Count(), 0, "nothing aimed at it"); + Check.Eq(self.B.ShieldSpellCount, 0, "its self-cast lines record no shield timer"); + Check.True(Armor.All(self.HasArmor), "the armor's are recorded as always"); + Check.False(self.B.NeedsAnyBuff(), "nothing due"); + + // 2. A late line naming it, nothing pending. + self.B.OnChatWindowText("You cast Flame Bane VI on Kite Shield", 7); + Check.Eq(self.B.ShieldSpellCount, 0, "a late line names it: still no shield timer"); + Check.False(self.B.NeedsAnyBuff(), "and nothing due"); + + // 3. A cast at it already in flight when it is marked: its line may record the timer, but + // neither that nor the timer running low makes anything due. + var flight = new Rig(worn: true); + flight.PutAwayForWand(); + flight.B.ForceFullRebuff(); + string first = ToFirstShieldCast(flight); + Check.Eq(first, "Impenetrability VI", "a cast at the shield is pending"); + ExcludeId(flight, Kite); + flight.S.ItemRules = new List(flight.S.ItemRules); // the Items face saves a new list + flight.Answer(Kite, first); + Check.Eq(flight.B.PendingSpellId, 0, "its line resolves the cast"); + Check.Eq(flight.CastAll().Count(s => s.EndsWith("@Kite Shield", StringComparison.Ordinal)), 0, "nothing more at it"); + Check.False(flight.B.NeedsAnyBuff(), "nothing due after the run"); + if (flight.HasShield("Impenetrability VI")) + { + flight.SetShieldLeft("Impenetrability VI", 10); + Check.False(flight.B.NeedsAnyBuff(), "its recorded timer running low is not due"); + } + Check.Eq(flight.CastAll().Count, 0, "and nothing is cast for it"); + + // Control for 1: the same lines with it not marked do record the shield's timers. + var control = new Rig(worn: true); + control.CastAll(alsoOnShield: _ => true); + Check.Eq(control.B.ShieldSpellCount, Armor.Length, "control: not marked, the lines record its timers"); + } + + private static void ExcludedWornBeatsStaleStow() + { + // The Kite was put away for the wand some time ago; the Round is now in the off hand. + Rig Make(bool excludeRound) + { + var made = new Rig(worn: true); + made.List(Sword, Kite, Round); + made.PutAwayForWand(); // the Kite into a pack, remembered as stowed + Wear(Round); + if (excludeRound) ExcludeId(made, Round); + return made; + } + + var control = Make(excludeRound: false); + Check.Eq(control.B.ShieldToBuff(out string where), unchecked((int)Round), "control: the Round in the off hand is picked (" + where + ")"); + + var rig = Make(excludeRound: true); + Check.Eq(rig.B.ShieldToBuff(out where), 0, "the marked Round in the off hand: no shield"); + Check.Eq(where, "the shield in the off hand is marked No buff", "and the reason says so"); + var sent = rig.CastAll(); + Check.Eq(At(sent, "Kite Shield").Count() + At(sent, "Round Shield").Count(), 0, "no cast names either shield: " + string.Join(", ", sent)); + Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the character's buffs as always"); + Check.False(rig.B.NeedsAnyBuff(), "nothing due"); + } + + private static void ExcludedAnyRuleEitherOrder() + { + foreach (bool excludedFirst in new[] { false, true }) + { + var rig = new Rig(worn: true); + var keep = new ItemRule { Id = unchecked((int)Kite), Name = "Kite Shield", Action = WeaponList.ShieldAction, Element = "", ElementSource = "" }; + var off = new ItemRule { Id = unchecked((int)Kite), Name = "Kite Shield", Action = WeaponList.ShieldAction, Element = "", ElementSource = "", KeepBuffed = false }; + var sword = rig.S.ItemRules.First(x => x.Id == unchecked((int)Sword)); + rig.S.ItemRules = excludedFirst ? new List { sword, off, keep } : new List { sword, keep, off }; + string order = excludedFirst ? "the marked rule first" : "the marked rule second"; + Check.Eq(rig.B.ShieldToBuff(out string where), 0, $"{order}: no shield ({where})"); + Check.Eq(At(rig.CastAll(), "Kite Shield").Count(), 0, $"{order}: nothing at it"); + } + } + + private static void ReimportKeepsShieldExclusion() + { + ItemRule Rule(int id, string action, bool keep) => new() { Id = id, Name = "x" + id, Action = action, Element = "Slash", KeepBuffed = keep }; + var rules = new List + { + Rule(1, WeaponList.ShieldAction, false), // a marked shield + Rule(2, WeaponList.ShieldAction, true), + Rule(3, "Weapon", false), // a "marked" weapon (the flag does nothing there) + }; + foreach (int id in new[] { 1, 2, 3, 4 }) + RynthCore.Plugin.RynthAi.MiniRemote.VTankUsdImporter.ReplaceItemRule(rules, Rule(id, id <= 2 ? WeaponList.ShieldAction : "Weapon", true)); + Check.Eq(rules.Count, 4, "each id replaced once, the new one added"); + Check.True(rules.Single(x => x.Id == 1).ExcludedFromBuffing(), "the marked shield stays marked after a re-import"); + Check.False(rules.Single(x => x.Id == 2).ExcludedFromBuffing(), "a buffed shield stays buffed"); + Check.False(rules.Single(x => x.Id == 3).ExcludedFromBuffing(), "a weapon takes the import as it is"); + Check.False(rules.Single(x => x.Id == 4).ExcludedFromBuffing(), "a new entry is buffed"); + } + + private static void ExcludedFlipInvalidatesShieldChoice() + { + var rig = new Rig(worn: true); + long ms = 50_000; + rig.B.KitClockMs = () => ms; + rig.B.ShieldReadMs = 1000; // the shipped value + Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "the worn shield, kept for a second"); + ms += 10; + Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "control: 10 ms later the kept answer"); + ExcludeId(rig, Kite); // flipped in place: same list, same count + ms += 10; + Check.Eq(rig.B.ShieldToBuff(out string where), 0, "marked in place: read again at once, none (" + where + ")"); + rig.S.ItemRules.First(x => x.Id == unchecked((int)Kite)).KeepBuffed = true; + ms += 10; + Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "and back on: at once"); + } + + private static void ExcludedWeaponDoesNothing() + { + // Marking a weapon does nothing: the marked sword's own aura (Blood Drinker) is still due. + var rig = new Rig(worn: true, listShield: false); + ExcludeId(rig, Sword); + var sent = rig.CastAll(); + Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the marked sword still makes its aura due"); + Check.Eq(rig.B.ShieldToBuff(out _), 0, "and no shield is involved"); + } + + private static void NoBuffPayloadContract() + { + const int SwordId = 1, ShieldId = 3; + List Saved(bool swordKeep, bool shieldKeep) => new() + { + new() { Id = SwordId, Name = "Sword", Action = "Weapon", Element = "Slash", KeepBuffed = swordKeep }, + new() { Id = ShieldId, Name = "Shield", Action = WeaponList.ShieldAction, Element = "", KeepBuffed = shieldKeep }, + }; + + // Out: every entry carries noBuff, shields and weapons alike. + var shown = WeaponList.ForDisplay(Saved(false, false), x => x.Name); + Check.True(shown.All(x => x.NoBuff == true), "a marked entry is sent noBuff true (weapon and shield)"); + shown = WeaponList.ForDisplay(Saved(true, true), x => x.Name); + Check.True(shown.All(x => x.NoBuff == false), "a buffed entry is sent noBuff false"); + string json = JsonSerializer.Serialize(new ItemsBridgePayload { Weapons = WeaponList.ForDisplay(Saved(true, false), x => x.Name) }, + RynthAiJsonContext.Default.ItemsBridgePayload); + Check.Eq(System.Text.RegularExpressions.Regex.Matches(json, "\"noBuff\":").Count, 2, "the wire field is \"noBuff\", once per entry: " + json); + Check.True(System.Text.RegularExpressions.Regex.IsMatch(json, "\"noBuff\":\\s*false") && System.Text.RegularExpressions.Regex.IsMatch(json, "\"noBuff\":\\s*true"), + "with its value per entry: " + json); + + // Back, in the engine's shape (lower-case names, only the fields WeaponEntry knows). + List Back(string weapons) => + WeaponList.MergeEdited(Saved(true, true), + JsonSerializer.Deserialize("{\"weapons\":[" + weapons + "]}", RynthAiJsonContext.Default.ItemsBridgePayload)!.Weapons); + const string Sw = "{\"id\":1,\"name\":\"Sword\",\"element\":\"Slash\",\"action\":\"Weapon\""; + const string Sh = "{\"id\":3,\"name\":\"Shield\",\"element\":\"Shield\",\"action\":\"Shield\""; + var m = Back(Sw + "}," + Sh + ",\"noBuff\":true}"); + Check.True(m.Single(x => x.Id == ShieldId).ExcludedFromBuffing(), "a shield ticked noBuff is left alone"); + m = Back(Sw + ",\"noBuff\":true}," + Sh + "}"); + Check.False(m.Single(x => x.Id == SwordId).ExcludedFromBuffing(), "noBuff on a weapon is ignored"); + m = WeaponList.MergeEdited(Saved(true, false), + JsonSerializer.Deserialize("{\"weapons\":[" + Sw + "}," + Sh + ",\"noBuff\":false}]}", RynthAiJsonContext.Default.ItemsBridgePayload)!.Weapons); + Check.False(m.Single(x => x.Id == ShieldId).ExcludedFromBuffing(), "a shield unticked is buffed again"); + m = WeaponList.MergeEdited(Saved(false, false), + JsonSerializer.Deserialize("{\"weapons\":[" + Sw + "}," + Sh + "}]}", RynthAiJsonContext.Default.ItemsBridgePayload)!.Weapons); + Check.True(m.All(x => x.ExcludedFromBuffing()), "noBuff absent (an older engine): both keep their saved value"); + m = WeaponList.MergeEdited(Saved(true, true), + JsonSerializer.Deserialize("{\"weapons\":[" + Sw + "}," + Sh + ",\"noBuff\":null}]}", RynthAiJsonContext.Default.ItemsBridgePayload)!.Weapons); + Check.False(m.Single(x => x.Id == ShieldId).ExcludedFromBuffing(), "noBuff null: unchanged"); + Check.True(m.All(x => x.NoBuff == null), "merged entries carry no wire field"); + var added = WeaponList.MergeEdited(new List(), new[] { new ItemRule { Id = 9, Name = "New", Action = WeaponList.ShieldAction, NoBuff = true } }); + Check.True(added.Single().ExcludedFromBuffing() && added.Single().NoBuff == null, "a new shield entry takes noBuff, and drops the wire field"); + + // Saved profiles: the field is never written; old profiles load with nothing marked. + var settings = new LegacyUiSettings { ItemRules = m }; + string profile = JsonSerializer.Serialize(settings, RynthAiJsonContext.Default.LegacyUiSettings); + Check.False(profile.Contains("noBuff", StringComparison.OrdinalIgnoreCase), "a saved profile has no noBuff"); + var old = JsonSerializer.Deserialize("{\"ItemRules\":[{\"Id\":1,\"Name\":\"Sword\",\"Action\":\"Weapon\"},{\"Id\":3,\"Name\":\"Shield\",\"Action\":\"Shield\",\"KeepBuffed\":true}]}", + RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(old != null && old.ItemRules.Count == 2 && old.ItemRules.All(x => !x.ExcludedFromBuffing()), "old profiles load with nothing marked"); + var round = JsonSerializer.Deserialize(JsonSerializer.Serialize(new LegacyUiSettings { ItemRules = { new ItemRule { Id = 3, Name = "Shield", Action = WeaponList.ShieldAction, KeepBuffed = false } } }, + RynthAiJsonContext.Default.LegacyUiSettings), RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(round != null && round.ItemRules.Single().ExcludedFromBuffing(), "No buff is saved and loaded"); + } + private static void Setting() { Check.True(new LegacyUiSettings().BuffShield, "a new profile: on"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ShieldFacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ShieldFacingTests.cs new file mode 100644 index 0000000..4caa30d --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ShieldFacingTests.cs @@ -0,0 +1,408 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.Json; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.CreatureData; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Damage taken by shield and facing (2026-11-08): does a shield actually cut a boss's hits? ACE +// counts a shield only in a combat stance and only when the attacker is within 90 degrees of the +// defender's facing (Creature_Combat.GetShieldMod, effectiveAngle 180). Each monster hit line is +// learned split by both, saved as TS rows in monster_damage.txt, and sent with the Damage panel row. +internal static class ShieldFacingTests +{ + private const uint Player = 0x50000C01; + private const uint Boss = 0x80001001, BossTwin = 0x80001002; + private const uint BossWcid = 70001; + private const uint Sword = 0x80000401, Shield = 0x80000404, Dagger = 0x80000402; + private const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000; + private const string BossName = "Hive Boss"; + private static readonly BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("shield facing: in front within 90 degrees either side, behind past it, at every heading", FacingMath); + r.Add("shield facing: unknown when nothing can be measured (on top, no frame, too far, NaN)", FacingUnknown); + r.Add("shield facing: the compass heading comes from the pose quaternion (not GetPlayerHeading)", HeadingFromQuaternion); + r.Add("shield facing: a monster's hit line is split by shield and where it stood", HitLinesSplit); + r.Add("shield facing: peace, a dual-wield off hand, an unknown off-hand item, two of the name that disagree", HitLinesEdgeCases); + r.Add("shield facing: TS rows save and load (tier rows too), old files load, unknown kinds are skipped", SaveLoadRoundTrip); + r.Add("shield facing: the [Taken] summary is one line per monster, not one per hit", SummaryLine); + r.Add("shield facing: the Damage panel row's mstats carries the split, even with no session numbers", DamageRowJson); + } + + // ── The math ───────────────────────────────────────────────────────────── + + /// The point m away at compass bearing (0 = North, clockwise). + private static (double X, double Y) At(double bearing, double dist) + { + double r = bearing * Math.PI / 180.0; + return (Math.Sin(r) * dist, Math.Cos(r) * dist); + } + + private static HitFacing F(double heading, double relBearing, double dist = 5) + { + var (x, y) = At(heading + relBearing, dist); + return ShieldFacing.Classify(heading, 0, 0, x, y); + } + + private static void FacingMath() + { + foreach (double h in new[] { 0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 359.0, 1.0 }) + { + Check.Eq(F(h, 0), HitFacing.Front, $"heading {h}: straight ahead is in front"); + Check.Eq(F(h, 180), HitFacing.Behind, $"heading {h}: straight behind"); + Check.Eq(F(h, 45), HitFacing.Front, $"heading {h}: 45 right is in front"); + Check.Eq(F(h, -45), HitFacing.Front, $"heading {h}: 45 left is in front"); + Check.Eq(F(h, 89), HitFacing.Front, $"heading {h}: 89 right is in front"); + Check.Eq(F(h, -89), HitFacing.Front, $"heading {h}: 89 left is in front"); + Check.Eq(F(h, 91), HitFacing.Behind, $"heading {h}: 91 right is behind"); + Check.Eq(F(h, -91), HitFacing.Behind, $"heading {h}: 91 left is behind"); + Check.Eq(F(h, 135), HitFacing.Behind, $"heading {h}: back right"); + Check.Eq(F(h, -135), HitFacing.Behind, $"heading {h}: back left"); + } + // Exactly at the side: ACE's test is |angle| > 90 for no shield, so 90 still counts. + Check.Eq(ShieldFacing.Classify(0, 0, 0, 5, 0), HitFacing.Front, "facing north, the attacker due east (90): in front"); + Check.Eq(ShieldFacing.Classify(0, 0, 0, -5, 0), HitFacing.Front, "due west (-90): in front"); + Check.Eq(ShieldFacing.Classify(90, 0, 0, 0, -5), HitFacing.Front, "facing east, due south: in front (side)"); + Check.Eq(ShieldFacing.Classify(90, 0, 0, -5, 0.01), HitFacing.Behind, "facing east, due west: behind"); + // The compass basis: facing north, a monster to the north-east is in front, to the south-west behind. + Check.Eq(ShieldFacing.Classify(0, 10, 10, 13, 13), HitFacing.Front, "north-east of us, facing north"); + Check.Eq(ShieldFacing.Classify(0, 10, 10, 7, 7), HitFacing.Behind, "south-west of us, facing north"); + Check.Eq(ShieldFacing.Classify(270, 10, 10, 5, 10), HitFacing.Front, "facing west, a monster west"); + Check.Eq(ShieldFacing.Classify(270, 10, 10, 15, 10), HitFacing.Behind, "facing west, a monster east"); + Check.Eq(Math.Round(ShieldFacing.AngleTo(350, 1, 10), 0), 16.0, "angle wraps past north (350 -> 5.7)"); + + // Landblock-local positions: across an outdoor landblock edge they are one frame. + Check.Eq(ShieldFacing.Classify(90, 0xA9B40001, 191f, 50f, 0xAAB40001, 1f, 50f), HitFacing.Front, + "outdoors, the attacker 2 m east in the next landblock, facing east"); + Check.Eq(ShieldFacing.Classify(270, 0xA9B40001, 191f, 50f, 0xAAB40001, 1f, 50f), HitFacing.Behind, + "the same, facing west"); + Check.Eq(ShieldFacing.Classify(0, 0x01D90105, 10f, 10f, 0x01D9010A, 10f, 20f), HitFacing.Front, + "in a dungeon, two cells of one landblock share its frame"); + + // Several of the name: they must all agree. + Check.Eq(ShieldFacing.Agree(new[] { HitFacing.Front, HitFacing.Front }), HitFacing.Front, "all in front: front"); + Check.Eq(ShieldFacing.Agree(new[] { HitFacing.Front, HitFacing.Behind }), HitFacing.Unknown, "one each side: unknown"); + Check.Eq(ShieldFacing.Agree(new[] { HitFacing.Behind, HitFacing.Unknown }), HitFacing.Unknown, "one not measurable: unknown"); + Check.Eq(ShieldFacing.Agree(Array.Empty()), HitFacing.Unknown, "none: unknown"); + } + + private static void FacingUnknown() + { + Check.Eq(ShieldFacing.Classify(0, 10, 10, 10, 10), HitFacing.Unknown, "on top of us: no direction"); + Check.Eq(ShieldFacing.Classify(double.NaN, 0, 0, 5, 5), HitFacing.Unknown, "no heading"); + Check.Eq(ShieldFacing.Classify(0, 0, 0, double.NaN, 5), HitFacing.Unknown, "a garbage position"); + Check.Eq(ShieldFacing.Classify(0, 0x01D90105, 10f, 10f, 0x01DA0105, 10f, 20f), HitFacing.Unknown, + "two dungeon landblocks: no shared frame"); + Check.Eq(ShieldFacing.Classify(0, 0xA9B40001, 10f, 10f, 0xA9B40001, 10f, 100f), HitFacing.Unknown, + "90 m away: too far to be the one that hit"); + Check.Eq(ShieldFacing.Classify(0, 0xA9B40001, 10f, 10f, 0xA9B40001, 10f, 80f), HitFacing.Front, "70 m: measured"); + Check.True(ShieldFacing.TryParse("behind", out var b) && b == HitFacing.Behind, "parse behind"); + Check.False(ShieldFacing.TryParse("sideways", out _), "an unknown word does not parse"); + } + + private static void HeadingFromQuaternion() + { + FakeHost.Reset(); + FakeHost.PlayerPose = (0xA9B40001, 10f, 10f, 0f); + var host = FakeHost.Create(Player); + foreach (double h in new[] { 0.0, 13.9, 90.0, 180.0, 270.0, 300.0 }) + { + FakeHost.HeadingDeg = h; + Check.True(PlayerCompass.TryGet(host, out float c), "pose read"); + Check.Eq(Math.Round(c, 1), Math.Round(h, 1), $"compass {h} from the quaternion"); + double half = -h * Math.PI / 360.0; + Check.Eq(Math.Round(ShieldFacing.CompassFromQuaternion(Math.Cos(half), Math.Sin(half)), 1), Math.Round(h % 360.0, 1), + $"ShieldFacing reads {h} the same way"); + } + } + + // ── The rig: a boss hits us ────────────────────────────────────────────── + + private sealed class Rig + { + public readonly LegacyUiSettings S = new(); + public readonly CombatManager C; + public readonly MonsterDamageStore Store = new(); + + public Rig(bool shieldOn, double heading, (float X, float Y) boss, (float X, float Y)? twin = null, bool offhandUnknown = false, + bool dagger = false, int mode = CombatMode.Melee) + { + FakeHost.Reset(); + FakeHost.EquippedCalls = true; // the engine's EquipmentTracker (v87) + FakeHost.WeaponCalls = true; // GetCurrentCombatMode + FakeHost.CombatModeValue = mode; + FakeHost.PlayerPose = (0xA9B40001, 50f, 50f, 0f); + FakeHost.HeadingDeg = heading; + Item(Sword, "Long Sword", 0x1, MeleeSlot, 1); + Item(Shield, "Kite Shield", 0x2, ShieldSlot, 4); + Item(Dagger, "Dagger", 0x1, MeleeSlot, 1); + FakeHost.Equipped[Sword] = (uint)MeleeSlot; + if (shieldOn) FakeHost.Equipped[offhandUnknown ? 0x80000999u : Shield] = (uint)ShieldSlot; + if (dagger) FakeHost.Equipped[Dagger] = (uint)ShieldSlot; + Monster(Boss, boss); + var ids = new List { Sword, Shield, Dagger, Boss }; + var health = new Dictionary { [Boss] = 1f }; + if (twin is { } t) { Monster(BossTwin, t); ids.Add(BossTwin); health[BossTwin] = 1f; } + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, ids, health); + C = new CombatManager(host, S, cache); + C.SetPlayerId(Player); + string folder = Path.Combine(Program.TempRoot, "shield-facing", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(folder); + Store.SetCharacter(folder); + C.SetDamageStores(null, Store); + C.OffhandReadMs = 0; + EquippedState.Invalidate(); + var seen = (Dictionary)typeof(CombatManager).GetField("_seenMonsterNameToWcid", Any)!.GetValue(C)!; + seen[BossName] = BossWcid; // what the scan learns when it sees the boss + } + + private static void Item(uint id, string name, uint itemType, int validSlots, int combatUse) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = itemType; + FakeHost.Ints[(id, 9)] = validSlots; + FakeHost.Ints[(id, 51)] = combatUse; + } + + private static void Monster(uint id, (float X, float Y) at) + { + FakeHost.Names[id] = BossName; + FakeHost.ItemTypes[id] = 0x10; + FakeHost.Wcids[id] = BossWcid; + FakeHost.Positions[id] = (0xA9B40001, at.X, at.Y, 0f); + } + + public void Hit(int amount) => C.HandleChatForDamage($"{BossName} slashes your upper leg for {amount} points of slashing damage!"); + + public Dictionary<(bool, HitFacing), MonsterDamageStore.ShieldTakenRow> Split() + => Store.GetShieldTaken(BossWcid, 0).ToDictionary(r => (r.Shield, r.Facing)); + } + + private static void HitLinesSplit() + { + // Facing north, shield up, the boss 2 m north: in front, the shield counts. + var rig = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f)); + rig.Hit(10); + rig.Hit(14); + var s = rig.Split(); + Check.True(s.TryGetValue((true, HitFacing.Front), out var sf), "shield + front recorded"); + Check.Eq(sf.Hits, 2, "two hits"); + Check.Eq(sf.Avg, 12.0, "their mean"); + Check.Eq(sf.Max, 14.0, "the biggest"); + Check.Eq(s.Count, 1, "nothing else"); + var t = rig.Store.GetDetail(BossWcid, 0).Taken; + Check.True(t.Any(x => x.Element == "Slash" && x.Hits == 2), "the T row (per element) still learns the hits"); + + // It walks behind us. + FakeHost.Positions[Boss] = (0xA9B40001, 50f, 48f, 0f); + rig.Hit(60); + Check.Eq(rig.Split()[(true, HitFacing.Behind)].Hits, 1, "shield + behind"); + + // We turn round to face it: in front again. + FakeHost.HeadingDeg = 180; + rig.Hit(20); + Check.Eq(rig.Split()[(true, HitFacing.Front)].Hits, 3, "turned to face it: in front"); + + // No shield in the off hand. + var bare = new Rig(shieldOn: false, heading: 90, boss: (53f, 50f)); + bare.Hit(54); + bare.Hit(54); + var b = bare.Split(); + Check.Eq(b[(false, HitFacing.Front)].Hits, 2, "no shield, in front"); + Check.False(b.ContainsKey((true, HitFacing.Front)), "and no shield cell"); + FakeHost.Positions[Boss] = (0xA9B40001, 47f, 50f, 0f); + bare.Hit(70); + Check.Eq(bare.Split()[(false, HitFacing.Behind)].Max, 70.0, "no shield, behind"); + + // A line for a monster the bot never saw (no wcid) learns nothing. + bare.C.HandleChatForDamage("Some Stranger slashes your upper leg for 9 points of slashing damage!"); + Check.Eq(bare.Split().Values.Sum(x => x.Hits), 3, "an unknown monster's line is not counted"); + } + + private static void HitLinesEdgeCases() + { + var peace = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), mode: CombatMode.NonCombat); + peace.Hit(30); + Check.True(peace.Split().ContainsKey((false, HitFacing.Front)), "in peace ACE ignores the shield: shield 0"); + + var dw = new Rig(shieldOn: false, heading: 0, boss: (50f, 52f), dagger: true); + dw.Hit(30); + Check.True(dw.Split().ContainsKey((false, HitFacing.Front)), "a dagger in the off hand is no shield"); + + var unknown = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), offhandUnknown: true); + unknown.Hit(30); + Check.Eq(unknown.Split().Count, 0, "an off-hand item the cache doesn't know: not split (no guess)"); + Check.True(unknown.Store.GetDetail(BossWcid, 0).Taken.Any(x => x.Hits == 1), "the T row still learns it"); + + var twins = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), twin: (50f, 47f)); + twins.Hit(30); + Check.True(twins.Split().ContainsKey((true, HitFacing.Unknown)), "two of the name, one each side: unknown"); + + var agree = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), twin: (52f, 53f)); + agree.Hit(30); + Check.True(agree.Split().ContainsKey((true, HitFacing.Front)), "two of the name, both in front: front"); + + var far = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), twin: (50f, 0f)); + FakeHost.Positions[BossTwin] = (0xA9B40001, 50f, -60f, 0f); // 110 m behind: not the one that hit + far.Hit(30); + Check.True(far.Split().ContainsKey((true, HitFacing.Front)), "one of the name 110 m away is left out"); + + var dead = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), twin: (50f, 47f)); + var cache = (WorldObjectCache)typeof(CombatManager).GetField("_worldFilter", Any)!.GetValue(dead.C)!; + cache.OnUpdateHealth(BossTwin, 0f); + dead.Hit(30); + Check.True(dead.Split().ContainsKey((true, HitFacing.Front)), "a dead one of the name is left out"); + + var noPose = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f)); + FakeHost.HasPose = false; + noPose.Hit(30); + Check.True(noPose.Split().ContainsKey((true, HitFacing.Unknown)), "no pose: unknown"); + } + + // ── Save and load ──────────────────────────────────────────────────────── + + private static string Folder(string name) + { + string folder = Path.Combine(Program.TempRoot, "shield-facing-file", name); + if (Directory.Exists(folder)) Directory.Delete(folder, true); + Directory.CreateDirectory(folder); + return folder; + } + + private static void SaveLoadRoundTrip() + { + string folder = Folder("roundtrip"); + var s = new MonsterDamageStore(); + s.SetCharacter(folder); + s.RecordTaken(BossWcid, BossName, "Slash", 40); + s.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Front, 10); + s.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Front, 13); + s.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Behind, 274); + s.RecordTakenSplit(BossWcid, BossName, false, HitFacing.Unknown, 54); + s.Difficulty = 3; + s.RecordTakenSplit(BossWcid, BossName, false, HitFacing.Front, 90); + s.Difficulty = 0; + s.SaveIfDirty(); + + string file = Path.Combine(folder, "monster_damage.txt"); + string[] lines = File.ReadAllLines(file); + Check.True(lines.Any(l => l.StartsWith("# TS|wcid|name|shield|facing|hitsTaken|avgDamageTaken|maxDamageTaken")), "the header names the TS row"); + Check.True(lines.Any(l => l.StartsWith("# ATS|tier|wcid|name|shield|facing")), "and the tier row"); + Check.True(lines.Contains($"TS|{BossWcid}|{BossName}|1|front|2|11.5|13"), "shield front: 2 hits, mean 11.5, max 13"); + Check.True(lines.Contains($"TS|{BossWcid}|{BossName}|1|behind|1|274|274"), "shield behind"); + Check.True(lines.Contains($"TS|{BossWcid}|{BossName}|0|unknown|1|54|54"), "no shield, facing unknown"); + Check.True(lines.Contains($"ATS|3|{BossWcid}|{BossName}|0|front|1|90|90"), "a difficulty tier's row"); + int ts = Array.FindIndex(lines, l => l.StartsWith("TS|")); + Check.True(ts > Array.FindIndex(lines, l => l.StartsWith("T|")), "TS rows follow the T rows"); + + var again = new MonsterDamageStore(); + again.SetCharacter(folder); + var rows = again.GetShieldTaken(BossWcid, 0); + Check.Eq(string.Join(";", rows.Select(r => $"{(r.Shield ? 1 : 0)}{ShieldFacing.Word(r.Facing)}{r.Hits}/{r.Avg}/{r.Max}")), + "1front2/11.5/13;1behind1/274/274;0unknown1/54/54", "loaded back the same, shield first, front before behind"); + Check.Eq(again.GetShieldTaken(BossWcid, 3).Single().Avg, 90.0, "the tier's row loaded"); + Check.Eq(again.GetDetail(BossWcid, 0).Taken.Single().Hits, 1, "the T row loaded beside them"); + again.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Front, 12.5); + Check.Eq(Math.Round(again.GetShieldTaken(BossWcid, 0)[0].Avg, 2), 11.83, "a loaded mean goes on being a mean ((10+13+12.5)/3)"); + + // An older file (no TS rows), with unknown row kinds a newer RynthAi might write: they load, the + // unknown kinds are skipped, and nothing breaks. + string old = Folder("old"); + File.WriteAllLines(Path.Combine(old, "monster_damage.txt"), new[] + { + "# RynthAi per-character monster damage learning (auto-generated).", + $"H|{BossWcid}|{BossName}|5000|2", + $"T|{BossWcid}|{BossName}|Slash|7|55|274", + $"TX|{BossWcid}|{BossName}|future|1|2|3|4", + $"TS|{BossWcid}|{BossName}|2|front|1|2|3", + $"TS|{BossWcid}|{BossName}|1|sideways|1|2|3", + $"TS|{BossWcid}|{BossName}|1|front|zero|2|3", + $"TS|{BossWcid}|{BossName}|1", + $"AZZ|2|{BossWcid}|{BossName}|1|2", + $"D|{BossWcid}|{BossName}|0|Fire|7|120|20|3.5|4|200|4|100|16", + }); + var o = new MonsterDamageStore(); + o.SetCharacter(old); + Check.Eq(o.GetLearnedHp(BossWcid), 5000.0, "the H row loads"); + Check.Eq(o.GetDetail(BossWcid, 0).Taken.Single().Max, 274.0, "the T row loads"); + Check.Eq(o.Snapshot().Count, 1, "the D row loads"); + Check.Eq(o.GetShieldTaken(BossWcid, 0).Count, 0, "unknown kinds and bad TS rows are skipped"); + + // What an older RynthAi does with a TS row: its loader compares the kind exactly (H, M, W, O, + // P, U, PK, T, D, DEF, and A* tier rows), so "TS" matches none and is skipped; this loader + // does the same with a kind it doesn't know (TX above). + Check.True(lines.All(l => !l.StartsWith("TS") || l.StartsWith("TS|")), "TS is its own kind, never a T row"); + } + + private static void SummaryLine() + { + var rig = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f)); + for (int i = 0; i < 5; i++) rig.Hit(10 + i); + FakeHost.Positions[Boss] = (0xA9B40001, 50f, 48f, 0f); + rig.Hit(274); + Check.False(FakeHost.Logs.Any(l => l.StartsWith("[Taken]")), "no line per hit"); + List lines = rig.C.TakenSummaryLines(RynthClock.Now); + Check.Eq(lines.Count, 1, "one line for the one monster"); + string line = lines[0]; + Check.True(line.StartsWith($"[Taken] {BossName}: 6 hits in "), "who and how many: " + line); + Check.True(line.Contains("shield front 5 avg 12 max 14"), "the front cell: " + line); + Check.True(line.Contains("shield behind 1 avg 274 max 274"), "the behind cell: " + line); + Check.Eq(rig.C.TakenSummaryLines(RynthClock.Now).Count, 0, "the tally starts over"); + } + + // ── The Damage panel row ───────────────────────────────────────────────── + + private static void DamageRowJson() + { + FakeHost.Reset(); + FakeHost.PlayerPose = (0xA9B40001, 10f, 10f, 0f); + var host = FakeHost.Create(Player); + var p = new RynthAiPlugin(); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi }); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(p, v); + Set("_objectCache", cache); + Set("_playerId", Player); + var store = new MonsterDamageStore(); + store.SetCharacter(Folder("row")); + Set("_damageStore", store); + Set("_creatureStore", new CreatureProfileStore()); + + store.RecordKill(0, BossWcid, BossName, "Fire", 7, 3, 5000); + for (int i = 0; i < 19; i++) store.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Front, 11); + store.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Behind, 274); + store.RecordTakenSplit(BossWcid, BossName, false, HitFacing.Front, 54); + store.RecordTakenSplit(BossWcid, BossName, false, HitFacing.Front, 55); + + using var doc = JsonDocument.Parse(p.BuildMonsterDamageJson()); + JsonElement row = doc.RootElement.EnumerateArray().Single(e => e.GetProperty("name").GetString() == BossName); + Check.True(row.TryGetProperty("mstats", out JsonElement m), "mstats is sent with only learned numbers (none since login)"); + Check.Eq(m.GetProperty("hsf").GetInt32(), 19, "shield front hits"); + Check.Eq(m.GetProperty("dsf").GetInt64(), 209L, "shield front total damage (19 x 11)"); + Check.Eq(m.GetProperty("msf").GetInt64(), 11L, "shield front biggest"); + Check.Eq(m.GetProperty("hsb").GetInt32(), 1, "shield behind hits"); + Check.Eq(m.GetProperty("msb").GetInt64(), 274L, "shield behind biggest"); + Check.Eq(m.GetProperty("hnf").GetInt32(), 2, "no shield front hits"); + Check.Eq(m.GetProperty("dnf").GetInt64(), 109L, "no shield front total"); + Check.False(m.TryGetProperty("hsu", out _), "an empty cell isn't sent"); + Check.False(m.TryGetProperty("sw", out _), "no session numbers: none sent"); + + // With session numbers too: both, one object. + string both = RynthAiPlugin.MonsterStatsJson(null, p.ShieldTakenFor(new[] { BossWcid }, 0)); + Check.True(both.StartsWith("\"mstats\":{\"hsf\":19,\"dsf\":209,\"msf\":11"), "the split alone: " + both); + Check.Eq(p.MonsterStatsJsonFor("Nobody", new uint[] { 12345 }, 0), "", "a monster with nothing: no mstats"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs index 80720d5..631ae30 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs @@ -375,31 +375,55 @@ internal static class StuckCastTests private static void ProbeWhenNothingOpen() { + // A start that is no heal: a waiting heal's probe is capped at ActionPacer.HealGraceMs (below). + bool Start(RynthCoreHost h) => MayAs(h, "Buff", HealNeed.None); var host = Setup(); try { - Check.True(May(host), "free"); + Check.True(Start(host), "free"); Cast(host, "Heart Rend"); _t += 100; FakeHost.UseDone(ActionPacer.TooBusyErr); // refused: the server is busy with something of no UseDone (a pickup) - Check.False(May(host), "held right after the 0x1D"); + Check.False(Start(host), "held right after the 0x1D"); _t += ActionPacer.BusyProbeMs - 1; - Check.False(May(host), "held until BusyProbeMs"); + Check.False(Start(host), "held until BusyProbeMs"); _t += 1; - Check.True(May(host), "one probe at BusyProbeMs"); - Check.False(May(host), "only one"); + Check.True(Start(host), "one probe at BusyProbeMs"); + Check.False(Start(host), "only one"); Cast(host, "Heart Rend"); _t += 100; FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again _t += ActionPacer.BusyProbeMs * 2 - 101; - Check.False(May(host), "the next probe waits twice as long"); + Check.False(Start(host), "the next probe waits twice as long"); _t += 1; - Check.True(May(host), "second probe at 2 x BusyProbeMs"); + Check.True(Start(host), "second probe at 2 x BusyProbeMs"); Check.Eq(FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "no breaker: no cast of ours was left open"); Cast(host, "Heart Rend"); _t += 900; FakeHost.UseDone(0); - Check.True(May(host), "a UseDone(0) clears it"); + Check.True(Start(host), "a UseDone(0) clears it"); + } + finally { Done(); } + + // The heal grace: a plain heal's probe comes at least every HealGraceMs, where the doubling would make it 3 s. + var heal = Setup(); + try + { + Check.True(May(heal), "free"); + Cast(heal, "Heart Rend"); + _t += 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); + Check.False(May(heal), "held right after the 0x1D"); + _t += ActionPacer.BusyProbeMs; + Check.True(May(heal), "the heal's first probe at BusyProbeMs"); + Cast(heal, "Heart Rend"); + _t += 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again + Check.False(May(heal), "held right after the second 0x1D"); + _t += ActionPacer.HealGraceMs - 101; + Check.False(May(heal), "1 ms under the heal grace: held"); + _t += 1; + Check.True(May(heal), "the heal's second probe at HealGraceMs, not 2 x BusyProbeMs"); } finally { Done(); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs index eae9795..4ae511e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs @@ -12,8 +12,9 @@ namespace RynthCore.RynthAiHostTests.Tests; // Combat target selection (2026-10-10): the Targeting setting (lowest health, closest, farthest, // least turning) and Target Lock. Combat used to switch targets mid-fight on a blended score; now -// a locked target is kept until it dies or goes, leaves Monster Range, or a higher-priority -// monster is in range, and with the lock off a switch needs a clear margin under the rule. +// a locked target is kept until it dies or goes or leaves Monster Range (a higher priority too, +// since 2026-11-07), and with the lock off a higher priority in range takes over at once and any +// other switch needs a clear margin under the rule. internal static class TargetingTests { private const uint Player = 0x50000E01; @@ -22,14 +23,48 @@ internal static class TargetingTests private const int LowestHealth = 0, Closest = 1, Farthest = 2, LeastTurning = 3; + // Melee reaches through walls (2026-11-06): within 4 yd the raycast doesn't hide a monster from melee. + private static void MeleeThroughWalls() + { + var near = new ScanPick(20); + near.Place(A, "Mob A", north: 3); + near.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(near.Tick(), A, "melee, 3 yd, a wall between: still the target"); + + var far = new ScanPick(20); + far.Place(A, "Mob A", north: 6); + far.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(far.Tick(), 0u, "melee, 6 yd, a wall between: the raycast still counts"); + + var magic = new ScanPick(20); + magic.Place(A, "Mob A", north: 3); + magic.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + Check.Eq(magic.Tick(), 0u, "magic, 3 yd, a wall between: spells don't go through"); + + var missile = new ScanPick(20); + missile.Place(A, "Mob A", north: 3); + missile.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Missile; + Check.Eq(missile.Tick(), 0u, "missile, 3 yd, a wall between: nor do arrows"); + } + public static void Register(Runner r) { + r.Add("targeting: melee within 4 yd ignores the raycast; beyond it, or with magic or missile, it counts", MeleeThroughWalls); r.Add("targeting: each scheme picks its monster", SchemesPick); r.Add("targeting: unknown health counts as full; ties go to the closest, then the lower id", UnknownHealthAndTies); r.Add("targeting: Target Lock keeps the target when a better one of its tier appears", LockKeeps); r.Add("targeting: Target Lock lets go when the target goes (after the scan grace)", LockReleasesWhenGone); r.Add("targeting: Target Lock lets go when the target leaves Monster Range", LockReleasesOutOfRange); - r.Add("targeting: a higher-priority monster in range takes over, lock or not", HigherPriorityWins); + r.Add("targeting: lock off, a higher-priority monster in range takes over", HigherPriorityWins); + r.Add("targeting: Target Lock holds over a higher priority until the target dies or leaves Monster Range", LockHoldsOverPriority); r.Add("targeting: lock off switches only past each scheme's margin", LockOffMargins); r.Add("targeting: lock off never switches with an attack at the target in flight", NoSwitchInFlight); r.Add("targeting: settings default to lowest health with the lock on", Defaults); @@ -39,6 +74,132 @@ internal static class TargetingTests r.Add("targeting: lock off keeps a target that blinks out of the scan (no switch on stale values)", LockOffNoSwitchOnStale); r.Add("targeting: lock off holds right after a cast goes out, before it is judged", LockOffHoldsJustSentCast); r.Add("targeting: a higher priority just past Monster Range is logged once while fighting, and /ra why names it", BeyondRangeWhileEngaged); + r.Add("targeting: lowest health ranks unread monsters by the engine plates' readings", PlatesRankUnread); + r.Add("targeting: plate readings older than 10 s, or 0, are ignored", PlatesStaleIgnored); + r.Add("targeting: a plate reading beats an estimate when lower, and an older own server value when clearly fresher", PlatesVersusOwn); + r.Add("targeting: plate readings rank only; health, fight and kill tracking are untouched", PlatesRankOnly); + r.Add("targeting: without the engine call (or on an older engine) lowest health is as before", PlatesNoCapability); + } + + // ── The engine plates' health (API v93 GetMonsterHealth, 2026-11-07) ───── + + private static void PlatesRankUnread() + { + // The server streams health only for the queried target: RynthAi knows none of these three. + var plates = new Dictionary { [A] = (0.9f, 1000), [B] = (0.25f, 3000), [C] = (0.6f, 500) }; + var t = new Rig(LowestHealth, true, plates: plates); + Check.True(t.Host.HasMonsterHealth, "the fake engine has the call"); + Check.Eq(t.Pick((A, 2, 0), (B, 5, 0), (C, 3, 0)), B, "B, 25% on the plates, is the most hurt (the closest is A)"); + Check.True(FakeHost.PlateHealthQueries > 0, "the plates were asked"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x80000402") && l.Contains("lowest health: health 25% (the plates' reading)")), + "the lock line gives the plates' number and says where it came from"); + + // A known own value still competes: A at 20% (the streamed target) beats B's 25% on the plates. + t = new Rig(LowestHealth, true, new Dictionary { [A] = 0.2f }, plates: new() { [B] = (0.25f, 3000) }); + Check.Eq(t.Pick((A, 4, 0), (B, 2, 0)), A, "own 20% beats the plates' 25%"); + + // Lock off: a plate reading clearly lower takes over, by the scheme's margin. + t = new Rig(LowestHealth, false, new Dictionary { [A] = 0.5f }, plates: new() { [B] = (0.9f, 1000) }); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "lock off: A at 50%, B at 90% on the plates"); + t.Plate(B, 0.47f, 1000); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B at 47% on the plates (3 points lower): A kept"); + t.Plate(B, 0.30f, 1000); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "B at 30% on the plates (20 points lower): switch"); + } + + private static void PlatesStaleIgnored() + { + var t = new Rig(LowestHealth, true, plates: new() { [A] = (0.9f, 1000), [B] = (0.1f, 10_500) }); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B's 10% is 10.5 s old: ignored (full), A's 90% wins"); + + t = new Rig(LowestHealth, true, plates: new() { [A] = (0.9f, 1000), [B] = (0.1f, 10_000) }); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "exactly 10 s old: still used"); + + t = new Rig(LowestHealth, true, new Dictionary { [B] = 0.95f }, plates: new() { [A] = (0f, 500) }); + Check.Eq(t.Pick((A, 1, 0), (B, 3, 0)), B, "a plate 0 (dead to the plates, not to RynthAi) isn't the most hurt: B at 95%"); + + t = new Rig(LowestHealth, true, plates: new() { [A] = (0.9f, uint.MaxValue) }); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "a reading of unknown age is stale: all full, the closest"); + } + + private static void PlatesVersusOwn() + { + // Own estimate (our splash hit) vs the plates: the lower of the two. + var t = new Rig(LowestHealth, true, new Dictionary { [B] = 0.5f }, plates: new() { [A] = (0.4f, 2000) }); + t.Cache.ApplyDamageEstimate(unchecked((int)A), 0.3); // A estimated 70% + Check.True(t.Cache.IsHealthEstimated(unchecked((int)A)), "A's own value is an estimate"); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "A: estimate 70%, plates 40% -> 40%, below B's 50%"); + + t = new Rig(LowestHealth, true, new Dictionary { [B] = 0.5f }, plates: new() { [A] = (0.8f, 2000) }); + t.Cache.ApplyDamageEstimate(unchecked((int)A), 0.7); // A estimated 30% + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "A: estimate 30%, plates 80% -> 30% (the estimate saw hits the plates didn't)"); + + // Own server value 80%, 5 s old; the plates read 30% a second ago: the plates are fresher. + t = new Rig(LowestHealth, true, new Dictionary { [A] = 0.5f }, plates: new() { [B] = (0.3f, 1000) }); + t.Health(B, 0.8f); + t.Advance(5000); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "B: own 80% (5 s old) vs plates 30% (1 s old) -> 30%"); + + // Own server value just in; the plates' is older: own stands. + t = new Rig(LowestHealth, true, new Dictionary { [A] = 0.5f }, plates: new() { [B] = (0.3f, 1000) }); + t.Health(B, 0.8f); + t.Advance(200); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B: own 80% (0.2 s old) stands over the plates' 30% (1 s old): A at 50%"); + + // A few ms apart is the same 0x01C0: not "fresher". + t = new Rig(LowestHealth, true, new Dictionary { [A] = 0.5f }, plates: new() { [B] = (0.3f, 1000) }); + t.Health(B, 0.8f); + t.Advance(1300); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "plates only 0.3 s fresher: own 80% stands"); + + // The server said dead: that stands whatever the plates say. + // (A dead monster never reaches the pick: the scan drops it. The rank itself is checked here.) + t = new Rig(LowestHealth, true, new Dictionary { [B] = 0f }, plates: new() { [B] = (0.4f, 100) }); + Check.True(t.Combat.RankingHealth(unchecked((int)B), out bool fromPlates) == 0f && !fromPlates, "own 0 (dead) isn't revived by the plates"); + } + + private static void PlatesRankOnly() + { + var t = new Rig(LowestHealth, true, plates: new() { [A] = (0.9f, 1000), [B] = (0.2f, 1000) }); + Check.Eq(t.Pick((A, 2, 0), (B, 4, 0)), B, "B is picked on the plates' 20%"); + int a = unchecked((int)A), b = unchecked((int)B); + Check.Eq(t.Cache.GetHealthRatio(b), -1f, "the cache still doesn't know B's health"); + Check.Eq(t.Cache.GetHealthRatio(a), -1f, "nor A's"); + Check.False(t.Cache.IsHealthEstimated(b), "nothing was written as an estimate"); + Check.False(t.Cache.TryGetServerHealthTime(b, out _), "nor as a server reading"); + Check.Eq(t.Combat.FightTargetHealthRatio, -1f, "the fight target's health (metas, kill checks) is RynthAi's own: unknown"); + + // The kill path is the same as without the plates: the notice drops B, the next pick is fresh. + t.Combat.OnKillNotification("Mob B's perforated corpse falls before you!"); + Check.Eq(t.Combat.activeTargetId, 0, "the kill notice drops B"); + Check.Eq(t.Cache.GetHealthRatio(b), -1f, "and still nothing in the cache from the plates"); + t.Plate(B, 0.2f, 1000); // the plates still remember B's last reading + Check.Eq(t.Pick((A, 2, 0)), A, "A is next"); + + // The server's own stream still drives the cache exactly as before. + t.Health(A, 0.6f); + Check.Eq(t.Cache.GetHealthRatio(a), 0.6f, "a real UpdateHealth lands in the cache"); + Check.Eq(t.Combat.FightTargetHealthRatio, 0.6f, "and is the fight target's health"); + } + + private static void PlatesNoCapability() + { + // No call on the engine: the plates' numbers can't be read, all unknown counts as full. + var t = new Rig(LowestHealth, true); + FakeHost.PlateHealth[B] = (0.1f, 500); // what an engine would have said (not wired) + Check.False(t.Host.HasMonsterHealth, "no GetMonsterHealth on this engine"); + Check.Eq(t.Pick((A, 2, 0), (B, 4, 0)), A, "all unknown: the closest, as before"); + Check.True(FakeHost.Logs.Any(l => l.Contains("lowest health: health unknown (as full)")), "logged as unknown, as before"); + + // The slot filled but the engine says API 92: not used, never called. + t = new Rig(LowestHealth, true, plates: new() { [B] = (0.1f, 500) }, plateVersion: 92); + Check.False(t.Host.HasMonsterHealth, "API 92: no HasMonsterHealth"); + Check.Eq(t.Pick((A, 2, 0), (B, 4, 0)), A, "the closest, as before"); + Check.Eq(FakeHost.PlateHealthQueries, 0, "the call was never made"); + + // With the call, but the plates know nothing: as before too. + t = new Rig(LowestHealth, true, new Dictionary { [B] = 0.95f }, plates: new()); + Check.Eq(t.Pick((A, 2, 0), (B, 5, 0)), B, "a known 95% beats an unknown (full) health, as before"); } // ── Schemes ─────────────────────────────────────────────────────────────── @@ -130,9 +291,31 @@ internal static class TargetingTests Check.Eq(t.Pick((A, 3, 0), (B, 4.8, 0)), B, "A coming back closer doesn't take it back (B is locked now)"); } + // Target Lock holds until the target dies or leaves Monster Range, a higher priority or not + // (the owner, 2026-11-07); with the lock off a higher priority in range takes over at once. + private static void LockHoldsOverPriority() + { + var t = new Rig(Closest, true, monsterRange: 10); + t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 2 }); + Check.Eq(t.Pick((A, 2, 0), (B, 3, 0)), A, "A is locked"); + Check.Eq(t.Pick((A, 2, 0), (B, 3, 0), (Boss, 9, 0)), A, "a Boss inside Monster Range: the lock keeps A"); + Check.True(FakeHost.Logs.Count(l => l.Contains("[CombatTarget] Target Lock keeps 0x80000401") && l.Contains("over 0x80000404")) == 1, + "the hold is logged once"); + t.Pick((A, 2, 0), (Boss, 9, 0)); + Check.True(FakeHost.Logs.Count(l => l.Contains("[CombatTarget] Target Lock keeps")) == 1, "and not again"); + Check.Eq(t.Pick((A, 11, 0), (Boss, 9, 0)), Boss, "A leaves Monster Range: the Boss"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("out of Monster Range")), + "the switch says why: out of Monster Range"); + + t = new Rig(Closest, true, monsterRange: 10); + t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 2 }); + t.Pick((A, 2, 0), (Boss, 9, 0)); + Check.Eq(t.Combat.activeTargetId, unchecked((int)Boss), "nothing locked yet: the higher priority is picked first"); + } + private static void HigherPriorityWins() { - foreach (bool lockOn in new[] { true, false }) + foreach (bool lockOn in new[] { false }) { string mode = lockOn ? "lock on" : "lock off"; var t = new Rig(Closest, lockOn, monsterRange: 10); @@ -275,6 +458,7 @@ internal static class TargetingTests FakeHost.NotAttackable.Remove(Boss); t.Blocked.Remove(Boss); + t.S.TargetLock = false; // with the lock on, Mob A would be kept (LockHoldsOverPriority) Check.Eq(t.Tick(), Boss, "in sight and attackable: the Boss takes over at once"); string sw = FakeHost.Logs.Last(l => l.Contains("[CombatTarget] switch")); Check.True(sw.Contains("priority 1 < 5") && !sw.Contains("passed over"), "the switch says priority, with nothing passed over"); @@ -371,7 +555,8 @@ internal static class TargetingTests Check.True(why != null && why.Contains("'Boss' priority 5") && why.Contains("beyond Monster Range (10 m)"), $"/ra why names it ({why})"); t.Place(Boss, "Boss", north: -9); - Check.Eq(t.Tick(), Boss, "inside Monster Range: the Boss takes over at once"); + t.S.TargetLock = false; // with the lock on, Mob A would be kept (LockHoldsOverPriority) + Check.Eq(t.Tick(), Boss, "inside Monster Range, lock off: the Boss takes over at once"); } private static int PassedLines() => FakeHost.Logs.Count(l => l.Contains("[CombatTarget] passed over")); @@ -431,9 +616,18 @@ internal static class TargetingTests private readonly WorldObjectCache _cache; private DateTime _now = RynthClock.Now; // the clock RynthAi times with - public Rig(int scheme, bool targetLock, Dictionary? health = null, int monsterRange = 20) + /// The engine plates' readings (API v93 GetMonsterHealth: id -> ratio, age ms); + /// null = an engine without the call. non-zero: the table's Version. + public Rig(int scheme, bool targetLock, Dictionary? health = null, int monsterRange = 20, + Dictionary? plates = null, uint plateVersion = 0) { FakeHost.Reset(); + if (plates != null) + { + FakeHost.PlateHealthCalls = true; + FakeHost.PlateHealthVersion = plateVersion; + foreach (var kv in plates) FakeHost.PlateHealth[kv.Key] = kv.Value; + } Place(Player, "Me", 96, 96, creature: false); FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); Place(A, "Mob A", 96, 98); @@ -442,14 +636,20 @@ internal static class TargetingTests Place(Boss, "Boss", 96, 101); S = new LegacyUiSettings { MonsterRange = monsterRange, TargetSelection = scheme, TargetLock = targetLock }; var host = FakeHost.Create(); + Host = host; _cache = FakeHost.MakeCache(host, Player, new[] { A, B, C, Boss }, health); + _cache.Clock = () => _now; // health from here on is stamped on the rig's clock Combat = new CombatManager(host, S, _cache); Combat.SetPlayerId(Player); Combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore()); Combat.TargetClock = () => _now; } + public readonly RynthCore.PluginSdk.RynthCoreHost Host; + public WorldObjectCache Cache => _cache; public void Health(uint id, float ratio) => _cache.OnUpdateHealth(id, ratio); + /// The engine plates now read at , old. + public void Plate(uint id, float ratio, uint ageMs) => FakeHost.PlateHealth[id] = (ratio, ageMs); public void Advance(double ms) => _now = _now.AddMilliseconds(ms); /// One tick: the scan holds these (id, distance m, facing angle deg); returns the target. diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs index 1e687dd..50c7242 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs @@ -43,6 +43,7 @@ internal static class UseRefusalTests r.Add("use check: the next open settles an answered one that opened nothing; an open resets", WatchSettlesOnNextOpen); r.Add("use check (looting): Drakkon's stall - stop once, retry, say it once in chat, stop opening corpses, probe, recover", LootingStall); r.Add("use check (looting): normal opens never trip it", LootingNormalOpens); + r.Add("use check (looting): opens with monsters about never trip it (a fight cancels them)", OpensInAFightDontCount); r.Add("flight recorder: the use check asks the engine for a dump (clean stop, stuck); normal opens never do", FlightDumpRequests); r.Add("corpse open: a corpse claimed while Combat owns the tick is opened only on the Looting tick", OpenWaitsForLootingTick); r.Add("move hold: while a corpse use is in flight RynthAi's moves and turns wait, stops go through, UseDone or 1.5 s releases", MoveHoldWhileUseInFlight); @@ -256,6 +257,34 @@ internal static class UseRefusalTests private static int ChatCount(string text) => FakeHost.Chat.Count(c => c.Contains(text)); + // 2026-11-06, a wave fight: combat's swings cancelled the walk to the corpse, each open came back + // answered with nothing opened, and four of them paused looting 5 minutes with "a relog fixes it". + private static void OpensInAFightDontCount() + { + World(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + var combat = new CombatManager(host, bot.S, bot.Cache); + combat.SetPlayerId(Player); + combat.SetScannedTargetsForTests(new[] { new CombatManager.ScannedTarget { Id = 0x7000, Distance = 3, Angle = 0, Bearing = double.NaN, Name = "Mob" } }); + bot.Set("_combatManager", combat); + WithClock((now, advance) => + { + long answerAt = 0; + for (int i = 0; i < 600; i++) + { + int uses = FakeHost.Uses.Count; + bot.Tick(BotActivity.Looting); + if (FakeHost.Uses.Count > uses) answerAt = now() + 60; + advance(100); + if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; } + } + Check.True(FakeHost.Uses.Count > 0, "opens went out"); + Check.Eq(ChatCount(StuckLine), 0, "no 'a relog fixes it'"); + Check.False(FakeHost.Logs.Any(l => l.Contains("Use check:")), "the use check never acts on them"); + }); + } + private static void LootingStall() { World(); @@ -289,7 +318,7 @@ internal static class UseRefusalTests int usesAtStuck = FakeHost.Uses.Count; Check.False((bool)bot.Call("HasLootWork", bot.S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!, "no loot work during the back-off: nav and combat run on"); - for (int i = 0; i < 2400; i++) Step(); // 4 minutes + for (int i = 0; i < 200; i++) Step(); // 20 s of the 30 s back-off Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no corpse is opened during the back-off"); Check.Eq(ChatCount(StuckLine), 1, "and nothing more is said"); @@ -639,7 +668,7 @@ internal static class UseRefusalTests var w = bot.Get("_useRefusals"); int usesAtStuck = FakeHost.Uses.Count; - for (int i = 0; i < 2400; i++) { bot.Tick(BotActivity.Looting); advance(100); } // 4 minutes + for (int i = 0; i < 200; i++) { bot.Tick(BotActivity.Looting); advance(100); } // 20 s of the 30 s back-off Check.Eq(FakeHost.TapJumps, 1, "no jump during the back-off"); Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no opens during the back-off"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VendorFlagTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VendorFlagTests.cs new file mode 100644 index 0000000..77b484d --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VendorFlagTests.cs @@ -0,0 +1,118 @@ +using System; +using System.Linq; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Vendor; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +/// +/// /ub vendor open finds a vendor by the server's vendor flag (PublicWeenieDesc BF_VENDOR 0x200). +/// The world cache never files anything as AcObjectClass.Vendor: a retail-style shopkeeper is a +/// creature (an Npc there), and a summoned storage NPC can reach the cache as a typed item. By +/// name, partial name or id the flagged object opens; without the flag it is not a vendor. +/// +internal static class VendorFlagTests +{ + private const uint Player = 0x50000E01; + private const uint Here = 0xA9B4001C; + private const uint Shopkeeper = 0x80310003; // a creature with the vendor flag (retail and stock ACE) + private const uint Keeper = 0x80310001; // a typed item with the vendor flag (a server's own NPC) + private const uint Plain = 0x80310002; // a typed item without it + private const uint Bystander = 0x80310004; // a creature (an Npc) without it + private const uint BfVendor = 0x200; + private const uint TGem = 0x800, TCreature = 0x10; + private const string Attempt = "AutoVendor: attempting to open vendor"; + + public static void Register(Runner r) + { + r.Add("vendor open: a shopkeeper NPC with the vendor bitfield is found by name (retail-style)", RetailShopkeeper); + r.Add("vendor open: a cache non-Vendor with the vendor bitfield is found by name", FoundByName); + r.Add("vendor open: a cache non-Vendor with the vendor bitfield is found by id", FoundById); + r.Add("vendor open: objects without the vendor bitfield are not vendors (by name and by id)", NotFlagged); + r.Add("vendor open: a partial name finds the flagged object", FoundByPartial); + } + + private static AutoVendorManager Rig() + { + FakeHost.Reset(); + FakeHost.Names[Player] = "Vendor Tester"; + FakeHost.Positions[Player] = (Here, 96f, 96f, 0f); + FakeHost.PlayerPose = (Here, 96f, 96f, 0f); + FakeHost.Containers[Player] = 0; + foreach (var (id, name, type) in new[] + { + (Keeper, "Vault Keeper", TGem), (Plain, "Plain Gem", TGem), + (Shopkeeper, "Shopkeeper Alfrid", TCreature), (Bystander, "Town Crier", TCreature), + }) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Here, 97f, 97f, 0f); + FakeHost.ItemTypes[id] = type; + FakeHost.Containers[id] = 0; + FakeHost.NotAttackable.Add(id); + } + FakeHost.Bitfields[Keeper] = BfVendor; + FakeHost.Bitfields[Shopkeeper] = BfVendor; + FakeHost.Bitfields[Bystander] = 0; + + var host = FakeHost.Create(Player); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + foreach (uint id in new[] { Keeper, Plain, Shopkeeper, Bystander }) cache.OnCreateObject(id); + for (int i = 0; i < 12; i++) cache.Tick(); + // Precondition: the cache really does file all of them as something other than Vendor. + foreach (uint id in new[] { Keeper, Plain, Shopkeeper, Bystander }) + Check.True(cache.AllKnownObjects().Any(w => w.Id == unchecked((int)id) && w.ObjectClass != AcObjectClass.Vendor), + $"precondition: 0x{id:X8} cached as a non-Vendor"); + return new AutoVendorManager(host, new LegacyUiSettings(), cache, Player, () => string.Empty); + } + + private static bool Attempted() => FakeHost.Logs.Any(l => l.Contains(Attempt, StringComparison.Ordinal)); + + // The open attempt names the chosen object: "...attempting to open vendor ". + private static bool Opened(string name) => FakeHost.Logs.Any(l => l.EndsWith(Attempt + " " + name, StringComparison.Ordinal)); + + private static void RetailShopkeeper() + { + var m = Rig(); + m.CommandOpen("Shopkeeper Alfrid", false); + Check.True(Opened("Shopkeeper Alfrid"), "the flagged shopkeeper is the one opened by name"); + } + + private static void FoundByName() + { + var m = Rig(); + m.CommandOpen("Vault Keeper", false); + Check.True(Opened("Vault Keeper"), "the flagged object is the one opened by name"); + } + + private static void FoundById() + { + var m = Rig(); + m.CommandOpen("0x" + Keeper.ToString("X8"), false); + Check.True(Opened("Vault Keeper"), "the flagged object is the one opened by hex id"); + } + + private static void NotFlagged() + { + var m = Rig(); + m.CommandOpen("Plain Gem", false); + Check.False(Attempted(), "an unflagged item is not opened by name"); + m.CommandOpen("0x" + Plain.ToString("X8"), false); + Check.False(Attempted(), "an unflagged item is not opened by id"); + m.CommandOpen("Town Crier", false); + Check.False(Attempted(), "an unflagged NPC is not opened by name"); + } + + private static void FoundByPartial() + { + var m = Rig(); + m.CommandOpen("keeper", true); + Check.True(Opened("Vault Keeper") || Opened("Shopkeeper Alfrid"), "a partial name opens a flagged object"); + Check.False(Opened("Plain Gem") || Opened("Town Crier"), "never an unflagged one"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs new file mode 100644 index 0000000..ac045f0 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs @@ -0,0 +1,543 @@ +using System; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Kits are the standard heal, and the shield stays on. +// A vital spell out of Magic mode with no caster in hand starts no weapon swap while a kit or potion +// for that vital is carried (BuffManager.VitalSpellWouldSwap); buffing still swaps. +internal static class VitalWandGateTests +{ + private const uint Player = 0x500000B7; + private const uint Wand = 0x80071001; + private const uint Kit = 0x80071002; + private const uint StamKit = 0x80071003; + private const uint ManaPot = 0x80071004; + private const uint HealPot = 0x80071005; + private const uint CurrentWieldedLocation = 10; // STypeInt CurrentWieldedLocation + private const uint HeldSlot = 0x01000000; + + public static void Register(Runner r) + { + r.Add("vital wand gate: out of Magic with a healing kit carried, Heal Self starts no wand swap (not handled)", HealRefusedWithKit); + r.Add("vital wand gate: the refused Heal Self falls through to the kit despite Kit Min Success", KitDespiteMinSuccessAfterRefusal); + r.Add("vital wand gate: a caster already wielded in melee stance: the Magic stance change only, no weapon move", StanceOnlyWithCasterWielded); + r.Add("vital wand gate: no kit and no potion at all: the swap is allowed (the only heal there is)", SwapAllowedWithNothingElse); + r.Add("vital wand gate: Revitalize with a stamina kit, Stamina to Mana in a fight, the script heal with a health potion: no swap", OtherVitalsRefused); + r.Add("vital wand gate: a pure caster in Magic mode with a kit carried still casts Heal Self", PureCasterUnaffected); + r.Add("vital wand gate: buffing still swaps to the wand with a kit carried", BuffsStillSwap); + r.Add("vital wand gate: Revitalize refused, no stamina potion: the stamina kit is used despite Kit Min Success", StaminaKitDespiteMinSuccess); + r.Add("vital wand gate: Stamina to Mana never swaps in a fight; out of one with no mana potion it may", ManaInFightNoSwap); + r.Add("vital wand gate: in Magic stance with no wand in hand and a kit carried, Heal Self is not gated", MagicNoWandNotGated); + r.Add("vital wand gate: a kit its line called used up, or gone from the client's pack, is no kit: Heal Self is handled and the swap is allowed", GoneKitAllowsSwap); + r.Add("vital wand gate: a swap already under way finishes when a kit reappears (no abandoned swap, no kit mid-wield)", SwapInFlightFinishes); + r.Add("vital wand gate: a kit the server refused 3 times within 10 s is no kit for the gate; a kit landing counts it again", RefusedKitAllowsSwap); + r.Add("vital wand gate: the mana step's stamina refill also uses the stamina kit despite Kit Min Success", ManaRefillStaminaLastResort); + r.Add("vital wand gate: out of a fight Stamina to Mana may swap with a mana potion carried; in a fight it may not", ManaPotionOutOfFightSwaps); + r.Add("vital wand gate: a refusal streak ages out: 11 s after the last refusal the kit counts again", RefusedStreakAgesOut); + r.Add("vital wand gate: no wand found: Heal Self takes the bare-handed Magic stance, not gated", NoWandNotGated); + r.Add("vital wand gate: one line when it starts refusing, one when the swap may go again or nothing asks for 5 s, one for a refused kit", GateLogLines); + r.Add("vital wand gate: under Emergency Heal At the kit despite Kit Min Success still goes; the HP failsafe's recall still swaps to the wand", EmergencyFloorKept); + r.Add("vital wand gate: the between-fights top-off (no Revitalize) uses a stamina kit under Stamina Kit Min Success as the last resort", TopOffStaminaLastResort); + r.Add("vital wand gate: at or under Emergency Heal At a health spell may swap to the wand with a kit carried (the surest heal goes)", EmergencySpellMaySwap); + r.Add("buffs wait: under Heal At in a fight no buff is cast and the arbiter isn't asked for buffs; over it or out of a fight they go on", BuffsWaitWhileHurt); + } + + // 2026-11-07: at 9% the gate sent Drakkon's kit (5-8% at low health with vitae) instead of Stamina to Health, and he died. + private static void EmergencySpellMaySwap() + { + var b = Rig(CombatMode.Melee, new[] { Kit }); + S.EmergencyHealAt = 30; + SetVitals(b, 9, 74, 100); + Check.True(VitalCast(b, "Stamina to Health Self"), "9% health, kit carried: Stamina to Health is handled: " + Why(b)); + Check.True(SwapActive(b), "its wand swap is under way"); + + var a = Rig(CombatMode.Melee, new[] { Kit }); + S.EmergencyHealAt = 30; + SetVitals(a, 45, 74, 100); + Check.False(VitalCast(a, "Heal Self"), "45%, over Emergency Heal At: the gate still refuses Heal Self"); + Check.True(Why(a).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "with its reason: " + Why(a)); + } + + // 2026-11-07: four weapon auras in a row with a golem hitting him under Heal At; the emergency heal waited for the last cast. + private static void BuffsWaitWhileHurt() + { + var b = Rig(CombatMode.Melee, Array.Empty()); + S.HealAt = 60; + b.InCombatOverride = () => true; + SetVitals(b, 54, 100, 100); + Check.True(b.BuffsWaitForHealth(), "54% under Heal At 60% in a fight: buffs wait"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[Buff] buffs wait: health 54% is under Heal At 60% in a fight", StringComparison.Ordinal)), "logged once at the start"); + Check.True(b.BuffsWaitForHealth(), "still waiting"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] buffs wait:", StringComparison.Ordinal)), 1, "not logged again"); + SetVitals(b, 70, 100, 100); + Check.False(b.BuffsWaitForHealth(), "back over Heal At: buffs go on"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[Buff] buffs go on", StringComparison.Ordinal)), "the end is logged"); + SetVitals(b, 40, 100, 100); + b.InCombatOverride = () => false; + Check.False(b.BuffsWaitForHealth(), "out of a fight: buffs go on even under Heal At"); + } + + private static void GateLogLines() + { + var b = Rig(CombatMode.Melee, new[] { Kit }); + DateTime t0 = new DateTime(2026, 1, 1, 18, 0, 0); + DateTime now = t0; + b.Clock = () => now; + VitalCast(b, "Heal Self"); + VitalCast(b, "Heal Self"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[RynthAi] Vitals: wand gate: no wand swap for Heal Self - a kit is carried", StringComparison.Ordinal)), 1, + "the start is logged once: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("wand gate", StringComparison.Ordinal)))); + now = t0.AddSeconds(6); + b.OnHeartbeat(); + Check.True(FakeHost.Logs.Any(l => l.Contains("wand gate ended for Heal Self: not asked for in 5 s", StringComparison.Ordinal)), "5 s with no refusal: the end is logged"); + + // The swap allowed again (the kit gone) ends it at once. + var g = Rig(CombatMode.Melee, new[] { Kit }); + VitalCast(g, "Heal Self"); + Check.True((bool)typeof(BuffManager).GetMethod("AttemptHealthKitUse", Np, new[] { typeof(bool) })!.Invoke(g, new object[] { false })!, "the kit goes out"); + g.OnChatWindowText("You heal yourself for 12 Health points. Your Treated Healing Kit is used up.", 0); + Check.True(VitalCast(g, "Heal Self"), "the kit used up: Heal Self handled"); + Check.True(FakeHost.Logs.Any(l => l.Contains("wand gate ended for Heal Self: no healing kit or potion is carried; its wand swap may go", StringComparison.Ordinal)), + "the end is logged with why"); + + // A kit refused 3 times stops counting, logged. + var k = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true); + FakeHost.UseDoneSeq = 10; + RefuseKit(k, Kit); RefuseKit(k, Kit); RefuseKit(k, Kit); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("refused 3 times in 10 s: it no longer counts as a heal", StringComparison.Ordinal)), 1, "the streak is logged once"); + } + + // The safety floor: the gate only refuses spells in the vitals chain. The last-resort kit still goes + // at Emergency Heal At, and the HP failsafe's Lifestone Recall (EnsureMagicMode, macro off) still swaps. + private static void EmergencyFloorKept() + { + // 2026-11-07: under Emergency Heal At a kit under Kit Min Success no longer beats the heal spell's wand + // swap (Drakkon's kit was 5-8% at low health and he died at 9% with it). + var b = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 95); + S.EmergencyHealAt = 30; + SetVitals(b, 20, 100, 100); + Check.True(b.CheckVitals(), "20% under Emergency Heal At 30%: the vitals act"); + Check.Eq(FakeHost.UsesOn.Count, 0, "no kit under Kit Min Success"); + Check.True(SwapActive(b), "the heal spell's wand swap goes instead"); + + // A kit at Kit Min Success is still the heal at Emergency Heal At. + var k = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 0); + S.EmergencyHealAt = 30; + SetVitals(k, 20, 100, 100); + Check.True(k.CheckVitals(), "20%, a kit that passes Kit Min Success: the vitals act"); + Check.Eq(FakeHost.UsesOn.Count, 1, "the kit goes out"); + Check.Eq(FakeHost.Casts.Count, 0, "no spell"); + + var r = Rig(CombatMode.Melee, new[] { Kit, HealPot }, usePotions: true); + int before = SwapActivity(); + string wait = (string)typeof(BuffManager).GetMethod("RecallCastHolds", Np)!.Invoke(r, null)!; + Check.Eq(wait, "wand swap / Magic stance", "the recall waits for its wand swap"); + Check.True(SwapActivity() > before, "the recall's wand swap starts with a kit and a potion carried"); + } + + // b2e1ade4: between fights out of Magic no Revitalize is cast for Top Off Stamina; kits still top off, + // and with this port a stamina kit under Stamina Kit Min Success % is that last resort. + private static void TopOffStaminaLastResort() + { + var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 95); + b.InCombatOverride = () => false; + S.TopOffStam = 60; S.RestamAt = 10; + SetVitals(b, 100, 40, 100); + Check.True(b.CheckVitals(), "stamina 40% under Top Off Stamina 60%, no fight: acts"); + Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use"); + Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "the stamina kit"); + Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize"); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, "no Magic stance"); + } + + // Out of a fight buffing is about to swap to the wand anyway, so a + // mana potion drunk to spare the swap is a potion wasted. In a fight the refusal stands. + private static void ManaPotionOutOfFightSwaps() + { + var q = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true); + q.InCombatOverride = () => false; + Check.True(VitalCast(q, "Stamina to Mana Self"), "out of a fight, mana potion carried: handled: " + Why(q)); + Check.True(SwapActive(q), "the wand swap is under way"); + + var f = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true); + f.InCombatOverride = () => true; + Check.False(VitalCast(f, "Stamina to Mana Self"), "in a fight, mana potion carried: not handled"); + Check.True(Why(f).Contains("Stamina to Mana in a fight", StringComparison.Ordinal), "the in-fight reason: " + Why(f)); + Check.Eq(SwapActivity(), 0, "in a fight: no swap"); + } + + // The stamina last resort covers every stamina path: the stamina step, the mana step's refill + // (AttemptManaRefill) and the buffing mana floor. + private static void ManaRefillStaminaLastResort() + { + var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 95); + SetVitals(b, 100, 10, 10); // stamina 10% <= the Stamina to Mana floor (15): refill stamina first + object[] args = { 10, false }; + bool acted = (bool)typeof(BuffManager).GetMethod("AttemptManaRefill", Np)!.Invoke(b, args)!; + Check.True(acted, "the mana step acts"); + Check.True((bool)args[1], "by refilling stamina"); + Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use"); + Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "the stamina kit Kit Min Success skipped"); + Check.True(FakeHost.Logs.Any(l => l.Contains("using the stamina kit despite Stamina Kit Min Success", StringComparison.Ordinal)), "logged"); + Check.Eq(SwapActivity(), 0, "no swap"); + } + + /// The kit sent and refused by the server (a UseDone with an error code). + private static void RefuseKit(BuffManager b, uint kit, bool stamina = false) + { + typeof(BuffManager).GetField("_kitRefusedAt", Np)!.SetValue(b, DateTime.MinValue); // past KitRetryAfterRefusalMs (real clock) + int uses = FakeHost.UsesOn.Count; + Check.True((bool)typeof(BuffManager).GetMethod(stamina ? "AttemptStaminaKitUse" : "AttemptHealthKitUse", Np, + stamina ? Type.EmptyTypes : new[] { typeof(bool) })!.Invoke(b, stamina ? null : new object[] { false })!, "the kit goes out"); + Check.Eq(FakeHost.UsesOn.Count, uses + 1, "sent"); + Check.Eq(FakeHost.UsesOn[^1].Source, kit, "that kit"); + FakeHost.UseDone(0x1D); // YoureTooBusy + Check.False(b.KitPending(), "refused: the wait ends"); + } + + // A kit the server keeps refusing (a UseDone error, "You're too busy!") is no answer the kit wait + // drops: without a cap it would count for the gate forever and no spell heal could ever go. + private static void RefusedKitAllowsSwap() + { + var setNow = new Action((bm, t) => bm.Clock = () => t); + var t0 = new DateTime(2026, 1, 1, 18, 0, 0); + + var b = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true); + FakeHost.UseDoneSeq = 10; + RefuseKit(b, Kit); + RefuseKit(b, Kit); + Check.False(VitalCast(b, "Heal Self"), "2 refusals: the kit still counts, Heal Self refused"); + RefuseKit(b, Kit); + Check.True(VitalCast(b, "Heal Self"), "3 refusals within 10 s: the kit is no kit, Heal Self handled: " + Why(b)); + Check.True(SwapActive(b), "the wand swap is under way"); + + // Spread over more than 10 s: no streak. + var s = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true); + FakeHost.UseDoneSeq = 10; + setNow(s, t0); RefuseKit(s, Kit); + setNow(s, t0.AddSeconds(6)); RefuseKit(s, Kit); + setNow(s, t0.AddSeconds(12)); RefuseKit(s, Kit); + Check.False(VitalCast(s, "Heal Self"), "3 refusals over 12 s: the kit still counts"); + + // A kit landing ends the streak. + var l = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true); + FakeHost.UseDoneSeq = 10; + RefuseKit(l, Kit); RefuseKit(l, Kit); RefuseKit(l, Kit); + typeof(BuffManager).GetField("_kitRefusedAt", Np)!.SetValue(l, DateTime.MinValue); + typeof(BuffManager).GetMethod("AttemptHealthKitUse", Np, new[] { typeof(bool) })!.Invoke(l, new object[] { false }); + l.OnChatWindowText("You heal yourself for 40 Health points. Your Treated Healing Kit has 3 uses left.", 0); + Check.False(VitalCast(l, "Heal Self"), "a kit landed: it counts again, Heal Self refused"); + + // Stamina kits too: Revitalize may swap once the stamina kit is refused 3 times. + var st = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 0, kitAnswers: true); + FakeHost.UseDoneSeq = 10; + Check.False(VitalCast(st, "Revitalize Self"), "control: the stamina kit carried, Revitalize refused"); + RefuseKit(st, StamKit, stamina: true); RefuseKit(st, StamKit, stamina: true); RefuseKit(st, StamKit, stamina: true); + Check.True(VitalCast(st, "Revitalize Self"), "stamina kit refused 3 times: Revitalize handled: " + Why(st)); + } + + // The gate allowed a swap (no kit), then a kit came back. Refusing now would leave the + // swap untouched until TickWandSwap abandons it, with the shield maybe already in the pack. + private static void SwapInFlightFinishes() + { + var b = Rig(CombatMode.Melee, Array.Empty()); + Check.True(VitalCast(b, "Heal Self"), "no kit: Heal Self handled"); + Check.True(SwapActive(b), "the swap started"); + var cache = (WorldObjectCache)typeof(BuffManager).GetField("_worldObjectCache", Np)!.GetValue(b)!; + _ = cache[unchecked((int)Kit)]; // the kit is back in the pack + cache.GetDirectInventory(forceRefresh: true); // the fake host has no container walk: refresh the snapshot by hand + Check.True((bool)typeof(BuffManager).GetMethod("HasUsableHealthKit", Np)!.Invoke(b, null)!, "the rig: the kit counts as usable"); + Check.True(VitalCast(b, "Heal Self"), "the kit back, the swap under way: still handled: " + Why(b)); + Check.True(SwapActive(b), "the swap is still under way"); + Check.Eq(FakeHost.UsesOn.Count, 0, "no kit sent mid-swap"); + } + + private static bool SwapActive(BuffManager b) + { + object swap = typeof(BuffManager).GetField("_wandSwap", Np)!.GetValue(b)!; + return (bool)swap.GetType().GetProperty("Active")!.GetValue(swap)!; + } + + // A wand not in hand is no reason to gate + // a character already in Magic: no weapon moves for its cast. + private static void MagicNoWandNotGated() + { + var b = Rig(CombatMode.Magic, new[] { Kit }); + VitalCast(b, "Heal Self"); + Check.False(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "in Magic: not gated: " + Why(b)); + } + + // A kit the kit picks would not use must not count for the gate either: one its result line called + // used up (BuffManager.KitUsedUp.cs), or one the client's live pack walk no longer lists. + private static void GoneKitAllowsSwap() + { + var b = Rig(CombatMode.Melee, new[] { Kit }); + Check.False(VitalCast(b, "Heal Self"), "control: the kit carried, Heal Self refused"); + + var u = Rig(CombatMode.Melee, new[] { Kit }); + Check.True((bool)typeof(BuffManager).GetMethod("AttemptHealthKitUse", Np, new[] { typeof(bool) })!.Invoke(u, new object[] { false })!, "the kit goes out"); + u.OnChatWindowText("You heal yourself for 12 Health points. Your Treated Healing Kit is used up.", 0); + Check.True(VitalCast(u, "Heal Self"), "the kit's line said used up: Heal Self handled: " + Why(u)); + Check.True(SwapActive(u), "the wand swap is under way"); + + var w = Rig(CombatMode.Melee, new[] { Kit }, walk: true); + var wc = (WorldObjectCache)typeof(BuffManager).GetField("_worldObjectCache", Np)!.GetValue(w)!; + DateTime wt = new DateTime(2026, 1, 1, 18, 0, 0); + wc.WalkClock = () => wt; // the walk's reuse on a test clock + Check.False(VitalCast(w, "Heal Self"), "control, live walk: the kit carried, Heal Self refused"); + FakeHost.Containers.Remove(Kit); // used up: the client deletes it; the cache never hears + FakeHost.Names.Remove(Kit); + wt = wt.AddMilliseconds(1100); // past the walk's 1 s reuse + Check.True(VitalCast(w, "Heal Self"), "the kit gone from the client's pack: Heal Self handled: " + Why(w)); + Check.True(SwapActive(w), "the wand swap is under way"); + } + + // A refusal streak ages out: with no refusal for 10 s the kit counts for the gate again. + private static void RefusedStreakAgesOut() + { + var b = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true); + var t0 = new DateTime(2026, 1, 1, 18, 0, 0); + DateTime now = t0; + b.Clock = () => now; + FakeHost.UseDoneSeq = 10; + RefuseKit(b, Kit); RefuseKit(b, Kit); RefuseKit(b, Kit); + Check.True(VitalCast(b, "Heal Self"), "control: 3 refusals, the kit is no kit: Heal Self handled: " + Why(b)); + var c = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true); + DateTime cnow = t0; + c.Clock = () => cnow; + FakeHost.UseDoneSeq = 10; + RefuseKit(c, Kit); RefuseKit(c, Kit); RefuseKit(c, Kit); + cnow = t0.AddSeconds(11); + Check.False(VitalCast(c, "Heal Self"), "11 s after the last refusal: the kit counts again, Heal Self refused"); + Check.True(Why(c).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "the gate's reason: " + Why(c)); + } + + // No wand found (no wand rule, none carried): the Magic stance goes bare-handed and no weapon moves. + private static void NoWandNotGated() + { + var b = Rig(CombatMode.Melee, new[] { Kit }, noWand: true); + VitalCast(b, "Heal Self"); + Check.False(Why(b).Contains("no wand swap", StringComparison.Ordinal), "no wand: not refused by the gate: " + Why(b)); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "the bare-handed Magic stance request goes out"); + Check.Eq(FakeHost.Wields.Count, 0, "no wield"); + } + + private static void SetVitals(BuffManager b, uint health, uint stamina, uint mana) + { + var v = (PlayerVitalsCache)typeof(BuffManager).GetField("_vitals", Np)!.GetValue(b)!; + v.CurrentHealth = health; v.CurrentStamina = stamina; v.CurrentMana = mana; + } + + private static void StaminaKitDespiteMinSuccess() + { + foreach (int minSuccess in new[] { 95, 0 }) + { + var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: minSuccess); + S.RestamAt = 50; + SetVitals(b, 100, 20, 100); + Check.True(b.CheckVitals(), $"min {minSuccess}: stamina 20% under Re-stam At 50%: the chain acts"); + Check.Eq(FakeHost.UsesOn.Count, 1, $"min {minSuccess}: one kit use"); + Check.Eq(FakeHost.UsesOn[0].Source, StamKit, $"min {minSuccess}: the stamina kit"); + bool lastResort = FakeHost.Logs.Any(l => l.Contains("using the stamina kit despite Stamina Kit Min Success", StringComparison.Ordinal)); + if (minSuccess == 95) Check.True(lastResort, "under Kit Min Success: used as the last resort, logged"); + else Check.False(lastResort, "control, chance fine: the normal kit use, no last-resort line"); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, $"min {minSuccess}: no Magic stance"); + Check.Eq(FakeHost.Casts.Count, 0, $"min {minSuccess}: no Revitalize"); + } + } + + private static void ManaInFightNoSwap() + { + // No mana potion, no kit: only the fight decides. + var f = Rig(CombatMode.Melee, Array.Empty(), usePotions: true); + f.InCombatOverride = () => true; + Check.False(VitalCast(f, "Stamina to Mana Self"), "in a fight: Stamina to Mana not handled"); + Check.True(Why(f).Contains("Stamina to Mana in a fight", StringComparison.Ordinal), "the why says so: " + Why(f)); + Check.Eq(SwapActivity(), 0, "in a fight: no swap"); + + var q = Rig(CombatMode.Melee, Array.Empty(), usePotions: true); + q.InCombatOverride = () => false; + int before = SwapActivity(); + Check.True(VitalCast(q, "Stamina to Mana Self"), "out of a fight, no mana potion: handled (the swap step): " + Why(q)); + Check.True(SwapActivity() > before, "out of a fight: the wand swap started"); + + // A caster in hand needs no swap: Stamina to Mana still goes in a fight. + var c = Rig(CombatMode.Melee, Array.Empty(), wandWielded: true); + c.InCombatOverride = () => true; + VitalCast(c, "Stamina to Mana Self"); + Check.False(Why(c).Contains("no wand swap", StringComparison.Ordinal), "caster in hand, in a fight: not gated: " + Why(c)); + } + + private static LegacyUiSettings S = new(); + + private static BuffManager Rig(int mode, uint[] items, bool wandWielded = false, bool usePotions = false, int kitMinSuccess = 0, bool kitAnswers = false, + bool walk = false, bool noWand = false) + { + FakeHost.Reset(); + uint[] carried = (noWand ? Array.Empty() : new[] { Wand }).Concat(items).ToArray(); + if (walk) + { + FakeHost.ContentsCalls = true; // the client's pack walk (GetContainerContents) + foreach (uint id in carried) FakeHost.Containers[id] = Player; + } + FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.UseOnCalls = true; + if (kitAnswers) { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; } // a kit's UseDone answers + FakeHost.CombatModeValue = mode; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic + FakeHost.Skills[(Player, 21)] = (10, 2); // Healing, low: a kit chance under any real Kit Min Success + if (!noWand) + { + FakeHost.Names[Wand] = "Wand"; + FakeHost.ItemTypes[Wand] = 0x8000; // a caster + FakeHost.Appraised.Add(Wand); // identified: FindWandInItems takes it (a real swap, not bare-handed Magic) + } + FakeHost.Names[Kit] = "Treated Healing Kit"; + // Lesser (boost 100): (10 + 100) x 1.1 = 121 vs 80 missing x 2 x 1.1 = 176 in melee, 16%, under the + // weapon-out bar of 30 (a Greater kit's boost 200 clears it). + FakeHost.Names[StamKit] = "Lesser Stamina Kit"; + FakeHost.Names[ManaPot] = "Mana Elixir"; + FakeHost.Names[HealPot] = "Healing Elixir"; + if (wandWielded) FakeHost.Ints[(Wand, CurrentWieldedLocation)] = unchecked((int)HeldSlot); + var host = FakeHost.Create(Player); + S = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 75, TopOffHP = 75, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = usePotions, EnableBuffing = false, + KitMinSuccessPct = kitMinSuccess, StaminaKitMinSuccessPct = kitMinSuccess, PeaceModeForKits = false, + }; + if (!noWand) S.ItemRules.Add(new ItemRule { Id = unchecked((int)Wand), Name = "Wand", Element = "Fire" }); + if (items.Contains(ManaPot)) S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)ManaPot), Name = "Mana Elixir", Type = "ManaPotion" }); + if (items.Contains(HealPot)) S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)HealPot), Name = "Healing Elixir", Type = "HealthPotion" }); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, S); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, S, sm, v); + b.SetCharacterSkills(skills); + b.MarkLiveBuffsReadyForTests(); + b.InCombatOverride = () => true; + b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, carried)); + DateTime now = new DateTime(2026, 1, 1, 18, 0, 0); + b.Clock = () => now; + return b; + } + + private static readonly BindingFlags Np = BindingFlags.Instance | BindingFlags.NonPublic; + + private static bool VitalCast(BuffManager b, string baseName) + => (bool)typeof(BuffManager).GetMethod("AttemptVitalCast", Np)!.Invoke(b, new object[] { baseName })!; + + private static string Why(BuffManager b) => (string)typeof(BuffManager).GetField("_vitalWhy", Np)!.GetValue(b)!; + + /// Everything a wand swap or stance change sends or logs. + private static int SwapActivity() => FakeHost.CombatModeRequests.Count + FakeHost.Wields.Count + FakeHost.Uses.Count + + FakeHost.Logs.Count(l => l.Contains("[WieldGate] switching to", StringComparison.Ordinal)); + + private static void HealRefusedWithKit() + { + foreach (int mode in new[] { CombatMode.Melee, CombatMode.Missile, CombatMode.NonCombat }) + { + var b = Rig(mode, new[] { Kit }); + int before = SwapActivity(); + Check.False(VitalCast(b, "Heal Self"), $"mode {mode}, kit carried: Heal Self not handled"); + Check.True(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), $"mode {mode}: the why says so: {Why(b)}"); + Check.Eq(SwapActivity(), before, $"mode {mode}: no stance change, wield or swap step"); + Check.Eq(FakeHost.Casts.Count, 0, $"mode {mode}: nothing cast"); + } + // A health potion alone (no kit) refuses it too. + var p = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: true); + Check.False(VitalCast(p, "Stamina to Health Self"), "health potion carried: Stamina to Health not handled"); + Check.Eq(SwapActivity(), 0, "and no swap"); + } + + private static void KitDespiteMinSuccessAfterRefusal() + { + var b = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 95); + Check.True(b.CheckVitals(), "40% under Heal At 75%: the chain acts"); + Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use"); + Check.Eq(FakeHost.UsesOn[0].Source, Kit, "the kit Kit Min Success skipped"); + Check.True(FakeHost.Logs.Any(l => l.Contains("despite Kit Min Success", StringComparison.Ordinal)), "the last resort is logged"); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, "no Magic stance asked for"); + Check.Eq(FakeHost.Casts.Count, 0, "no Heal Self"); + } + + private static void StanceOnlyWithCasterWielded() + { + var b = Rig(CombatMode.Melee, new[] { Kit }, wandWielded: true); + Check.False(Why(b).Contains("no wand swap", StringComparison.Ordinal), "rig"); + VitalCast(b, "Heal Self"); + Check.False(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "caster in hand: not refused by the gate: " + Why(b)); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "the Magic stance change goes out"); + Check.Eq(FakeHost.Wields.Count, 0, "no wield"); + Check.Eq(FakeHost.Uses.Count, 0, "no use (no re-equip)"); + Check.False(FakeHost.Logs.Any(l => l.Contains("[WieldGate] switching to", StringComparison.Ordinal)), "no swap started"); + } + + private static void SwapAllowedWithNothingElse() + { + // Control for HealRefusedWithKit: the same rig with nothing else to heal with. + var b = Rig(CombatMode.Melee, Array.Empty(), usePotions: true); + int before = SwapActivity(); + bool handled = VitalCast(b, "Heal Self"); + Check.True(handled, "no kit, no potion: Heal Self handled (its swap step in flight): " + Why(b)); + Check.True(SwapActivity() > before, "the wand swap started"); + // A potion only, with Use Potions off: nothing RynthAi may use, so the swap is allowed. + var k = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: false); + Check.True(VitalCast(k, "Heal Self"), "a potion Use Potions may not drink is no heal: the swap is allowed"); + } + + private static void OtherVitalsRefused() + { + var s = Rig(CombatMode.Melee, new[] { StamKit }); + Check.False(VitalCast(s, "Revitalize Self"), "stamina kit carried: Revitalize not handled"); + Check.Eq(SwapActivity(), 0, "no swap for Revitalize"); + var sc = Rig(CombatMode.Melee, new[] { Kit }); + Check.True(VitalCast(sc, "Revitalize Self"), "control: a healing kit is no stamina restore: Revitalize may swap"); + + var m = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true); + m.InCombatOverride = () => true; // the potion alone no longer refuses it (out of a fight it may swap): the fight does + Check.False(VitalCast(m, "Stamina to Mana Self"), "in a fight, mana potion carried: Stamina to Mana not handled"); + Check.Eq(SwapActivity(), 0, "no swap for Stamina to Mana in a fight"); + + // The script hook's heal goes through CastVital with the Healing label. + var h = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: true); + int heal = SpellTable.Rows.First(r => r.Name.StartsWith("Heal Self", StringComparison.Ordinal)).Id; + object[] args = { heal, Player, BuffManager.LabelHealing, "Heal Self (script)", false }; + bool handled = (bool)typeof(BuffManager).GetMethod("CastVital", Np)!.Invoke(h, args)!; + Check.False(handled, "script heal, health potion carried: not handled"); + Check.False((bool)args[4], "not sent"); + Check.Eq(SwapActivity(), 0, "no swap for the script heal"); + } + + private static void PureCasterUnaffected() + { + var b = Rig(CombatMode.Magic, new[] { Kit }, wandWielded: true); + S.UseKitsInMagicMode = false; // the kit is skipped in Magic: the spell is the heal + Check.True(b.CheckVitals(), "a caster in Magic under Heal At: acts"); + Check.True(FakeHost.Casts.Count > 0, "Heal Self is cast: " + Why(b)); + Check.Eq(FakeHost.UsesOn.Count, 0, "no kit"); + Check.Eq(FakeHost.Wields.Count, 0, "no wield"); + } + + private static void BuffsStillSwap() + { + var b = Rig(CombatMode.Melee, new[] { Kit, HealPot }, usePotions: true); + int before = SwapActivity(); + var ensure = typeof(BuffManager).GetMethod("EnsureMagicMode", Np)!; + bool inMagic = (bool)ensure.Invoke(b, new object[] { true, false })!; + Check.False(inMagic, "not in Magic yet"); + Check.True(SwapActivity() > before, "buffing starts the wand swap with a kit and potion carried"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs index 4428726..104deb4 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs @@ -26,10 +26,12 @@ internal static class VitalsTests r.Add("vitals: a recharge started in a fight, or under Re-stam At just after one, finishes to Re-stam To", RestamRunOutlivesFight); r.Add("vitals: a Re-stam To run counts casts sent, not the ticks spent waiting for one", RestamRunCountsSentCasts); r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst); + r.Add("vitals: no wand swap for the between-fights stamina top-off; under Re-stam At, with a potion or in Magic it acts as before", NoWandSwapForStaminaTopOff); r.Add("vitals: a listed potion whose stack ran out is drunk from the next stack of that name", ListedPotionNextStack); r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait); r.Add("vitals: Heal Self known only above the tier Life Magic allows (vitae) is still cast", HealAboveAllowedTier); r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter); + r.Add("vitals: health falling with nothing in the scan uses the fight's Heal At, not Top Off HP, for 5 s", BeingHitIsAFight); r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals); r.Add("vitals: no components for the top level - the next lower level is cast, not the same one again", NoComponentsFallsBack); // Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md). @@ -112,6 +114,32 @@ internal static class VitalsTests // 2026-10-04, "nav and looting have priority over healing, almost dying in packs": the // arbiter only saw a heal on ticks where CheckVitals ran (never while looting kept the client // busy). Health under a line now says "wants vitals" by itself. + // 2026-11-06: a mob behind a wall isn't in the scan, so a character it hit read as idle and every + // hit put him under Top Off HP: kits for 45 s and nothing else ran. + private static void BeingHitIsAFight() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 95, EmergencyHealAt = 0, StaminaToHealthAt = 0, UsePotions = false }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + b.SetCharacterSkills(skills); + + Check.False(b.WantsVitalRecharge, "full health: nothing to do"); + v.CurrentHealth = 80; + Check.False(b.WantsVitalRecharge, "hit down to 80%: a fight, and over Heal At 60"); + v.CurrentHealth = 50; + Check.True(b.WantsVitalRecharge, "50% is under Heal At: heals"); + } + private static void HealthWinsArbiter() { BuffManager Make(byte lifeTraining, out PlayerVitalsCache vitals, out LegacyUiSettings s) @@ -293,6 +321,56 @@ internal static class VitalsTests } } + // The owner, 2026-11-07: a melee character with no stamina kit or potion swapped weapons for the + // wand and back (about 5.5 s) for every between-fights stamina top-off. Out of a fight and over + // Re-stam At it now waits for regeneration; under Re-stam At, in Magic stance, or with a potion, + // stamina is handled as before. + private static void NoWandSwapForStaminaTopOff() + { + const uint Tincture = 0x80001234; + BuffManager Rig(int mode, int stamina, bool potion, out PlayerVitalsCache vitals) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = mode; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + if (potion) FakeHost.Names[Tincture] = "Stamina Tincture"; + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 30, RestamTo = 90, TopOffStam = 60, + UsePotions = potion, EnableBuffing = false }; + if (potion) s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Tincture), Name = "Stamina Tincture", Type = "Stamina" }); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = (uint)stamina, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, vitals) { InCombatOverride = () => false }; + b.SetCharacterSkills(skills); + b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, potion ? new[] { Tincture } : System.Array.Empty())); + return b; + } + + var melee = Rig(CombatMode.Melee, 50, potion: false, out _); + Check.False(melee.CheckVitals(), "melee, idle, 50% under Top Off 60, nothing but the spell: nothing to do"); + Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize"); + Check.False(FakeHost.Wields.Count > 0 || FakeHost.CombatModeRequests.Contains(CombatMode.Magic), "and no wand swap or Magic stance"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no wand swap for it out of a fight")), "logged why"); + + melee = Rig(CombatMode.Melee, 25, potion: false, out _); + Check.True(melee.CheckVitals(), "melee, idle, 25% under Re-stam At 30: the recharge goes (wand swap and Revitalize)"); + + var drink = Rig(CombatMode.Melee, 50, potion: true, out _); + Check.True(drink.CheckVitals(), "melee, idle, 50% with a tincture: still topped off"); + Check.True(FakeHost.Uses.Contains(Tincture), "the tincture is drunk"); + + var caster = Rig(CombatMode.Magic, 50, potion: false, out _); + Check.True(caster.CheckVitals(), "in Magic stance (no swap needed): the top-off casts as before"); + Check.True(FakeHost.Casts.Count > 0, "Revitalize is cast"); + } + // Report 2026-10-10: 200+ Stamina Tinctures, and RynthAi stopped drinking them whenever the stack // the rule was added from ran out, until the player added the next stack by hand. private static void ListedPotionNextStack() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VtRingImportTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VtRingImportTests.cs new file mode 100644 index 0000000..0809890 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VtRingImportTests.cs @@ -0,0 +1,145 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.MiniRemote; +using RynthCore.Plugin.RynthAi.ProfileImport; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// A VTank .usd import brings VTank's ring options along with the monsters' Ring ticks (2026-11-06): +// MinimumRingTargets -> Min Ring Targets, RingDistance (landblock units, x240 = yards, as every +// VTank distance RynthAi reads) -> Ring Range, each held to the settings window's range. A value +// the profile lacks leaves the setting alone. Only an import the player starts sets them. +// Fixtures\vtank-rings*.usd: a MyMonsters table (DEFAULT with Ring on) and then the options. +internal static class VtRingImportTests +{ + private const uint Player = 0x50000D01; + + public static void Register(Runner r) + { + r.Add("vtank ring import: the options read, converted (landblock units x240) and held to the settings' range", ReadAndConvert); + r.Add("vtank ring import (Hub): preview lists them, the import sets them and says so; none in the profile = left alone", HubImport); + r.Add("vtank ring import (profile importer): set when the profiles agree, left alone when they differ or have none", ProfileImporter); + } + + private static string Fixture(string name) => Path.Combine(AppContext.BaseDirectory, "Fixtures", name); + + private static void ReadAndConvert() + { + var r = VtRingSettings.Read(File.ReadAllLines(Fixture("vtank-rings.usd"))); + Check.Eq(r.MinRingTargets, 2, "MinimumRingTargets 2"); + Check.Eq(r.RingRange, 4, "RingDistance 0.0166667 landblock = 4 yards"); + Check.Eq(r.Describe(), "Min Ring Targets 2, Ring Range 4 (from the profile)", "the summary"); + Check.Eq(r.Clamped.Count, 0, "nothing held"); + + var none = VtRingSettings.Read(File.ReadAllLines(Fixture("vtank-rings-none.usd"))); + Check.False(none.Any, "a profile without them: none (AttackDistance and the rest are not ring options)"); + Check.Eq(none.Describe(), "", "nothing to say"); + + var clamp = VtRingSettings.Read(File.ReadAllLines(Fixture("vtank-rings-clamp.usd"))); + Check.Eq(clamp.MinRingTargets, 20, "MinimumRingTargets 30 held to 20"); + Check.Eq(clamp.RingRange, 50, "RingDistance 0.3 = 72 yards, held to 50"); + Check.Eq(string.Join("; ", clamp.Clamped), "Min Ring Targets 30 -> 20; Ring Range 72 -> 50", "the holds are noted"); + + var one = VtRingSettings.Read(File.ReadAllLines(Fixture("vtank-rings-mintargets-only.usd"))); + Check.Eq(one.MinRingTargets, 1, "MinimumRingTargets 0 held to 1"); + Check.Eq(one.RingRange, null, "no RingDistance: no Ring Range"); + + // The conversion is the meta path's: a meta's RingDistance gives the same Ring Range. + string[] Lines(string d) => new[] { "s", "RingDistance", "d", d }; + Check.Eq(VtRingSettings.Read(Lines("0.0208333333333333")).RingRange, 5, "5/240 landblock = 5"); + Check.Eq(VtRingSettings.Read(Lines("0.00833333333333333")).RingRange, 2, "2/240 landblock = 2"); + Check.Eq(VtRingSettings.Read(Lines("0.0188333333333333")).RingRange, 5, "4.52 yards rounds to 5"); + Check.Eq(VtRingSettings.Read(Lines("7")).RingRange, 7, "a value over 1 is yards already (typed by hand), as the meta path reads it"); + Check.Eq(VtRingSettings.Read(Lines("0")).RingRange, 1, "0 held to 1"); + Check.Eq(VtRingSettings.Read(new[] { "x", "RingDistance", "d", "0.02" }).RingRange, null, "only an option row (an 's' line before the name)"); + } + + private sealed class HubRig + { + public readonly LegacyUiSettings S = new() { MinRingTargets = 4, RingRange = 5 }; + public readonly VTankUsdImporter Usd; + public int Saves; + + public HubRig() + { + FakeHost.Reset(); + var host = FakeHost.Create(Player); + string dir = Path.Combine(Program.TempRoot, "vtank-ring-import"); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var store = new MiniRemoteStore(dir); + var cache = FakeHost.MakeCache(host, Player, Array.Empty()); + var ctx = new MiniRemoteContext(host, store.Load(), store, new MiniRemoteInventory(host, () => cache), + new ServerHubClient(host), () => S) + { SaveCombatSettings = () => Saves++ }; + Usd = new VTankUsdImporter(ctx); + } + } + + private static void HubImport() + { + var rig = new HubRig(); + rig.Usd.Preview(Fixture("vtank-rings.usd")); + Check.True(rig.Usd.Status.Contains("ring settings: Min Ring Targets 2 (now 4), Ring Range 4 (now 5)"), $"the preview lists them: {rig.Usd.Status}"); + Check.Eq((rig.S.MinRingTargets, rig.S.RingRange), (4, 5), "a preview changes nothing"); + rig.Usd.Apply(); + Check.Eq((rig.S.MinRingTargets, rig.S.RingRange), (2, 4), "the import sets them"); + Check.True(rig.Usd.Status.Contains("set Min Ring Targets 2, Ring Range 4 (from the profile)"), $"and says so: {rig.Usd.Status}"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Min Ring Targets 2, Ring Range 4 (from the profile)")), "in the chat too"); + Check.True(rig.S.MonsterRules.Any(m => m.UseRing), "the monsters' Ring ticks came along"); + Check.Eq(rig.Saves, 1, "saved once"); + + var none = new HubRig(); + none.S.MinRingTargets = 3; none.S.RingRange = 9; + none.Usd.Preview(Fixture("vtank-rings-none.usd")); + Check.True(none.Usd.Status.Contains("no ring settings in the profile"), $"the preview says there are none: {none.Usd.Status}"); + none.Usd.Apply(); + Check.Eq((none.S.MinRingTargets, none.S.RingRange), (3, 9), "none in the profile: left alone"); + Check.True(none.Usd.Status.Contains("ring settings left alone"), $"and says so: {none.Usd.Status}"); + + var half = new HubRig(); + half.Usd.Preview(Fixture("vtank-rings-mintargets-only.usd")); + half.Usd.Apply(); + Check.Eq((half.S.MinRingTargets, half.S.RingRange), (1, 5), "only Min Ring Targets in the profile: Ring Range left alone"); + + var clamp = new HubRig(); + clamp.Usd.Preview(Fixture("vtank-rings-clamp.usd")); + clamp.Usd.Apply(); + Check.Eq((clamp.S.MinRingTargets, clamp.S.RingRange), (20, 50), "held to the settings' range"); + } + + private static void ProfileImporter() + { + var s = new LegacyUiSettings { MinRingTargets = 4, RingRange = 5 }; + var result = new VirindiTankProfileImporter.Result(); + VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings.usd"), s, result); + Check.Eq((s.MinRingTargets, s.RingRange), (4, 5), "reading a profile changes nothing by itself"); + VirindiTankProfileImporter.ApplyRingSettings(s, result); + Check.Eq((s.MinRingTargets, s.RingRange), (2, 4), "one profile: its values"); + Check.Eq(result.RingSettingsSet, "Min Ring Targets 2, Ring Range 4 (from the profile)", "the summary"); + Check.True(result.LogLines.Any(l => l.Contains("Ring settings: set Min Ring Targets 2, Ring Range 4")), "the import's lines say it"); + + // Two profiles (two characters) that disagree: neither wins. + var s2 = new LegacyUiSettings { MinRingTargets = 4, RingRange = 5 }; + var r2 = new VirindiTankProfileImporter.Result(); + VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings.usd"), s2, r2); + VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings-clamp.usd"), s2, r2); + VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings-none.usd"), s2, r2); + VirindiTankProfileImporter.ApplyRingSettings(s2, r2); + Check.Eq((s2.MinRingTargets, s2.RingRange), (4, 5), "profiles that differ: left alone"); + Check.True(r2.LogLines.Any(l => l.Contains("the profiles differ") && l.Contains("left alone")), "and it says so"); + Check.Eq(r2.RingSettingsSet, "", "nothing set"); + + // Only profiles without ring options: nothing found, nothing said or set. + var s3 = new LegacyUiSettings { MinRingTargets = 3, RingRange = 7 }; + var r3 = new VirindiTankProfileImporter.Result(); + VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings-none.usd"), s3, r3); + VirindiTankProfileImporter.ApplyRingSettings(s3, r3); + Check.Eq((s3.MinRingTargets, s3.RingRange), (3, 7), "none in the profiles: left alone"); + Check.False(r3.LogLines.Any(l => l.StartsWith("Ring settings")), "nothing to say"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WieldBanTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WieldBanTests.cs new file mode 100644 index 0000000..c8d62b6 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/WieldBanTests.cs @@ -0,0 +1,263 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +/// +/// The false "it never reached your hand" ban: combat's wield of a weapon landed, buffing swapped +/// it out for the wand before combat looked again, each of those wields counted as a failed try, +/// and after the third the weapon was left out of the choice for 30 min. The engine's equipment +/// list (FakeHost.Equipped, API v87) plays the server's wield messages here. A wield that truly +/// never shows in the list must still be banned. +/// +internal static class WieldBanTests +{ + private const uint Player = 0x50000C01; + private const uint Blade = 0x800484AA, Wand = 0x80048401, Nodachi = 0x80048402; + private const uint MeleeSlot = 0x00100000, HeldSlot = 0x01000000, ShieldSlot = 0x00200000; + private const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic; + + public static void Register(Runner r) + { + r.Add("wield ban: a weapon seen wielded between combat's looks is not banned, its tries start over", SeenWieldedNotBanned); + r.Add("wield ban: no ban while the equipment list shows the weapon at the give-up", ListShowsItAtGiveUp); + r.Add("wield ban: a wield that never shows in the list is still banned", NeverShownStillBanned); + r.Add("wield ban: one sighting, then three wields never seen: banned (a new run forgets the sighting)", SeenOnceThenNeverBanned); + r.Add("wield ban: a weapon in the shield slot is not a main-hand sighting, it still rests", ShieldSlotNotASighting); + r.Add("wield ban: the server's 'skill too low' still bans at once", SkillTooLowStillBans); + r.Add("wield ban: the plugin's sampler call alone resets the tries (no heartbeat)", DirectSamplerResetsTries); + r.Add("wield ban: RynthAiPlugin's tick samples wields before the buffing hold returns", PluginSamplesBeforeBuffHold); + r.Add("wield ban: a stale try count stops the equipment list sampling", StaleCountStopsSampling); + } + + private sealed class Rig + { + public readonly CombatManager C; + private readonly MethodInfo _send = typeof(CombatManager).GetMethod("MarkWieldSent", F)!; + private readonly MethodInfo _step = typeof(CombatManager).GetMethod("SwapStep", F)!; + + public Rig(bool equipped = true, bool weenieErrors = false) + { + FakeHost.Reset(); + FakeHost.EquippedCalls = equipped; + FakeHost.WeenieErrorCalls = weenieErrors; + FakeHost.Names[Blade] = "Test Blade"; + FakeHost.Names[Wand] = "Fire Wand"; + FakeHost.Names[Nodachi] = "Nodachi"; + var host = FakeHost.Create(); + var cache = FakeHost.MakeCache(host, Player, new[] { Blade, Wand, Nodachi }); + C = new CombatManager(host, new LegacyUiSettings(), cache); + C.SetPlayerId(Player); + C.SwapTracker.ResolveMs = 0; // each look after a send resolves it (no real 2.5 s waits) + Hold(Wand, HeldSlot); + } + + /// What the server says is wielded now: only . + public void Hold(uint id, uint slot) + { + FakeHost.Equipped.Clear(); + FakeHost.Equipped[id] = slot; + EquippedState.Invalidate(); + } + + public void Send(uint id, uint from) => _send.Invoke(C, new object[] { unchecked((int)id), unchecked((int)from) }); + public WeaponSwapTracker.Step Step(uint id, uint inHand) => + (WeaponSwapTracker.Step)_step.Invoke(C, new object[] { unchecked((int)id), unchecked((int)inHand) })!; + public bool Banned(uint id) => C.SkillTooLowFor(unchecked((int)id)); + public int Tries(uint id) => C.SwapTracker.TriesFor(unchecked((int)id)); + } + + private static bool NeverReachedLogged() => FakeHost.Logs.Any(l => l.Contains("never reached your hand")); + + /// A weapon that lands, is swapped out for the wand by buffing, and lands again is never banned: three times over. + private static void SeenWieldedNotBanned() + { + var rig = new Rig(); + try + { + for (int i = 1; i <= 3; i++) + { + rig.Send(Blade, Wand); // combat sends the wield + rig.Hold(Blade, MeleeSlot); // the server wields it + rig.C.OnHeartbeat(); // a tick samples the equipment list + Check.Eq(rig.Tries(Blade), 0, $"wield {i}: seen in hand, its try count starts over"); + rig.Hold(Wand, HeldSlot); // buffing swaps it out for the wand + rig.Step(Blade, Wand); // combat looks: the wand is in hand + } + Check.False(rig.Banned(Blade), "three wields that landed: not left out of the weapon choice"); + Check.False(NeverReachedLogged(), "no 'never reached your hand' line"); + } + finally { EquippedState.Invalidate(); } + } + + /// The give-up itself reads the list, and a list holding the weapon is no ban. + private static void ListShowsItAtGiveUp() + { + var rig = new Rig(); + try + { + for (int i = 1; i <= 3; i++) + { + rig.Send(Blade, Wand); + // No tick samples between the wields here. At the third look the server's list + // holds the weapon (the hand read combat passed in is stale). + if (i == 3) { FakeHost.Equipped[Blade] = MeleeSlot; EquippedState.Invalidate(); } + rig.Step(Blade, Wand); + } + Check.False(rig.Banned(Blade), "the list shows it wielded at the give-up: not banned"); + Check.False(NeverReachedLogged(), "no 'never reached your hand' line"); + + // Control: no equipment list from the engine, nothing is known: no ban either way (as before). + var blind = new Rig(equipped: false); + for (int i = 1; i <= 3; i++) { blind.Send(Blade, Wand); blind.Step(Blade, Wand); } + Check.False(blind.Banned(Blade), "no equipment list: no 'never reached' ban"); + } + finally { EquippedState.Invalidate(); } + } + + /// A wield the client or server truly refuses (never in the list) still bans. + private static void NeverShownStillBanned() + { + var rig = new Rig(); + try + { + for (int i = 1; i <= 3; i++) + { + rig.Send(Blade, Wand); + rig.C.OnHeartbeat(); // ticks sample: only the wand, every time + Check.Eq(rig.Tries(Blade), i, $"wield {i}: never seen, the try counts"); + rig.Step(Blade, Wand); + } + Check.True(rig.Banned(Blade), "three wields never seen in the list: left out of the weapon choice"); + Check.True(NeverReachedLogged(), "logged as 'never reached your hand'"); + } + finally { EquippedState.Invalidate(); } + } + + /// + /// A sighting counts for its own run of wields only. The weapon lands once (buffing swaps it + /// out), then stops reaching the hand: three unseen wields still end in the ban, instead of + /// three wields and an off-hand clear every 2 min forever. + /// + private static void SeenOnceThenNeverBanned() + { + var rig = new Rig(); + try + { + rig.Send(Blade, Wand); + rig.Hold(Blade, MeleeSlot); + rig.C.OnHeartbeat(); + Check.Eq(rig.Tries(Blade), 0, "the landed wield: seen, the count starts over"); + rig.Hold(Wand, HeldSlot); + rig.Step(Blade, Wand); + for (int i = 1; i <= 3; i++) + { + rig.Send(Blade, Wand); + rig.C.OnHeartbeat(); // only the wand, every time + rig.Step(Blade, Wand); + } + Check.True(rig.Banned(Blade), "three later wields never seen: left out of the weapon choice"); + Check.True(NeverReachedLogged(), "logged as 'never reached your hand'"); + } + finally { EquippedState.Invalidate(); } + } + + /// + /// Only main-hand slots count (as InHandWeaponId reads them). A weapon chosen while it sits in + /// the shield slot is not a landed wield: its tries count, and after three it rests instead + /// of being sent again every 2.5 s. + /// + private static void ShieldSlotNotASighting() + { + var rig = new Rig(); + try + { + FakeHost.Equipped[Blade] = ShieldSlot; // the off-hand slot, next to the wand + EquippedState.Invalidate(); + var last = WeaponSwapTracker.Step.Swap; + for (int i = 1; i <= 3; i++) + { + rig.Send(Blade, Wand); + rig.C.OnHeartbeat(); + Check.Eq(rig.Tries(Blade), i, $"wield {i}: the shield slot is no sighting, the try counts"); + last = rig.Step(Blade, Wand); + } + Check.Eq(last, WeaponSwapTracker.Step.Hold, "after three tries: rested, not sent again"); + Check.Eq(rig.Step(Blade, Wand), WeaponSwapTracker.Step.Hold, "still resting on the next look"); + } + finally { EquippedState.Invalidate(); } + } + + /// The server's own "skill too low" answer is untouched by the sightings: banned at once. + private static void SkillTooLowStillBans() + { + var rig = new Rig(weenieErrors: true); + try + { + rig.Send(Nodachi, Wand); + FakeHost.WeenieError(CombatManager.SkillTooLowErr, 0x00A0, Nodachi); + rig.C.OnHeartbeat(); + rig.Step(Nodachi, Wand); + Check.True(rig.Banned(Nodachi), "the server refused it: left out of the weapon choice"); + } + finally { EquippedState.Invalidate(); } + } + + /// The sampler the plugin calls every tick works without combat's heartbeat. + private static void DirectSamplerResetsTries() + { + var rig = new Rig(); + try + { + rig.Send(Blade, Wand); + Check.Eq(rig.Tries(Blade), 1, "setup: one wield sent"); + rig.Hold(Blade, MeleeSlot); + rig.C.NoteSwapWieldsSeen(); + Check.Eq(rig.Tries(Blade), 0, "the sampler alone sees it in hand: the count starts over"); + } + finally { EquippedState.Invalidate(); } + } + + /// + /// Source pin. The buffing hold returns from OnTick before combat's heartbeat runs, so the + /// plugin's own sampler call must come after the buff step and before that hold. + /// + private static void PluginSamplesBeforeBuffHold() + { + string? root = AppContext.BaseDirectory; + while (root != null && !Directory.Exists(Path.Combine(root, "Plugins"))) root = Path.GetDirectoryName(root); + Check.True(root != null, "found the repo (a Plugins folder above the test output)"); + if (root == null) return; + string src = File.ReadAllText(Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthAi", "RynthAiPlugin.cs")); + int buffStep = src.IndexOf("Guard(TickStep.BuffsAndVitals, () => _buffManager?.OnHeartbeat());", StringComparison.Ordinal); + int sample = src.IndexOf("_combatManager?.NoteSwapWieldsSeen();", StringComparison.Ordinal); + int buffHold = src.IndexOf("if (settings.IsMacroRunning && _activity == BotActivity.Buffing)", StringComparison.Ordinal); + Check.True(buffStep >= 0, "the buff step is in OnTick"); + Check.True(buffHold >= 0, "the buffing hold is in OnTick"); + Check.True(sample >= 0, "OnTick calls NoteSwapWieldsSeen"); + Check.True(sample > buffStep && sample < buffHold, "after the buff step and before the buffing hold's return"); + int holdReturn = buffHold >= 0 ? src.IndexOf("return;", buffHold, StringComparison.Ordinal) : -1; + Check.True(holdReturn > buffHold, "the buffing hold returns early (what makes the call's place matter)"); + } + + /// A try count left behind with no send for 2 min no longer keeps the sampler reading every tick. + private static void StaleCountStopsSampling() + { + var tr = new WeaponSwapTracker(); + var t = new DateTime(2026, 11, 2, 12, 0, 0); + tr.Sent(5, 1, t); + tr.Next(5, 1, t.AddSeconds(3)); // not seen in 2.5 s: the try stays counted + Check.Eq(tr.PendingId, 0, "setup: nothing in flight"); + Check.Eq(tr.TriesFor(5), 1, "setup: one try counted"); + Check.True(tr.HasAttemptsAt(t.AddSeconds(10)), "10 s after the send: sampled"); + Check.False(tr.HasAttemptsAt(t.AddMinutes(3)), "3 min after the last send: not sampled"); + tr.Sent(5, 1, t.AddMinutes(3)); + Check.True(tr.HasAttemptsAt(t.AddMinutes(3)), "a new send: sampled again"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs index 69db529..b4c96b0 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs @@ -37,6 +37,7 @@ internal static class WorldCacheTypedTests r.Add("world cache: corpses: named at once, and a Container-typed one named late is rescued", Corpses); r.Add("world cache: an Unknown whose type arrives late is filed as the item it is", LateType); r.Add("world cache: scrolls, slot-typed weapons, chests, lifestones; signs stay scenery", LootClasses); + r.Add("world cache: a chest created before its position was known lands on the landscape once it has one", LooseChestWithoutPosition); } // ── Rig ─────────────────────────────────────────────────────────────── @@ -112,6 +113,32 @@ internal static class WorldCacheTypedTests Check.False(FakeHost.Logs.Any(l => l.Contains("stuck Unknown", StringComparison.Ordinal)), "nothing left for the Unknown re-probe"); } + /// The Dreamweave dig's Unearthed Cache (2026-11-02): a container created with no position yet, nobody holding + /// it. It was filed as carried for good, so "use " and Loot by name never found it. + private static void LooseChestWithoutPosition() + { + World(); + uint cache = _next++; + FakeHost.Names[cache] = "Unearthed Cache"; + FakeHost.ItemTypes[cache] = TContainer; + FakeHost.Containers[cache] = 0; // nobody holds it + FakeHost.NotAttackable.Add(cache); + uint bag = _next++; // a side pack we carry, also created before it had a position + FakeHost.Names[bag] = "Caravaneer's Pack"; + FakeHost.ItemTypes[bag] = TContainer; + FakeHost.Containers[bag] = Player; + FakeHost.NotAttackable.Add(bag); + + var c = Classify(cache, bag); + Check.True(InInventory(c, cache), "no position yet: filed with what is carried (as before)"); + + FakeHost.Positions[cache] = (Here, 98f, 98f, 0f); + FakeHost.Positions[bag] = (Here, 99f, 99f, 0f); + Reclassify(c); + Where(c, cache, AcObjectClass.Container, false, true, "the cache once it has a position"); + Where(c, bag, AcObjectClass.Container, true, false, "a pack we carry stays in the inventory"); + } + private static void OtherPlayersGear() { World(); diff --git a/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj b/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj index 70b4055..e97a7ab 100644 --- a/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj +++ b/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj @@ -28,6 +28,7 @@ + diff --git a/Tools/RynthCore.TrackerSessionTests/SessionStatsTests.cs b/Tools/RynthCore.TrackerSessionTests/SessionStatsTests.cs index 6284bf1..10314c7 100644 --- a/Tools/RynthCore.TrackerSessionTests/SessionStatsTests.cs +++ b/Tools/RynthCore.TrackerSessionTests/SessionStatsTests.cs @@ -17,6 +17,7 @@ internal static partial class Program TestLumChatLines(); TestIltBankLum(); TestIltDepositExpires(); + TestServerProfileBankLum(); TestChatFallbackUntilBank(); TestAelrynthAndRetailLum(); TestLumLast5Min(); @@ -94,6 +95,29 @@ internal static partial class Program Eq(s.LumTotal, 400L, "an expired deposit line no longer eats income"); } + // A server that banks earned luminance where the client can't read it: its server plugin reads the + // bank once a minute and the tracker passes that reading in as the bank (2026-11-02). The same value + // comes in on every poll in between; the character's luminance is never sent. + private static void TestServerProfileBankLum() + { + var s = new SessionStats(); + s.Reset(S0); + DateTime t = S0; + void Polls(long bank, int seconds) + { + for (int i = 0; i < seconds * 2; i++) { t = t.AddSeconds(0.5); s.Sample(new SessionSample(1, null, bank, null, null, null), t); } + } + Polls(2_000_000, 60); + Eq(s.LumTotal, 0L, "profile bank: the first reading is the baseline"); + Check(s.BankTracked, "profile bank: the bank is tracked"); + for (int minute = 1; minute <= 59; minute++) Polls(2_000_000 + minute * 10_000L, 60); + Eq(s.LumTotal, 590_000L, "profile bank: each minute's rise counts once"); + Check(Math.Abs(s.View(t).LumPerHour - 590_000) < 1, $"profile bank: about 590,000 an hour ({s.View(t).LumPerHour:0})"); + Polls(100_000, 60); + Eq(s.LumTotal, 590_000L, "profile bank: spending is a drop, not negative"); + Polls(150_000, 60); + Eq(s.LumTotal, 640_000L, "profile bank: and the next rise counts"); + } // "You've banked" counts only until a bank property is read; then the bank covers it. private static void TestChatFallbackUntilBank() { diff --git a/Tools/RynthDefective.Tests/BusyClearTests.cs b/Tools/RynthDefective.Tests/BusyClearTests.cs new file mode 100644 index 0000000..7edf335 --- /dev/null +++ b/Tools/RynthDefective.Tests/BusyClearTests.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.RynthDefective; +using RynthCore.Plugin.RynthDefective.Items; +using RynthCore.Plugin.RynthDefective.Model; +using RynthCore.Plugin.RynthDefective.Ui; +using RynthCore.Plugin.RynthDefective.Use; +using RynthCore.Plugin.RynthDefective.Views; + +namespace RynthDefective.Tests +{ + // "Shortcuts clear a stuck busy state" (2026-11-04, DefSettings.ClearStuckBusy): when a press clears + // the busy count first (BusyClearRule: only the count holds it, nothing real in flight), the use + // controller's clear-then-use (once per press, logged), off by default, the setting, the command. + internal static partial class Program + { + private static void BusyClearDecisions() + { + Check(!new DefSettings().ClearStuckBusy, "off by default"); + + // A count of 2 that moved a second ago, nothing of ours for a long time, no gesture, no RynthAi. + var f = new BusyFacts(Count: 2, CountSteadyMs: 1000, Leftover: 0, SinceOwnSendMs: 60_000, + Animating: false, AnimatingMs: 0, BotWaiting: null, BotSteadyMs: 0); + bool Clear(in BusyFacts x, BusyHold hold = BusyHold.Busy, bool on = true, bool inFlight = false, bool answered = true, long sinceBusy = 60_000) => + BusyClearRule.ShouldClear(on, hold, x, inFlight, answered, sinceBusy); + + Check(Clear(f), "only the count holds it: clear"); + Check(!Clear(f, on: false), "the option off: never"); + Check(!Clear(f, BusyHold.Animation) && !Clear(f, BusyHold.Bot) && !Clear(f, BusyHold.None), "held by something else, or not held: no"); + Check(!Clear(f with { Count = 0 }), "no count: nothing to clear"); + Check(!Clear(f, inFlight: true), "our own use in flight: no"); + Check(!Clear(f with { SinceOwnSendMs = 1000 }, answered: false), "our own last use, unanswered, just now: no (it may be the count)"); + Check(Clear(f with { SinceOwnSendMs = 1000 }, answered: true), "our own last use was answered: the count isn't it"); + Check(Clear(f with { SinceOwnSendMs = BusyRule.OwnTrustMs }, answered: false), "unanswered but long ago: not ours any more"); + Check(!Clear(f with { Animating = true, AnimatingMs = 100 }), "a gesture animating: no"); + Check(!Clear(f with { Animating = true, AnimatingMs = 60_000 }), "even one that has 'animated' for a minute: no"); + Check(!Clear(f with { BotPaced = true, BotPacedMs = 100 }), "RynthAi's own action unanswered: no"); + Check(!Clear(f with { BotPaced = true, BotPacedMs = 60_000 }), "even a stale one: no"); + Check(Clear(f with { BotPaced = false, BotWaiting = true, BotSteadyMs = 100 }), + "RynthAi says it has nothing in flight: its 'waiting' bit is its copy of the count"); + Check(!Clear(f with { BotWaiting = true, BotSteadyMs = 1000 }), "a RynthAi that can't say, waiting on the server just now: no"); + Check(Clear(f with { BotWaiting = true, BotSteadyMs = BusyRule.BotTrustMs }), "its bit stuck for longer than any of its actions: yes"); + Check(!Clear(f, sinceBusy: 2000), "the server said 'too busy' 2 s ago: it really is busy, no"); + Check(Clear(f, sinceBusy: BusyClearRule.ServerBusyRecentMs), "5 s later: yes"); + } + + private static void UseClearStuckBusy() + { + ItemRef kit = ItemRef.From(Kit(0x10)); + + // Off (the default): a login's count holds the press as before, and nothing is reset. + Harness h = With(Kit(0x10)); + h.World.BusyCount = 2; + h.Tick(); + h.Slot(kit); + h.Ticks(3, 1000); + Check(h.World.Sent.Count == 0 && h.World.Clears == 0, "off: held, nothing cleared"); + h.Tick(1000); + Eq(string.Join("|", h.World.Sent), "useon 10 me", "off: it goes once the count is a leftover, as before"); + Eq(h.World.Clears, 0, "off: the count is never reset"); + + // On: the clear, then the use as soon as the reset reads. + h = With(Kit(0x10)); + h.Use.Settings.ClearStuckBusy = true; + h.World.BusyCount = 2; + h.Tick(); + h.Slot(kit); + h.Tick(50); + Check(h.World.Clears == 1 && h.World.Sent.Count == 0, "on: cleared first, nothing sent yet"); + Check(h.Logged.Any(l => l.Contains("held only by the client's busy count (2") && l.Contains("as /ra clearbusy does")), "the clear is logged: " + string.Join(";", h.Logged)); + Check(h.Said.Any(s => s.Contains("clearing a stuck busy state")), "and on the status line"); + h.Tick(50); + Eq(string.Join("|", h.World.Sent), "useon 10 me", "the reset read: the kit goes at once"); + Eq(h.World.Clears, 1, "once for the press"); + Eq(h.Warned.Count, 0, "no warning"); + + // The next press gets its own (once per press, not once ever). + h.World.Answer(); + h.Tick(100); + h.World.BusyCount = 1; // something raises it again + h.Tick(300); + h.Slot(kit); + h.Tick(50); + Eq(h.World.Clears, 2, "a new press held by the count: one more clear"); + h.Tick(50); + Eq(h.World.Sent.Count, 2, "and it goes"); + + // The reset doesn't take: the press waits the settle time, then the count is a leftover and it goes. + h = With(Kit(0x10)); + h.Use.Settings.ClearStuckBusy = true; + h.World.ClearLands = false; + h.World.BusyCount = 2; + h.Tick(); + h.Slot(kit); + h.Tick(50); + h.Tick(100); + Check(h.World.Clears == 1 && h.World.Sent.Count == 0, "the count still reads 2: waiting for the reset"); + h.Tick(UseController.ClearSettleMs); + Eq(string.Join("|", h.World.Sent), "useon 10 me", "after the settle time it goes: what is left is a leftover"); + Eq(h.World.Clears, 1, "not cleared twice"); + Eq(h.Use.Busy.Leftover, 2, "2 is the leftover"); + + // An engine that can't reset: logged, and the usual rules. + h = With(Kit(0x10)); + h.Use.Settings.ClearStuckBusy = true; + h.World.CanClear = false; + h.World.BusyCount = 2; + h.Tick(); + h.Slot(kit); + h.Ticks(3, 1000); + Check(h.World.Sent.Count == 0 && h.Logged.Count(l => l.Contains("can't reset it")) == 1, "can't clear: said once in the log, held as usual"); + h.Tick(1000); + Eq(h.World.Sent.Count, 1, "and goes when the usual rules let it"); + + // Never with something real in flight: a gesture, RynthAi's own action, the server's 'too busy'. + h = With(Kit(0x10)); + h.Use.Settings.ClearStuckBusy = true; + h.World.BusyCount = 2; + h.World.Animating = true; + h.Tick(); + h.Slot(kit); + h.Ticks(3, 1000); + Eq(h.World.Clears, 0, "a gesture animating: nothing cleared"); + + h = With(Kit(0x10)); + h.Use.Settings.ClearStuckBusy = true; + h.World.YieldOn = true; + h.World.BotOwnAction = true; + h.World.BusyCount = 2; + h.Tick(); + h.Slot(kit); + h.Ticks(4, 1000); + Eq(h.World.Clears, 0, "RynthAi's own action in flight: nothing cleared"); + + h = With(Kit(0x10)); + h.Use.Settings.ClearStuckBusy = true; + h.Slot(kit); + h.Tick(); + Eq(h.World.Sent.Count, 1, "sent"); + h.World.Answer(UseController.TooBusyError); + h.World.BusyCount = 1; + h.Tick(100); + Check(h.Use.HasPending, "the server said 'too busy': one more try queued"); + h.Ticks(3, 1000); + Eq(h.World.Clears, 0, "the server really is busy: nothing cleared for the retry"); + + // Our own last use answered, the count still up a moment (the engine's count catches up later): + // the next press may clear it. + h = With(Kit(0x10), Potion(0x11)); + h.Use.Settings.ClearStuckBusy = true; + h.Slot(kit); + h.Tick(); + h.World.BusyCount = 1; + h.Tick(100); + h.World.Answer(); + h.Tick(100); + Check(!h.Use.InFlight, "the kit was answered"); + h.Slot(ItemRef.From(Potion(0x11))); + h.Tick(300); + Eq(h.World.Clears, 1, "the potion: the count is no action of ours in flight, cleared"); + h.Tick(50); + Eq(h.World.Sent.Count, 2, "and the potion goes"); + } + + private static void ClearBusySettingAndCommand() + { + // The character's file. + var d = new DefData(); + d.Settings.ClearStuckBusy = true; + Check(DefStore.Parse(JsonDocument.Parse(DefStore.ToJson(d)).RootElement).Settings.ClearStuckBusy, "saved and read: on"); + Check(!DefStore.Parse(JsonDocument.Parse("{\"settings\":{\"quantityBox\":true}}").RootElement).Settings.ClearStuckBusy, "a file from before: off"); + + // The command. + DefCommand c = DefCommandParser.Parse("shortcuts clearbusy on"); + Check(c.Verb == DefVerb.Shortcuts && c.Text == "on", "/rdef shortcuts clearbusy on"); + Check(DefCommandParser.Parse("shortcuts clearbusy off").Text == "off", "off"); + Check(DefCommandParser.Parse("shortcuts ClearBusy OFF").Text == "off", "any case"); + c = DefCommandParser.Parse("shortcuts clearbusy"); + Check(c.Verb == DefVerb.Shortcuts && c.Text == "", "alone: says what it is"); + foreach (string wrong in new[] { "shortcuts", "shortcuts clearbusy maybe", "shortcuts frob on", "shortcuts clearbusy on now" }) + { + c = DefCommandParser.Parse(wrong); + Check(c.Verb == DefVerb.Error && c.Error.Contains("Usage", StringComparison.Ordinal), $"'/rdef {wrong}' answers how it's typed: {c.Error}"); + } + Check(DefReplies.ClearBusy(true).Contains(": on") && DefReplies.ClearBusy(true).Contains("/ra clearbusy"), "the on reply says what it does"); + Check(DefReplies.ClearBusy(false).Contains(": off (the default)"), "the off reply"); + + // The settings window's box, and the script-window bar's. + var b = new BarRig("clearbusy-settings"); + var host = new UiHost(); + UiWindow win = host.Add(new UiWindow("RynthDefective/Settings", "Defective Settings") { Visible = true, ShowInBar = false }); + var view = new BarSettingsView(b.S) { WindowShown = t => t == BarSettingsView.BarTitle ? true : null }; + win.Begin(); view.Draw(win); win.End(); + ParseAll(host, "settings window with the clear-busy box", out _); + Check(Encoding.UTF8.GetString(win.Body).Contains("Shortcuts clear a stuck busy state"), "the box is in the settings"); + var w = new Windows("clearbusy-settings-events"); + w.Host.Add(win); + int saves = b.R.Saves; + w.SetBool(win, "set.clearbusy", true); + Check(b.S.Settings.ClearStuckBusy && b.R.Saves > saves, "ticking it turns it on, saved"); + w.SetBool(win, "set.clearbusy", false); + Check(!b.S.Settings.ClearStuckBusy, "and off"); + + var t = new Windows("clearbusy-old-bar"); + var panel = new SettingsPanel(t.S, () => { }); + UiWindow pw = t.Host.Add(new UiWindow("RynthDefective/Old", "Old") { Visible = true }); + pw.Begin(); panel.Draw(pw); pw.End(); + Check(Encoding.UTF8.GetString(pw.Body).Contains("Shortcuts clear a stuck busy state"), "the script-window bar's settings have it too"); + t.SetBool(pw, "set.clearbusy", true); + Check(t.S.Settings.ClearStuckBusy, "and it works there"); + } + } +} diff --git a/Tools/RynthDefective.Tests/ClockTests.cs b/Tools/RynthDefective.Tests/ClockTests.cs new file mode 100644 index 0000000..4e1a9c6 --- /dev/null +++ b/Tools/RynthDefective.Tests/ClockTests.cs @@ -0,0 +1,152 @@ +using System; +using RynthCore.Plugin.RynthDefective.Clock; +using RynthCore.Plugin.RynthDefective.Model; +using RynthCore.Plugin.Shared; + +namespace RynthDefective.Tests +{ + // The Day/Night timer (2026-11-04): Plugins/Shared/DerethClock.cs from a raw clock reading (no game). + // With RynthAi's calendar offset the time of day is (raw + 3600) mod 7620 ticks, a tick a real second. + internal static partial class Program + { + /// A raw clock reading ticks after Darktide began (a later day, so the raw is positive). + private static double RawAt(double into, int day = 1) => DerethClock.TicksInDay * day + into - 3600; + + private static void ClockDayNight() + { + Eq(DerethClock.TicksInDay, 7620.0, "a Dereth day is 7620 ticks"); + Eq(DerethClock.TicksInDay * DerethClock.SecondsPerTick / 60.0, 127.0, "= 2 h 7 min of real time"); + + // Darktide's start: night, dawn in 4 hours = 1905 s. + DerethNow n = DerethClock.At(RawAt(0)); + Check(!n.IsDay, "Darktide: night"); + Eq(n.Hour, 0, "Darktide: hour 0"); + Eq(n.HourName, "Darktide", "Darktide: its name"); + Eq(n.SecondsToChange, 1905.0, "Darktide: dawn in 4 hours of 476.25 s"); + Eq(n.Next, "Day", "at night the day comes next"); + Eq(n.NextHourName, "Dawnsong", "at Dawnsong"); + + // Dawn itself: day for 8 hours, 3810 s. + n = DerethClock.At(RawAt(1905)); + Check(n.IsDay, "Dawnsong: day"); + Eq(n.HourName, "Dawnsong", "Dawnsong: its name"); + Eq(n.SecondsToChange, 3810.0, "Dawnsong: dusk in 63.5 real minutes"); + Eq(n.NextHourName, "Evensong", "by day the night comes at Evensong"); + + // The examples: "Night in 23m", "Day in 4m 10s", "Day in 45s". + n = DerethClock.At(RawAt(5715 - 1380)); + Check(n.IsDay, "23 min before dusk: day"); + Eq(n.HourName, "Midsong-and-Half", "23 min before dusk: hour 9"); + Eq(DerethClock.Label(n, n.SecondsToChange), "Night in 23m", "23 min before dusk"); + n = DerethClock.At(RawAt(5715 - 250)); + Eq(n.HourName, "Warmtide-and-Half", "the last day hour"); + Eq(DerethClock.Label(n, n.SecondsToChange), "Night in 4m 10s", "250 s before dusk"); + n = DerethClock.At(RawAt(1905 - 45)); + Check(!n.IsDay, "45 s before dawn: night"); + Eq(n.HourName, "Foredawn-and-Half", "the last night hour"); + Eq(DerethClock.Label(n, n.SecondsToChange), "Day in 45s", "45 s before dawn"); + + // Dusk itself: night through midnight to the next dawn, 3810 s. + n = DerethClock.At(RawAt(5715)); + Check(!n.IsDay, "Evensong: night"); + Eq(n.HourName, "Evensong", "Evensong: its name"); + Eq(n.SecondsToChange, 3810.0, "Evensong: dawn in 63.5 real minutes (across midnight)"); + Eq(DerethClock.At(RawAt(7000)).SecondsToChange, 7620.0 - 7000 + 1905, "Gloaming: dawn across midnight"); + + // Whole days and the 10-year offset change nothing; a big clock keeps its precision. + Eq(DerethClock.At(RawAt(735, day: 200_000)).SecondsToChange, DerethClock.At(RawAt(735)).SecondsToChange, "a later day: the same"); + + // Not readable yet. + Check(!DerethClock.IsUsable(0), "0: the clock isn't set"); + Check(!DerethClock.IsUsable(double.NaN) && !DerethClock.IsUsable(-5) && !DerethClock.IsUsable(double.PositiveInfinity), "NaN, negative, infinite: not used"); + Check(DerethClock.IsUsable(123456.5), "a real reading is used"); + } + + /// Against RynthAi's own meta expressions (getisday, getgamehour, getminutesuntilday/night), and the countdown's continuity. + private static void ClockMatchesRynthAi() + { + const double hourTicks = 476.25; + const int dayTicks = 7620; + int mismatches = 0, jumps = 0, flips = 0; + DerethNow prev = default; + double prevRaw = 0; + for (double raw = 10_000; raw < 10_000 + 2 * dayTicks; raw += 3.7) + { + // RynthAi (Meta/ExpressionEngine.cs), as it is written there. + double ticks = raw - 210 + hourTicks * 8 + hourTicks * 16 * 30 * 12 * 10; + int hour = (int)(ticks % dayTicks / hourTicks); + bool isDay = hour >= 4 && hour < 12; + double into = ticks % dayTicks; + double untilDay = isDay ? 0 : into < 4 * hourTicks ? 4 * hourTicks - into : dayTicks - into + 4 * hourTicks; + double untilNight = isDay ? 12 * hourTicks - into : 0; + int minutes = (int)((isDay ? untilNight : untilDay) / 60); + + DerethNow n = DerethClock.At(raw); + if (n.Hour != hour || n.IsDay != isDay || (int)(n.SecondsToChange / 60) != minutes) mismatches++; + + if (raw > 10_000) + { + if (n.IsDay != prev.IsDay) + { + flips++; + // The change came when the countdown ran out. + if (prev.SecondsToChange > raw - prevRaw + 1e-6) jumps++; + } + else if (Math.Abs(prev.SecondsToChange - (raw - prevRaw) - n.SecondsToChange) > 1e-6) jumps++; // a second a second + } + prev = n; + prevRaw = raw; + } + Eq(mismatches, 0, "the hour, day or night and the minutes are RynthAi's"); + Eq(jumps, 0, "the countdown falls a second a real second, and the change comes when it runs out"); + Eq(flips, 4, "two days: two dawns and two dusks"); + } + + private static void ClockCountdownText() + { + Eq(DerethClock.Countdown(0), "0s", "0"); + Eq(DerethClock.Countdown(0.2), "1s", "a part second rounds up: never 0s before the change"); + Eq(DerethClock.Countdown(45), "45s", "under a minute: seconds"); + Eq(DerethClock.Countdown(59.5), "1m 0s", "59.5 s rounds up to a minute"); + Eq(DerethClock.Countdown(250), "4m 10s", "under 10 minutes: minutes and seconds"); + Eq(DerethClock.Countdown(599), "9m 59s", "just under 10 minutes"); + Eq(DerethClock.Countdown(600), "10m", "10 minutes: minutes only"); + Eq(DerethClock.Countdown(601), "11m", "over 10 minutes: whole minutes rounded up"); + Eq(DerethClock.Countdown(1380), "23m", "23 minutes"); + Eq(DerethClock.Countdown(3600), "1h 0m", "an hour"); + Eq(DerethClock.Countdown(3810), "1h 4m", "the longest wait: 63.5 minutes"); + Eq(DerethClock.Countdown(-3), "0s", "a stale reading past the change: 0s, not negative"); + } + + private static void ClockWindowAndCommand() + { + // The window counts down from when the tick read the clock. + var v = new DayNightView(true, DerethClock.At(RawAt(5715 - 100)), 1000); + Eq(v.SecondsLeft(1000), 100.0, "at the reading"); + Eq(v.SecondsLeft(3500), 97.5, "2.5 s later"); + Eq(v.SecondsLeft(1_000_000), 0.0, "long after: 0, not negative"); + Check(!DayNightView.NotReady.Ready, "before the world: not ready"); + Eq(DayNightWindow.NotInWorld, "—", "out of world it shows a dash"); + Check(DayNightWindow.Tip(DayNightView.NotReady, 0).Contains("in the world", StringComparison.Ordinal), "tooltip out of world"); + string tip = DayNightWindow.Tip(v, 100); + Check(tip.Contains("Day now (Warmtide-and-Half)", StringComparison.Ordinal) && tip.Contains("Night comes at Evensong, in 1 min 40 s", StringComparison.Ordinal), "tooltip: " + tip); + + // /rdef daynight [show|hide]: parsed, and every answer says what happened. + Eq(DefCommandParser.Parse("daynight").Text, "", "alone: toggle"); + Eq(DefCommandParser.Parse("daynight show").Text, "show", "show"); + Eq(DefCommandParser.Parse("DayNight ON").Text, "show", "on = show, any case"); + Eq(DefCommandParser.Parse("daynight hide").Text, "hide", "hide"); + Eq(DefCommandParser.Parse("daynight off").Text, "hide", "off = hide"); + DefCommand bad = DefCommandParser.Parse("daynight soon"); + Check(bad.Verb == DefVerb.Error && bad.Error.Contains("Usage", StringComparison.Ordinal), "a wrong word: the usage"); + Check(DefCommandParser.Usage.Contains("daynight", StringComparison.Ordinal), "in the usage"); + + DerethNow dusk = DerethClock.At(RawAt(5715)); + Eq(DefReplies.DayNight(1, dusk), (true, "Day/Night timer shown. Night now (Evensong); day in 1h 4m of real time."), "shown, with the time"); + Eq(DefReplies.DayNight(0, null), (true, "Day/Night timer hidden."), "hidden, out of world: no time"); + var old = DefReplies.DayNight(-1, dusk); + Check(!old.Ok && old.Text.Contains("v90", StringComparison.Ordinal) && old.Text.Contains("day in 1h 4m", StringComparison.Ordinal), + "an engine without the window: why, and the time still"); + } + } +} diff --git a/Tools/RynthDefective.Tests/ExtraBarTests.cs b/Tools/RynthDefective.Tests/ExtraBarTests.cs new file mode 100644 index 0000000..d3fc695 --- /dev/null +++ b/Tools/RynthDefective.Tests/ExtraBarTests.cs @@ -0,0 +1,269 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.RynthDefective; +using RynthCore.Plugin.RynthDefective.Items; +using RynthCore.Plugin.RynthDefective.Model; +using RynthCore.Plugin.RynthDefective.ShortcutBar; +using RynthCore.Plugin.RynthDefective.Ui; +using RynthCore.Plugin.RynthDefective.Use; +using RynthCore.Plugin.RynthDefective.Views; + +namespace RynthDefective.Tests +{ + // The extra Shortcuts bars (2026-11-04, ExtraBar): adding and removing them (at most 3, the lowest + // free number), their own slots filled and used like the main bar's own, the character's file, the + // /rdef bars command, what an extra bar's window draws, and the settings window's rows for them. + internal static partial class Program + { + private static void ExtraBarsAddRemoveCap() + { + var d = new DefData(); + Eq(d.ExtraBars.Count, 0, "none by default"); + var numbers = new List(); + for (int i = 0; i < ExtraBar.Max; i++) numbers.Add(d.AddExtraBar()?.Number ?? 0); + Eq(string.Join(",", numbers), "2,3,4", "three bars, numbered 2-4 (the main bar is 1)"); + Check(d.AddExtraBar() == null && d.ExtraBars.Count == ExtraBar.Max, "a fourth is refused: the cap"); + Check(ExtraBar.Max + 5 <= 8, "the cap fits the engine's 8 windows for a plugin (RynthDefective draws 5 others, Day/Night included)"); + Check(d.RemoveExtraBar(3) && d.Extra(3) == null && d.ExtraBars.Count == 2, "remove bar 3"); + Check(!d.RemoveExtraBar(3), "removing it again: nothing to remove"); + Eq(d.AddExtraBar()?.Number, 3, "the next added takes the free number (its window comes back where it was)"); + Eq(string.Join(",", d.ExtraBars.Select(b => b.Number)), "2,3,4", "kept in number order"); + ExtraBar b2 = d.Extra(2)!; + Eq(b2.SlotCount, ExtraBar.DefaultSlots, "10 slots to start"); + Eq(b2.Slots.Count, ExtraBar.SlotsMax, "always 24 slots kept (fewer shown hides them)"); + Eq(b2.Title, "Shortcuts 2", "its window's title"); + Eq(ExtraBar.SurfaceOf(4), "window:bar4", "its surface"); + + // The session's words for it, and the saves. + var rig = new Rig("xbars"); + string m = rig.S.AddBar(out int n); + Check(n == 2 && rig.S.Data.Extra(2) != null && rig.Saves == 1, "session: bar 2 added and saved"); + Check(m.Contains("Shortcuts bar 2 added") && m.Contains("drag items"), "it says how to fill it: " + m); + for (int i = 0; i < 2; i++) rig.S.AddBar(out _); + int saves = rig.Saves; + m = rig.S.AddBar(out n); + Check(n == 0 && rig.Saves == saves && rig.S.Data.ExtraBars.Count == 3, "at the cap: not added, not saved"); + Check(m.Contains("Remove one first") && m.Contains("8 windows"), "and it says why: " + m); + + m = rig.S.RemoveBar(1); + Check(m.Contains("can't be removed") && rig.S.Data.ExtraBars.Count == 3, "bar 1 is the Shortcuts bar itself: " + m); + m = rig.S.RemoveBar(9); + Check(m.StartsWith("There is no Shortcuts bar 9", StringComparison.Ordinal) && m.Contains("Extra Shortcuts bars: 2"), "no such bar: it lists them: " + m); + rig.Inv = new List { Kit(0x7400_0001u) }; + rig.S.SetFromId(1, 0x7400_0001u, bar: 4); + m = rig.S.RemoveBar(4); + Check(rig.S.Data.Extra(4) == null && m.Contains("1 of its slots") && m.Contains("forgotten"), "a bar that held something: says it's forgotten: " + m); + m = rig.S.RemoveBar(3); + Check(m == "Shortcuts bar 3 removed.", "an empty one: " + m); + Check(rig.S.DescribeBars().Contains("2 (10 slots, 0 set)") && !rig.S.DescribeBars().Contains("3 (10 slots") && rig.S.DescribeBars().Contains("2 more can be added"), "the list: " + rig.S.DescribeBars()); + + m = rig.S.SetBarSlots(2, 12); + Check(rig.S.Data.Extra(2)!.SlotCount == 12 && m == "Shortcuts bar 2 shows 12 slots.", "bar 2 shows 12: " + m); + m = rig.S.SetBarSlots(2, 99); + Check(rig.S.Data.Extra(2)!.SlotCount == ExtraBar.SlotsMax && m.Contains("1 to 24"), "too many: the most: " + m); + Check(rig.S.SetBarSlots(7, 3).StartsWith("There is no Shortcuts bar 7", StringComparison.Ordinal), "slots of a bar that isn't there"); + + var none = new Rig("xbars-none"); + Check(none.S.DescribeBars().Contains("/rdef bars add"), "no bars: how to add one"); + } + + private static void ExtraBarsSlots() + { + var rig = new Rig("xbar-slots"); + var kit = Kit(0x7410_0001u); + var potion = Potion(0x7410_0002u); + rig.Inv = new List { kit, potion }; + rig.S.AddBar(out _); + + rig.Selected = kit.Id; + string m = rig.S.SetFromSelected(1, bar: 2); + Check(rig.S.Data.Extra(2)!.Slots[0].Item?.Id == kit.Id && rig.S.Data.Slots[0].Empty, "the selected kit goes in bar 2's slot 1, not the main bar's"); + Check(m.StartsWith("Bar 2 slot 1: Peerless Healing Kit", StringComparison.Ordinal), "named by its bar: " + m); + m = rig.S.SetFromId(3, potion.Id, bar: 2); + Check(rig.S.Data.Extra(2)!.Slots[2].Item?.Id == potion.Id && m.StartsWith("Bar 2 slot 3:", StringComparison.Ordinal), "an item dropped on bar 2's slot 3"); + m = rig.S.SetSpell(2, 1, bar: 2); // the spellbook can't be read here: any spell id goes in + Check(rig.S.Data.Extra(2)!.Slots[1].IsSpell && m.StartsWith("Bar 2 slot 2:", StringComparison.Ordinal), "a spell in bar 2's slot 2: " + m); + Check(rig.S.SetFromId(1, potion.Id, bar: 3).StartsWith("There is no Shortcuts bar 3", StringComparison.Ordinal), "a bar that isn't there"); + Check(rig.S.SetFromId(25, potion.Id, bar: 2) == "Bar 2 has no slot 25.", "a slot past 24"); + Check(rig.S.Data.Slots.All(s => s.Empty), "the main bar's own slots are untouched"); + + // Pressing: through the use controller, as the main bar's own slots. + Check(rig.S.UseSlot(1, bar: 2) == null && rig.S.Use.Pending?.Item?.Id == kit.Id && rig.S.Use.Pending?.Source == "bar 2 slot 1", "a click uses bar 2's kit: " + rig.S.Use.Pending?.Source); + rig.S.Use.Reset(); + Check(rig.S.UseSlot(2, bar: 2) == null && rig.S.Use.Pending?.Spell == 1, "a spell slot casts"); + rig.S.Use.Reset(); + m = rig.S.UseSlot(4, bar: 2)!; + Check(m.StartsWith("Bar 2 slot 4 is empty", StringComparison.Ordinal) && m.Contains("right-click"), "an empty one says how to fill it: " + m); + Check(rig.S.UseSlot(1, bar: 5)!.StartsWith("There is no Shortcuts bar 5", StringComparison.Ordinal), "a bar that isn't there"); + + m = rig.S.ClearSlot(3, bar: 2); + Check(rig.S.Data.Extra(2)!.Slots[2].Empty && m == "Bar 2 slot 3 cleared.", "cleared: " + m); + + // The slots follow their items: the kit used up, the next of its name is the one. + var kit2 = Kit(0x7410_0009u); + rig.Inv = new List { kit2, potion }; + Check(rig.S.Maintain(rig.Inv) && rig.S.Data.Extra(2)!.Slots[0].Item?.Id == kit2.Id, "an extra bar's slot follows its item like the main bar's"); + + // The main bar's own slots still read as before. + Check(rig.S.SetFromId(1, potion.Id) == "Slot 1: Health Potion (used when pressed).", "the main bar's words unchanged: " + rig.S.SetFromId(1, potion.Id)); + Check(rig.S.UseSlot(43) == "There is no slot 43.", "and its limits"); + } + + private static void ExtraBarsStore() + { + var st = new DefStore(Path.Combine(_temp, "xbar-store")); + var d = new DefData(); + ExtraBar a = d.AddExtraBar()!; + a.SlotCount = 12; + a.Slots[0].Item = ItemRef.From(Kit(0x7420_0001u)); + a.Slots[0].Mode = UseMode.OnSelf; + a.Slots[11] = new DefSlot { SpellId = 1, SpellName = "Strength Other I" }; + a.Slots[23].Item = ItemRef.From(Potion(0x7420_0002u)); // past the shown count: kept + d.AddExtraBar(); + ExtraBar c = d.AddExtraBar()!; + c.SlotCount = 3; + d.RemoveExtraBar(3); // bars 2 and 4 are left + d.Slots[0].Item = ItemRef.From(Potion(0x7420_0003u)); + + Check(st.Save("TestServer", "Test", d) == null, "saved"); + DefData r = st.Load("TestServer", "Test", out string? problem); + Check(problem == null, "read back"); + Eq(string.Join(",", r.ExtraBars.Select(b => b.Number)), "2,4", "bars 2 and 4"); + ExtraBar ra = r.Extra(2)!, rc = r.Extra(4)!; + Check(ra.SlotCount == 12 && rc.SlotCount == 3, "their slot counts"); + Check(ra.Slots[0].Item?.Id == 0x7420_0001u && ra.Slots[0].Mode == UseMode.OnSelf, "an item and its mode"); + Check(ra.Slots[11].SpellId == 1 && ra.Slots[11].SpellName.Length > 0, "a spell slot"); + Check(ra.Slots[23].Item?.Id == 0x7420_0002u, "a slot past the shown count is kept"); + Check(ra.Slots.Count == ExtraBar.SlotsMax && rc.Filled == 0, "24 slots each; bar 4 empty"); + Check(r.Slots[0].Item?.Id == 0x7420_0003u, "the main bar's own slots alongside"); + Eq(DefStore.ToJson(r), DefStore.ToJson(d), "the round trip writes the same file"); + + // A file from before the extra bars: none. Odd entries: skipped, clamped, capped. + var old = DefStore.Parse(JsonDocument.Parse("{\"slots\":[]}").RootElement); + Eq(old.ExtraBars.Count, 0, "a file from before has none"); + string odd = "{\"extraBars\":[\"x\", {\"number\":1}, {\"number\":9}, {\"number\":3,\"slotCount\":99,\"slots\":[{\"item\":{\"id\":5,\"name\":\"Arrow\"}}]}," + + "{\"number\":3}, {\"number\":2,\"slotCount\":0}, {\"number\":4,\"slots\":\"none\"}, {\"number\":5}, {\"number\":4}]}"; + DefData o = DefStore.Parse(JsonDocument.Parse(odd).RootElement); + Eq(string.Join(",", o.ExtraBars.Select(b => b.Number)), "2,3,4", "bad numbers (1, 9 and 5) and repeats skipped, sorted, at most 3"); + Check(o.Extra(3)!.SlotCount == ExtraBar.SlotsMax && o.Extra(3)!.Slots[0].Item?.Name == "Arrow", "too many slots: the most; its item read"); + Check(o.Extra(2)!.SlotCount == ExtraBar.SlotsMin, "too few: one"); + Check(o.Extra(4)!.Slots.All(s => s.Empty) && o.Extra(4)!.SlotCount == ExtraBar.DefaultSlots, "slots that aren't a list: empty, the default count"); + } + + private static void ExtraBarsCommands() + { + DefCommand c = DefCommandParser.Parse("bars"); + Check(c.Verb == DefVerb.Bars && c.Text == "list", "/rdef bars lists"); + Check(DefCommandParser.Parse("bars list").Text == "list", "/rdef bars list"); + Check(DefCommandParser.Parse("bars add").Text == "add", "/rdef bars add"); + c = DefCommandParser.Parse("bars remove 3"); + Check(c.Verb == DefVerb.Bars && c.Text == "remove" && c.Slot == 3, "/rdef bars remove 3"); + c = DefCommandParser.Parse("bars slots 2 12"); + Check(c.Verb == DefVerb.Bars && c.Text == "slots" && c.Slot == 2 && c.Count == 12, "/rdef bars slots 2 12"); + c = DefCommandParser.Parse("bars show 4"); + Check(c.Verb == DefVerb.Bars && c.Text == "show" && c.Slot == 4, "/rdef bars show 4"); + Check(DefCommandParser.Parse("bars hide 4").Text == "show", "hide is the same toggle"); + foreach (string wrong in new[] { "bars remove", "bars remove two", "bars slots 2", "bars slots 2 99", "bars slots 2 0", "bars show", "bars frob", "bars add 2" }) + { + c = DefCommandParser.Parse(wrong); + Check(c.Verb == DefVerb.Error && (c.Error.Contains("e.g.", StringComparison.Ordinal) || c.Error.Contains("Usage", StringComparison.Ordinal)), + $"'/rdef {wrong}' answers how it's typed: {c.Error}"); + } + Check(DefCommandParser.Usage.Contains("bars"), "the usage line has it"); + + // The surfaces the engine draws them by. + Check(RynthDefectivePlugin.TryExtraSurface("window:bar2", out int s2) && s2 == 2, "window:bar2 is bar 2"); + Check(RynthDefectivePlugin.TryExtraSurface(ExtraBar.SurfaceOf(4), out int s5) && s5 == 4, "window:bar4 is bar 4"); + foreach (string not in new[] { "window:bar", "window:bar1", "window:bar6", "window:bar22", "window:panels", "window:barx" }) + Check(!RynthDefectivePlugin.TryExtraSurface(not, out _), $"{not} is no extra bar"); + } + + private static void ExtraBarSnapshot() + { + var rig = new Rig("xbar-snap"); + var kit = Kit(0x7430_0001u); + rig.Inv = new List { kit }; + rig.S.AddBar(out _); + rig.S.AddBar(out _); + rig.S.SetFromId(2, kit.Id, bar: 3); + rig.S.SetSpell(5, 1, bar: 3); + + BarSnapshot v = BarSnapshotBuilder.BuildExtra(rig.S, 3, rig.Inv, canCast: true); + Check(v.Ready && v.Bar == 3 && v.Slots.Length == ExtraBar.DefaultSlots, "bar 3: ready, 10 slots"); + Check(v.MinSlots == ExtraBar.SlotsMin && v.MaxSlots == ExtraBar.SlotsMax, "its edit buttons go 1-24"); + Check(v.Slots.All(s => !s.Retail && s.Key.Length == 0 && s.AllKeys.Length == 0), "no game slots, no keys"); + Check(v.Slots[1].ObjectId == kit.Id && v.Slots[1].Count == "28", "slot 2: the kit and its uses left"); + Check(v.Slots[1].Tooltip.Contains("Click: use it on you") && !v.Slots[1].Tooltip.Contains("press the key") && !v.Slots[1].Tooltip.Contains("No key yet"), + "its tooltip: clicks, no keys: " + v.Slots[1].Tooltip); + Check(v.Slots[4].SpellId == 1 && !v.Slots[4].Tooltip.Contains("press the key"), "slot 5: the spell"); + Check(v.Slots[0].Empty && v.Slots[0].Tooltip.Contains("Drag an item"), "an empty slot says how to fill it"); + Eq(string.Join(",", v.Extras.Select(e => e.Number + ":" + e.Filled)), "2:0,3:2", "the bars there are, for the menus"); + Check(v.CanAddBar, "two more can be added"); + rig.S.SetBarSlots(3, 2); + Eq(BarSnapshotBuilder.BuildExtra(rig.S, 3, rig.Inv, true).Slots.Length, 2, "fewer slots shown"); + Check(!BarSnapshotBuilder.BuildExtra(rig.S, 4, rig.Inv, true).Ready, "a bar that isn't there: not ready"); + rig.S.AddBar(out _); + rig.S.AddBar(out _); + Check(!BarSnapshotBuilder.BuildExtra(rig.S, 2, rig.Inv, true).CanAddBar, "at three: no more"); + Check(BarSnapshot.NotReady.Bar == 0 && BarSnapshot.NotReady.MaxSlots == DefSettings.BarSlotsMax, "the main bar's limits by default"); + } + + private static void ExtraBarSettings() + { + var b = new BarRig("xbar-settings"); + var host = new UiHost(); + UiWindow win = host.Add(new UiWindow("RynthDefective/Settings", "Defective Settings") { Visible = true, ShowInBar = false }); + var view = new BarSettingsView(b.S); + var shown = new Dictionary { [BarSettingsView.BarTitle] = true }; + view.WindowShown = t => shown.TryGetValue(t, out bool v) ? v : null; + view.ShowWindow = (t, v) => shown[t] = v; + int adds = 0; + var removed = new List(); + view.AddBar = () => { adds++; b.S.AddBar(out _); }; + view.RemoveBar = n => { removed.Add(n); b.S.RemoveBar(n); }; + void Draw() { win.Begin(); view.Draw(win); win.End(); } + string Text() => Encoding.UTF8.GetString(win.Body); + var w = new Windows("xbar-settings-events"); + w.Host.Add(win); + + Draw(); + ParseAll(host, "settings window with no extra bars", out _); + Check(Text().Contains("More shortcut bars") && Text().Contains("Add a shortcut bar"), "the section and its Add button"); + w.Click(win, "set.xbar.add"); + Eq(adds, 1, "Add a shortcut bar adds one"); + Draw(); + Check(Text().Contains("Shortcuts bar 2: opening..."), "not hosted yet: opening"); + shown[ExtraBar.TitleOf(2)] = false; + Draw(); + ParseAll(host, "settings window with bar 2", out int ops); + Check(ops < 1500, "inside the engine's limits"); + w.SetBool(win, "set.xbar.2.shown", true); + Check(shown[ExtraBar.TitleOf(2)], "its box shows it"); + w.SetInt(win, "set.xbar.2.slots", 15); + Check(b.S.Data.Extra(2)!.SlotCount == 15, "its slider sets its slots"); + w.Click(win, "set.xbar.2.remove"); + Draw(); + Check(Text().Contains("Remove Shortcuts bar 2?") && removed.Count == 0, "Remove asks first"); + w.Click(win, "set.xbar.2.no"); + Draw(); + Check(!Text().Contains("Remove Shortcuts bar 2?") && b.S.Data.Extra(2) != null, "Keep it keeps it"); + w.Click(win, "set.xbar.2.remove"); + Draw(); + w.Click(win, "set.xbar.2.yes"); + Check(removed.SequenceEqual(new[] { 2 }) && b.S.Data.Extra(2) == null, "Remove it removes it"); + + for (int i = 0; i < ExtraBar.Max; i++) b.S.AddBar(out _); + Draw(); + Check(!Text().Contains("Add a shortcut bar") && Text().Contains("as many as there can be"), "at three: no Add button, and why"); + + // An engine without the Shortcuts bar: no section. + shown.Remove(BarSettingsView.BarTitle); + Draw(); + Check(!Text().Contains("More shortcut bars"), "no Shortcuts bar on this engine: no extra bars either"); + } + } +} diff --git a/Tools/RynthDefective.Tests/Program.cs b/Tools/RynthDefective.Tests/Program.cs index e079154..a727033 100644 --- a/Tools/RynthDefective.Tests/Program.cs +++ b/Tools/RynthDefective.Tests/Program.cs @@ -73,6 +73,9 @@ namespace RynthDefective.Tests Run("busy rule with RynthAi holding: its own action and our last use hold, the rest of the count doesn't", BusyRulePaced); Run("use: the player's turn - after a death the press goes next, RynthAi holds and is let go", UsePlayersTurn); Run("use: just after a portal the client takes nothing for a few seconds - the press waits and goes when it can", UseAfterPortal); + Run("busy clear rule: only a count with nothing real in flight is cleared", BusyClearDecisions); + Run("use: shortcuts clear a stuck busy state - off by default, then clear once per press and use", UseClearStuckBusy); + Run("store, command and settings: shortcuts clear a stuck busy state", ClearBusySettingAndCommand); Run("spells: the table's names and flags, the name search", SpellTableAndSearch); Run("spells: whom a cast goes to", SpellCastTarget); Run("spells: a slot casts, Magic mode first, refusals", SpellUse); @@ -98,6 +101,12 @@ namespace RynthDefective.Tests Run("bar: making it independent offers to copy the game's 18 slots", BarIndependentCopy); Run("store: the independent bar setting; files from before read it off", BarStoreIndependent); Run("window: the settings window parses and its switches reach their code", BarSettingsWindow); + Run("extra bars: add and remove, the lowest free number, at most 4", ExtraBarsAddRemoveCap); + Run("extra bars: their own slots filled, used and kept like the main bar's own", ExtraBarsSlots); + Run("store: the extra bars saved and read; files from before and odd ones", ExtraBarsStore); + Run("extra bars: /rdef bars parsing", ExtraBarsCommands); + Run("extra bars: what an extra bar's window draws (no game slots, no keys)", ExtraBarSnapshot); + Run("window: the settings window's rows for the extra bars", ExtraBarSettings); Run("corpses: the server's lines", CorpseLinesParse); Run("corpses: a death, the server's line before or after it, nothing dropped", CorpseDeaths); Run("corpses: a corpse in view is the death beside it, else one found", CorpseSeen); @@ -117,6 +126,10 @@ namespace RynthDefective.Tests Run("quantity: a server's bank - its values, pack + bank, one that can't be read, max", QtyBankRules); Run("quantity: buy and max with no bank, a bank that covers it, one that doesn't, one that can't be read", QtyBankBuy); Run("store: the quantity box setting; files from before read it on", QtyStore); + Run("day/night: day or night, the hour and the real seconds to dawn or dusk", ClockDayNight); + Run("day/night: the same as RynthAi's meta expressions, a countdown with no jumps", ClockMatchesRynthAi); + Run("day/night: the countdown text (23m, 4m 10s, 45s)", ClockCountdownText); + Run("day/night: the window's view and tooltip, /rdef daynight and its answers", ClockWindowAndCommand); } finally { @@ -257,6 +270,20 @@ namespace RynthDefective.Tests Releases++; BotHeldNow = false; } + /// + /// The busy-count resets asked for ("Shortcuts clear a stuck busy state"). CanClear false: an engine + /// without ForceResetBusyCount. ClearLands false: the reset doesn't take. It lands on the next tick. + /// + public int Clears; + public bool CanClear = true, ClearLands = true; + private bool _clearPending; + public bool ClearBusyCount() + { + if (!CanClear) return false; + Clears++; + _clearPending = ClearLands; + return true; + } public int UseDoneSeq { get; set; } = 1; public int CombatMode { get; set; } = Stance.NonCombat; public int RefusalSeq { get; set; } @@ -307,7 +334,11 @@ namespace RynthDefective.Tests return true; } - public void Advance(long ms) => NowMs += ms; + public void Advance(long ms) + { + NowMs += ms; + if (_clearPending) { BusyCount = 0; _clearPending = false; } // the engine resets on the game's next tick + } public void Answer(uint error = 0) { UseDoneSeq++; diff --git a/Tools/RynthDefective.Tests/ReplyTests.cs b/Tools/RynthDefective.Tests/ReplyTests.cs index b0e42bd..71df159 100644 --- a/Tools/RynthDefective.Tests/ReplyTests.cs +++ b/Tools/RynthDefective.Tests/ReplyTests.cs @@ -84,7 +84,7 @@ namespace RynthDefective.Tests { // Wrong words: the parser's error is the reply, with an example or the usage. string[] wrong = { "use", "set", "set x", "set 0", "spell 3", "spell", "clear", "clear x", "bind 3", "bind", "unbind", "unbind x", "slots", "slots 99", - "qty 0", "qty lots", "split 0", "give someone", "give -1", "buy 0 Mana Scarab" }; + "qty 0", "qty lots", "split 0", "give someone", "give -1", "buy 0 Mana Scarab", "bars remove", "bars slots 2", "bars frob", "shortcuts", "shortcuts clearbusy maybe", "daynight later" }; foreach (string w in wrong) { DefCommand c = DefCommandParser.Parse(w); @@ -105,6 +105,9 @@ namespace RynthDefective.Tests ("Stamina Kit", DefVerb.Use), ("corpses", DefVerb.Corpses), ("corpses clear", DefVerb.Corpses), ("qty", DefVerb.Quantity), ("qty 25", DefVerb.Quantity), ("split", DefVerb.Split), ("split 25 into Sack", DefVerb.Split), ("give 10", DefVerb.Give), ("buy 25 Mana Scarab", DefVerb.Buy), ("buy max", DefVerb.Buy), + ("daynight", DefVerb.DayNight), ("daynight show", DefVerb.DayNight), ("daynight hide", DefVerb.DayNight), + ("bars", DefVerb.Bars), ("bars add", DefVerb.Bars), ("bars remove 2", DefVerb.Bars), ("bars slots 2 12", DefVerb.Bars), + ("bars show 3", DefVerb.Bars), ("shortcuts clearbusy on", DefVerb.Shortcuts), ("shortcuts clearbusy", DefVerb.Shortcuts), }; var seen = new HashSet(); foreach (var (typed, verb) in right) diff --git a/Tools/RynthDefective.Tests/RynthDefective.Tests.csproj b/Tools/RynthDefective.Tests/RynthDefective.Tests.csproj index f639768..50a7ff2 100644 --- a/Tools/RynthDefective.Tests/RynthDefective.Tests.csproj +++ b/Tools/RynthDefective.Tests/RynthDefective.Tests.csproj @@ -13,7 +13,8 @@ (RynthCore src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, compiled in from the sibling RynthCore checkout) and that clicks reach the code that drew the button; the quantity box (counts, max and half, a vendor's price and the most you can buy, every refusal, split / give / buy - against a scripted world). + against a scripted world); the Day/Night timer's clock (day or night, the real seconds to the next dawn or + dusk, the countdown text, /rdef daynight). Nothing native is loaded: no AC, no ImGui context. Files go to a temp folder, never C:\Games. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -41,6 +42,8 @@ + + diff --git a/Tools/RynthNav.GraphTests/Program.cs b/Tools/RynthNav.GraphTests/Program.cs index 1b2b04e..37225d4 100644 --- a/Tools/RynthNav.GraphTests/Program.cs +++ b/Tools/RynthNav.GraphTests/Program.cs @@ -10,7 +10,7 @@ using RynthNav.Baker; using RynthNav.Routing; using RynthCore.Plugin.Shared; -internal static class Program +internal static partial class Program { private static int _fails, _asserts; private static void Check(bool cond, string msg) @@ -57,6 +57,7 @@ internal static class Program Run(nameof(RealMeshView), RealMeshView); Run(nameof(DungeonFileAndLayer), DungeonFileAndLayer); Run(nameof(RealDungeons), RealDungeons); + RunRouteMaker(); // RouteMakerTests.cs } finally { try { Directory.Delete(_root, true); } catch { } } Console.WriteLine(); diff --git a/Tools/RynthNav.GraphTests/RouteMakerTests.cs b/Tools/RynthNav.GraphTests/RouteMakerTests.cs new file mode 100644 index 0000000..e0dd70e --- /dev/null +++ b/Tools/RynthNav.GraphTests/RouteMakerTests.cs @@ -0,0 +1,317 @@ +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthNav; +using RynthNav.Routing; + +// The route maker on the navmesh (LoopMaker, TilePathFinder's route maker options), on floors baked here +// and on the real map when it's installed (read only): a loop's points (walkable, out of buildings, away +// from portals, reachable, in an order whose legs don't cross), its legs (round a pond, never through a +// portal's circle, round a building's rooms, off walls), what is dropped and why, and a path through +// given points (each leg walked; a point or a leg that can't be, named). +internal static partial class Program +{ + private static void RunRouteMaker() + { + Run(nameof(LoopOnOpenGround), LoopOnOpenGround); + Run(nameof(LoopLegsGoRoundAPond), LoopLegsGoRoundAPond); + Run(nameof(LoopDropsWhatItCantReach), LoopDropsWhatItCantReach); + Run(nameof(LegsNeverThroughAPortal), LegsNeverThroughAPortal); + Run(nameof(LegsRoundABuildingAndOffWalls), LegsRoundABuildingAndOffWalls); + Run(nameof(PathThroughGivenPoints), PathThroughGivenPoints); + Run(nameof(RealLoopsNearHoltburg), RealLoopsNearHoltburg); + } + + private static double MinGap(IReadOnlyList path, double x, double y) + { + double best = double.MaxValue; + for (int i = 1; i < path.Count; i++) best = Math.Min(best, PortalAvoid.SegmentDistance(x, y, path[i - 1].X, path[i - 1].Y, path[i].X, path[i].Y)); + return best; + } + + /// Does any stretch of the path pass through the box (sampled every half yard)? + private static bool Enters(IReadOnlyList path, double x0, double y0, double x1, double y1) + { + for (int i = 1; i < path.Count; i++) + { + WorldPt a = path[i - 1], b = path[i]; + int n = Math.Max(1, (int)(a.FlatDistance(b) * 2)); + for (int k = 0; k <= n; k++) + { + double x = a.X + (b.X - a.X) * k / n, y = a.Y + (b.Y - a.Y) * k / n; + if (x > x0 && x < x1 && y > y0 && y < y1) return true; + } + } + return false; + } + + private static void CheckLoopRules(LoopMaker.Result r, TilePathFinder mesh, BuildingOutlines? buildings, IReadOnlyList portals, string what) + { + Check(r.Ok && r.Route != null, $"{what}: a loop ({r.Error})"); + if (!r.Ok || r.Route == null) return; + Check(r.Points.Count >= 3 && r.Legs.Count == r.Points.Count, $"{what}: {r.Points.Count} points, a leg from each"); + foreach (WorldPt p in r.Points) + { + Check(mesh.Snap(p, 1.0, out _, out _), $"{what}: point {NavCoords.Fmt(p.Ns, p.Ew)} is on walkable ground"); + if (buildings != null) Check(buildings.Inside(p.X, p.Y, 2.9) < 0, $"{what}: point {NavCoords.Fmt(p.Ns, p.Ew)} is out of every building"); + foreach (PortalAvoid.Spot s in portals) + Check(Math.Sqrt((p.X - s.X) * (p.X - s.X) + (p.Y - s.Y) * (p.Y - s.Y)) >= 20 - 0.01, $"{what}: point 20 yd or more from {s.Name}"); + } + Check(RouteShape.Crossings(r.Points, closed: true) == 0, $"{what}: walked in an order where no two legs cross"); + for (int i = 0; i < r.Legs.Count; i++) + { + List leg = r.Legs[i]; + Check(leg[0].FlatDistance(r.Points[i]) < 1 && leg[^1].FlatDistance(r.Points[(i + 1) % r.Points.Count]) < 2.5, $"{what}: leg {i + 1} joins its two points"); + foreach (PortalAvoid.Spot s in portals) + Check(MinGap(leg, s.X, s.Y) >= s.R - 0.06, $"{what}: leg {i + 1} keeps out of {s.Name}'s circle ({MinGap(leg, s.X, s.Y):F2} yd)"); + } + Check(r.Route.RouteType == NavRouteType.Circular && r.Route.Points.Count >= r.Points.Count, $"{what}: a circular nav, a waypoint at least per point"); + Check(Math.Abs(RouteInfo.Length(r.Route) - r.Yards) < 2, $"{what}: its length is the nav file's ({r.Yards:F0} yd)"); + NavRouteParser back = NavRouteParser.LoadFromLines(r.Route.ToLines()); + Check(back.LoadWarning == null && back.Points.Count == r.Route.Points.Count && back.RouteType == NavRouteType.Circular, $"{what}: RynthAi reads it back"); + } + + private static void LoopOnOpenGround() + { + // 3 x 3 tiles of open ground; a building's outline where the north point would go, a portal where the east one would. + string dir = Bake("loopopen", (0, 0, 576, 576)); + var centre = new WorldPt(288, 288, double.NaN); + var buildings = BuildingOutlines.FromPolygons(new[] { new (double, double)[] { (270, 350), (306, 350), (306, 386), (270, 386) } }); + var portals = new List { new(368, 288, PortalAvoid.MapRadius, "Unwanted Portal") }; + var mesh = new TilePathFinder(dir, null, portals); + var opt = new LoopMaker.LoopOptions { Radius = 80, Points = 8, WallClearance = 1.0 }; + LoopMaker.Result r = LoopMaker.Loop(mesh, centre, opt, buildings, portals); + CheckLoopRules(r, mesh, buildings, portals, "open ground"); + Check(r.Points.Count == 8 && r.DroppedPoints.Count == 0, $"every point placed ({r.Points.Count}, {r.DroppedPoints.Count} dropped)"); + Check(r.Points.All(p => Math.Abs(p.FlatDistance(r.Centre) - 80) < 45), "the points round the circle"); + Check(r.Yards > 2 * Math.PI * 80 * 0.6 && r.Yards < 2 * Math.PI * 80 * 1.3, $"a lap of about the circle ({r.Yards:F0} yd)"); + Console.WriteLine($" open ground: {r.Points.Count} points, {r.Route?.Points.Count} waypoints, {r.Yards:F0} yd a lap, {mesh.TilesRead} tiles"); + + // Default point count, and the order starts north and goes clockwise. + var r2 = LoopMaker.Loop(new TilePathFinder(dir, null, null), centre, new LoopMaker.LoopOptions { Radius = 40 }, null, Array.Empty()); + Check(r2.Ok && r2.Asked == RouteShape.DefaultPoints(40), $"no point count: {RouteShape.DefaultPoints(40)} by default ({r2.Asked})"); + Check(r2.Ok && RouteShape.Bearing(r2.Centre, r2.Points[0]) < 30 && RouteShape.Bearing(r2.Centre, r2.Points[1]) > RouteShape.Bearing(r2.Centre, r2.Points[0]), "north first, clockwise"); + Check(r2.Notes.Any(n => n.Contains("worldmap.vec")), "without building outlines it says so"); + + // No ground at the centre: refused, saying where. + var none = LoopMaker.Loop(new TilePathFinder(dir, null, null), new WorldPt(5000, 5000, double.NaN), opt, null, Array.Empty()); + Check(!none.Ok && none.Error.Contains("navmesh"), "no tiles at the centre: " + none.Error); + } + + private static void LoopLegsGoRoundAPond() + { + // Open ground with a pond (x 300..330, y 340..365) right on the straight leg from the north point to the north-east one. + string dir = Bake("looppond", (0, 0, 576, 340), (0, 340, 300, 576), (330, 340, 576, 576), (300, 365, 330, 576)); + var mesh = new TilePathFinder(dir, null, null); + LoopMaker.Result r = LoopMaker.Loop(mesh, new WorldPt(288, 288, double.NaN), new LoopMaker.LoopOptions { Radius = 80, Points = 8 }, null, Array.Empty()); + CheckLoopRules(r, mesh, null, Array.Empty(), "pond"); + bool anyNear = false; + foreach (List leg in r.Legs) + { + Check(!Enters(leg, 300.5, 340.5, 329.5, 364.5), "no leg walks through the pond"); + anyNear |= Enters(leg, 296, 336, 334, 369); + } + Check(anyNear, "a leg goes round its edge (it was in the way)"); + Check(!Enters(r.Route!.Points.Select(p => WorldPt.FromMap(p.NS, p.EW)).ToList(), 300.5, 340.5, 329.5, 364.5), "nor does the saved route"); + } + + private static void LoopDropsWhatItCantReach() + { + // The main ground ends at x = 375; past 20 yd of water (to 395) an island no walk reaches. + string dir = Bake("loopisland", (0, 0, 375, 576), (395, 0, 576, 576)); + var mesh = new TilePathFinder(dir, null, null); + LoopMaker.Result r = LoopMaker.Loop(mesh, new WorldPt(340, 288, double.NaN), new LoopMaker.LoopOptions { Radius = 100, Points = 8 }, null, Array.Empty()); + CheckLoopRules(r, mesh, null, Array.Empty(), "island"); + Check(r.Points.All(p => p.X < 376), "every point on the main ground"); + Check(r.DroppedPoints.Count >= 1 && r.DroppedPoints.Any(d => d.Why.Contains("not reachable")), $"the east is dropped: {string.Join("; ", r.DroppedPoints.Select(d => d.Why))}"); + Check(r.Points.Count + r.DroppedPoints.Count == 8, "kept + dropped = asked"); + + // Too little ground for a loop: refused, with why. + string tiny = Bake("looptiny", (100, 100, 112, 112)); + var t = LoopMaker.Loop(new TilePathFinder(tiny, null, null), new WorldPt(106, 106, double.NaN), new LoopMaker.LoopOptions { Radius = 60, Points = 6 }, null, Array.Empty()); + Check(!t.Ok && (t.Error.Contains("could be placed") || t.Error.Contains("ground")), "a speck of ground: no loop: " + t.Error); + } + + private static void LegsNeverThroughAPortal() + { + // Two rooms joined only by a corridor 12 yd wide with a portal in the middle of it. + string dir = Bake("portalcorridor", (0, 0, 150, 192), (150, 90, 250, 102), (250, 0, 400, 192)); + var portals = new List { new(200, 96, PortalAvoid.MapRadius, "Blocking Portal") }; + var a = new WorldPt(75, 96, double.NaN); + var b = new WorldPt(325, 96, double.NaN); + + var loose = new TilePathFinder(dir, null, portals); + loose.LoadArea(0, 0, 400, 192); + List? through = loose.Leg(a, b, out string n1); + Check(through != null && MinGap(through, 200, 96) < PortalAvoid.MapRadius, "the plain planner walks through it when there's no way round (saveroute's behaviour, unchanged): " + n1); + + var strict = new TilePathFinder(dir, null, portals) { StrictPortals = true }; + strict.LoadArea(0, 0, 400, 192); + List? none = strict.Leg(a, b, out string note); + Check(none == null && note.Contains("Blocking Portal"), "strict: no leg, and the portal is named: " + note); + var walk = new TilePathFinder(dir, null, portals) { StrictPortals = true, NoGaps = true }; + Check(walk.Walk(a, b, false, out string wn) == null && wn.Contains("Blocking Portal"), "strict walk with no gaps allowed: none either: " + wn); + + // A loop round the first room never uses the corridor, and its legs keep out of the circle. + var room = new TilePathFinder(dir, null, portals); + LoopMaker.Result r = LoopMaker.Loop(room, new WorldPt(75, 96, double.NaN), new LoopMaker.LoopOptions { Radius = 60, Points = 6 }, null, portals); + CheckLoopRules(r, room, null, portals, "beside a portal"); + Check(r.Points.All(p => p.X < 151), "all its points in the first room"); + + // A live portal (one the client sees) counts the same. + var live = new List { new(200, 96, PortalAvoid.LiveRadius, "Live Portal") }; + var liveStrict = new TilePathFinder(dir, null, null, live) { StrictPortals = true }; + liveStrict.LoadArea(0, 0, 400, 192); + Check(liveStrict.Leg(a, b, out string ln) == null && ln.Contains("Live Portal"), "a live portal blocks it too: " + ln); + } + + private static void LegsRoundABuildingAndOffWalls() + { + // Two strips of ground joined by a building (a room with a narrow way in from each strip, the two not + // in line: its floor is navmesh too) and, the long way, a lane at the west end. In line, Recast made + // one thin polygon from strip to strip straight through the room, and a leg's own two polygons are + // always allowed, so a leg along that line couldn't be kept out. + string dir = Bake("building", (0, 0, 384, 60), (0, 132, 384, 192), (0, 60, 30, 132), + (170, 68, 214, 124), (172, 58, 184, 70), (200, 122, 212, 134)); + var a = new WorldPt(300, 30, double.NaN); + var b = new WorldPt(300, 162, double.NaN); + var through = new TilePathFinder(dir, null, null); + through.LoadArea(0, 0, 384, 192); + List? direct = through.Leg(a, b, out _); + Check(direct != null && Enters(direct, 172, 64, 212, 128), "without outlines the leg goes through the building"); + + var outline = BuildingOutlines.FromPolygons(new[] { new (double, double)[] { (168, 62), (216, 62), (216, 130), (168, 130) } }); + var round = new TilePathFinder(dir, null, null) { AvoidArea = (x, y) => outline.Inside(x, y) >= 0 }; + round.LoadArea(0, 0, 384, 192); + List? outside = round.Leg(a, b, out string note); + Check(outside != null && !Enters(outside, 172, 64, 212, 128), "with the outline it goes round by the lane: " + note); + Check(outside != null && outside.Any(p => p.X < 32), "...the west lane"); + // A building that is the only way: through it all the same (keeping off buildings gives way). + string only = Bake("buildingonly", (0, 0, 384, 60), (0, 132, 384, 192), (170, 68, 214, 124), (172, 58, 184, 70), (200, 122, 212, 134)); + var must = new TilePathFinder(only, null, null) { AvoidArea = (x, y) => outline.Inside(x, y) >= 0 }; + must.LoadArea(0, 0, 384, 192); + Check(must.Leg(a, b, out _) != null, "when the building is the only way, through it"); + + // Walls: the corners round the end of the wall come off it by the clearance, onto the ground. + string wall = Bake("wallcorner", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192)); + var from = new WorldPt(100, 20, double.NaN); + var to = new WorldPt(480, 20, double.NaN); + var plain = new TilePathFinder(wall, null, null); + plain.LoadArea(0, 0, 576, 192); + var pushed = new TilePathFinder(wall, null, null) { WallClearance = 1.0 }; + pushed.LoadArea(0, 0, 576, 192); + List? p0 = plain.Leg(from, to, out _), p1 = pushed.Leg(from, to, out _); + Check(p0 != null && p1 != null && p0.Count == p1.Count, "the same corners with and without the clearance"); + if (p0 != null && p1 != null && p0.Count == p1.Count) + { + double moved = 0; + for (int i = 1; i < p0.Count - 1; i++) moved = Math.Max(moved, p0[i].FlatDistance(p1[i])); + Check(moved > 0.9 && moved < 1.1, $"a corner moved by the clearance ({moved:F2} yd)"); + Check(p1.All(p => pushed.Snap(p, 0.2, out _, out _)), "every corner still on walkable ground"); + Check(p0[0].FlatDistance(p1[0]) < 0.01 && p0[^1].FlatDistance(p1[^1]) < 0.01, "the ends never move"); + } + } + + private static void PathThroughGivenPoints() + { + // The wall again: from the south of tile 0 to the south of tile 2 the only way is round the north. + string dir = Bake("pathwall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192), (700, 0, 760, 60)); + BuildGraph(dir, out NavGraph g); + g.BuildComponents(); + var pts = new List { new(100, 20, double.NaN), new(480, 20, double.NaN), new(500, 120, double.NaN) }; + var mesh = new TilePathFinder(dir, g, null) { WallClearance = 1.0 }; + LoopMaker.Result r = LoopMaker.Path(mesh, pts, NavRouteType.Once, 30, Array.Empty()); + Check(r.Ok && r.Legs.Count == 2, $"two legs ({r.Error})"); + Check(r.Ok && r.Legs[0].Any(p => p.Y > 150), "the first goes north through the passage"); + Check(r.Ok && r.Route!.RouteType == NavRouteType.Once && r.Route.Points.Count >= 4, "a once route"); + Check(r.Ok && NavCoords.Distance(r.Route!.Points[0].NS, r.Route.Points[0].EW, pts[0].Ns, pts[0].Ew) < 3 + && NavCoords.Distance(r.Route.Points[^1].NS, r.Route.Points[^1].EW, pts[2].Ns, pts[2].Ew) < 3, "it starts and ends at the given points"); + var back = NavRouteParser.LoadFromLines(r.Route!.ToLines()); + Check(back.LoadWarning == null && back.Points.Count == r.Route.Points.Count, "RynthAi reads it back"); + + var loop = LoopMaker.Path(new TilePathFinder(dir, g, null), pts, NavRouteType.Circular, 30, Array.Empty()); + Check(loop.Ok && loop.Legs.Count == 3 && loop.Route!.RouteType == NavRouteType.Circular, "a loop also walks back from the last point to the first"); + var line = LoopMaker.Path(new TilePathFinder(dir, g, null), pts, NavRouteType.Linear, 30, Array.Empty()); + Check(line.Ok && line.Legs.Count == 2 && line.Route!.RouteType == NavRouteType.Linear, "a line doesn't"); + + // A point with no ground, a leg that can't be walked, a point in a portal's circle: refused, named. + var off = LoopMaker.Path(new TilePathFinder(dir, g, null), new List { pts[0], new(288, 50, double.NaN), pts[1] }, NavRouteType.Once, 30, Array.Empty()); + Check(!off.Ok && off.Error.StartsWith("point 2"), "a point in the gap: " + off.Error); + var island = LoopMaker.Path(new TilePathFinder(dir, g, null), new List { pts[1], new(730, 30, double.NaN) }, NavRouteType.Once, 30, Array.Empty()); + Check(!island.Ok && island.Error.StartsWith("leg 1"), "a leg to an island: " + island.Error); + var portal = new List { new(480, 22, PortalAvoid.MapRadius, "Some Portal") }; + var inPortal = LoopMaker.Path(new TilePathFinder(dir, g, portal), pts, NavRouteType.Once, 30, portal); + Check(!inPortal.Ok && inPortal.Error.StartsWith("point 2") && inPortal.Error.Contains("Some Portal"), "a point at a portal: " + inPortal.Error); + } + + /// Yards of the legs inside building outlines (sampled every half yard). + private static double YardsInBuildings(IEnumerable> legs, BuildingOutlines b) + { + double inside = 0; + foreach (List leg in legs) + for (int i = 1; i < leg.Count; i++) + { + WorldPt p = leg[i - 1], q = leg[i]; + int n = Math.Max(1, (int)(p.FlatDistance(q) * 2)); + for (int k = 0; k < n; k++) + if (b.Inside(p.X + (q.X - p.X) * (k + 0.5) / n, p.Y + (q.Y - p.Y) * (k + 0.5) / n) >= 0) inside += p.FlatDistance(q) / n; + } + return inside; + } + + /// + /// The real map (read only, when it's installed): loops by Holtburg (in town, among its buildings and + /// portals, and out on the open ground east of it) with the real building outlines and the Atlas's + /// portals, with and without keeping the legs off building floors. Prints the sizes and times. + /// + private static void RealLoopsNearHoltburg() + { + string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData"; + if (!File.Exists(Path.Combine(dir, "nav_A9B4.tile"))) { Console.WriteLine(" (no real NavData here: skipped)"); return; } + BuildingOutlines? buildings = BuildingOutlines.Load(Path.Combine(dir, BuildingOutlines.FileName)); + var portals = new List(); + string tsv = Path.Combine(dir, "portals.tsv"); + if (File.Exists(tsv)) + foreach (string line in File.ReadLines(tsv)) + { + string[] f = line.Split('\t'); + if (f.Length < 5 || !double.TryParse(f[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double ns) + || !double.TryParse(f[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double ew)) continue; + portals.Add(new PortalAvoid.Spot(NavCoords.WorldX(ew), NavCoords.WorldY(ns), PortalAvoid.MapRadius, f[4])); + } + Console.WriteLine($" {buildings?.Count ?? 0} building outlines, {portals.Count} portals"); + foreach (var (name, ns, ew, radius) in new[] { ("Holtburg", 42.08, 33.6, 60.0), ("east of Holtburg", 42.0, 34.6, 150.0) }) + { + var sw = System.Diagnostics.Stopwatch.StartNew(); + var near = portals.Where(p => Math.Abs(p.X - NavCoords.WorldX(ew)) < radius + 300 && Math.Abs(p.Y - NavCoords.WorldY(ns)) < radius + 300).ToList(); + var mesh = new TilePathFinder(dir, null, near) { }; + LoopMaker.Result r = LoopMaker.Loop(mesh, WorldPt.FromMap(ns, ew, double.NaN), new LoopMaker.LoopOptions { Radius = radius, WallClearance = 1.0 }, buildings, near); + long ms = sw.ElapsedMilliseconds; + Console.WriteLine($" {name}, {radius:F0} yd: {(r.Ok ? $"{r.Points.Count} of {r.Asked} points, {r.Route?.Points.Count} waypoints, {r.Yards:F0} yd a lap" : r.Error)}, " + + $"{r.DroppedPoints.Count} dropped{(r.DroppedPoints.Count > 0 ? $" ({string.Join("; ", r.DroppedPoints.Select(d => d.Why).Distinct())})" : "")}, {mesh.TilesRead} tiles, {ms} ms"); + CheckLoopRules(r, mesh, buildings, near, name); + Check(ms < 30000, $"{name}: in reasonable time ({ms} ms)"); + if (buildings == null || !r.Ok) continue; + // The same loop with the legs free to cross building floors: they go through at least as much. + LoopMaker.Result free = LoopMaker.Loop(new TilePathFinder(dir, null, near), WorldPt.FromMap(ns, ew, double.NaN), + new LoopMaker.LoopOptions { Radius = radius, WallClearance = 1.0, LegsRoundBuildings = false }, buildings, near); + double kept = YardsInBuildings(r.Legs, buildings), loose = free.Ok ? YardsInBuildings(free.Legs, buildings) : double.NaN; + Console.WriteLine($" legs inside building outlines: {kept:F0} yd kept off them, {loose:F0} yd free ({free.Yards:F0} yd a lap)"); + Check(!free.Ok || kept <= loose + 1, $"{name}: keeping legs off buildings doesn't put more of them inside ({kept:F0} vs {loose:F0} yd)"); + } + + // A path from Holtburg out east and back up north, on the route graph, never through a portal's circle. + string graphFile = Path.Combine(dir, NavGraph.FileName); + if (!File.Exists(graphFile)) return; + NavGraph g = NavGraph.Load(graphFile); + g.BuildComponents(); + var pts = new List { WorldPt.FromMap(42.0, 33.9, double.NaN), WorldPt.FromMap(41.6, 35.2, double.NaN), WorldPt.FromMap(42.4, 35.6, double.NaN) }; + var sw2 = System.Diagnostics.Stopwatch.StartNew(); + var finder = new TilePathFinder(dir, g, portals) { StrictPortals = true, WallClearance = 1.0 }; + LoopMaker.Result p = LoopMaker.Path(finder, pts, NavRouteType.Once, 30, portals); + Console.WriteLine($" a path east of Holtburg: {(p.Ok ? $"{p.Legs.Count} legs, {p.Route?.Points.Count} waypoints, {p.Yards:F0} yd" : p.Error)}, {finder.TilesRead} tiles, {sw2.ElapsedMilliseconds} ms"); + Check(p.Ok && p.Legs.Count == 2, "the real path: two legs " + p.Error); + if (p.Ok) + foreach (List leg in p.Legs) + foreach (PortalAvoid.Spot s in portals.Where(s => Math.Abs(s.X - pts[1].X) < 1000 && Math.Abs(s.Y - pts[1].Y) < 1000)) + Check(MinGap(leg, s.X, s.Y) >= s.R - 0.06, $"the real path keeps out of {s.Name}"); + } +} diff --git a/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj b/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj index 922c46b..c31a253 100644 --- a/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj +++ b/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj @@ -36,6 +36,16 @@ + + + + + + + + + + diff --git a/Tools/RynthNav.RouteTests/Program.cs b/Tools/RynthNav.RouteTests/Program.cs index 36d6958..e9303ef 100644 --- a/Tools/RynthNav.RouteTests/Program.cs +++ b/Tools/RynthNav.RouteTests/Program.cs @@ -61,6 +61,7 @@ internal static partial class Program RunTravelPlan(); RunTripExport(); RunAutoRunGate(); + RunRouteMaker(); RunSteering(); Console.WriteLine(); diff --git a/Tools/RynthNav.RouteTests/RouteMakerTests.cs b/Tools/RynthNav.RouteTests/RouteMakerTests.cs new file mode 100644 index 0000000..579a5e2 --- /dev/null +++ b/Tools/RynthNav.RouteTests/RouteMakerTests.cs @@ -0,0 +1,513 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthNav; +using RynthNav.Routing; + +namespace RynthNav.RouteTests; + +// The route maker's parts that need no navmesh (RynthNavPlugin.RouteMaker.cs): what a /rnav command and +// the "RynthNav.Routes" JSON are read as and what they refuse (RouteRequest), the job table and its +// states (RouteJobTable), a loop's order and the joined legs as a nav file RynthAi reads back +// (RouteShape), what a saved nav is (RouteInfo, on a made-up file and the real NavProfiles when they're +// here, read only), a plan's figures (TripSummary) and the building outlines file (BuildingOutlines). +// The navmesh side (choosing loop points, joining legs) is in RynthNav.GraphTests. +internal static partial class Program +{ + private static void RunRouteMaker() + { + Run(nameof(RouteNameRules), RouteNameRules); + Run(nameof(RouteJsonRequests), RouteJsonRequests); + Run(nameof(RouteJsonRefusals), RouteJsonRefusals); + Run(nameof(RouteChatCommands), RouteChatCommands); + Run(nameof(RouteJobStates), RouteJobStates); + Run(nameof(LoopOrderNoCrossings), LoopOrderNoCrossings); + Run(nameof(LoopNavWrittenAndReadBack), LoopNavWrittenAndReadBack); + Run(nameof(RouteInfoOnASampleFile), RouteInfoOnASampleFile); + Run(nameof(RouteInfoOnRealNavProfiles), RouteInfoOnRealNavProfiles); + Run(nameof(PlanSummaryFigures), PlanSummaryFigures); + Run(nameof(BuildingOutlinesFile), BuildingOutlinesFile); + } + + private static RouteRequest? Json(string json) => RouteRequest.FromJson(json, out _); + + private static string JsonError(string json) + { + RouteRequest? r = RouteRequest.FromJson(json, out string error); + return r == null ? error : ""; + } + + // ── Names ──────────────────────────────────────────────────────────── + + private static void RouteNameRules() + { + // saveroute's rules, the same for every make op: chat and JSON. + Check(RouteRequest.FromCommand("makeloop", "Hunt 1 radius 50", out _)?.Name == "Hunt 1", "a plain name"); + Check(RouteRequest.FromCommand("makeloop", "Hunt 1.nav radius 50", out _)?.Name == "Hunt 1", ".nav is dropped"); + Check(RouteRequest.FromCommand("makeloop", "a\\b radius 50", out string e1) == null && e1.Contains("file name"), "a path isn't a name: " + e1); + Check(RouteRequest.FromCommand("makeloop", "a:b radius 50", out _) == null, "nor characters a file can't have"); + Check(RouteRequest.FromCommand("makeloop", ".. radius 50", out _) == null, "nor .."); + Check(RouteRequest.FromCommand("makeloop", new string('x', 101) + " radius 50", out _) == null, "nor over 100 characters"); + Check(RouteRequest.FromCommand("routeinfo", "", out string e2) == null && e2.Length > 0, "routeinfo needs a name"); + Check(Json("{\"op\":\"info\",\"name\":\"../x\"}") == null, "JSON: a path is refused too"); + Check(Json("{\"op\":\"makeloop\",\"name\":\"\",\"radius\":50}") == null, "JSON: an empty name is refused"); + Check(Json("{\"op\":\"makeloop\",\"name\":\"Loop A\",\"radius\":50}")?.Overwrite == false, "never overwrite unless asked"); + Check(Json("{\"op\":\"makeloop\",\"name\":\"Loop A\",\"radius\":50,\"overwrite\":true}")?.Overwrite == true, "overwrite: true asks"); + Check(RouteRequest.FromCommand("makeloop", "Loop A radius 50 overwrite", out _)?.Overwrite == true, "chat: overwrite at the end"); + Check(RouteRequest.FromCommand("makeloop", "Loop A radius 50", out _)?.Overwrite == false, "chat: not without it"); + + // An existing file stays unless overwrite (the same NavRouteExport.Save the jobs use). + string dir = Path.Combine(Path.GetTempPath(), "rnav-maker-" + Guid.NewGuid().ToString("N")); + try + { + var a = new NavRouteParser { RouteType = NavRouteType.Circular }; + a.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1, EW = 1 }); + a.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1.1, EW = 1 }); + Check(NavRouteExport.Save(dir, "Loop A", a, false, out string file, out _, out _), "a new loop is written"); + var b = new NavRouteParser { RouteType = NavRouteType.Once }; + b.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 5, EW = 5 }); + Check(!NavRouteExport.Save(dir, "Loop A", b, false, out _, out bool exists, out _) && exists, "the same name: refused"); + Check(NavRouteParser.Load(file).RouteType == NavRouteType.Circular, "and the file is the first one still"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + // ── JSON in ────────────────────────────────────────────────────────── + + private static void RouteJsonRequests() + { + RouteRequest? p = Json("{\"op\":\"plan\",\"to\":\"Holtburg\",\"portals\":true}"); + Check(p != null && p.Op == RouteOp.Plan && p.To == "Holtburg" && p.Portals == true && !p.Show && !p.FromChat, "plan to a place, portals on"); + RouteRequest? pc = Json("{\"op\":\"plan\",\"to\":{\"ns\":42.1234,\"ew\":-33.5}}"); + Check(pc != null && pc.Portals == null, "plan without portals: the switch"); + Check(pc != null && NavCoords.TryParseLoc(pc.To, out double tns, out double tew) && Math.Abs(tns - 42.1234) < 1e-9 && Math.Abs(tew + 33.5) < 1e-9, + "coordinates kept exactly as text /rnav go reads: " + pc?.To); + + RouteRequest? mr = Json("{\"op\":\"makeroute\",\"name\":\"To Holtburg\",\"to\":\"Holtburg\",\"overwrite\":true,\"show\":true}"); + Check(mr != null && mr.Op == RouteOp.MakeRoute && mr.Name == "To Holtburg" && mr.Overwrite && mr.Show, "makeroute"); + + RouteRequest? ml = Json("{\"op\":\"makeloop\",\"name\":\"Hunt\",\"radius\":80,\"points\":8}"); + Check(ml != null && ml.Op == RouteOp.MakeLoop && ml.Here && ml.Radius == 80 && ml.Points == 8, "makeloop here (no at)"); + RouteRequest? mla = Json("{\"op\":\"makeloop\",\"name\":\"Hunt\",\"at\":{\"ns\":10.5,\"ew\":-20.25},\"radius\":20}"); + Check(mla != null && !mla.Here && mla.AtNs == 10.5 && mla.AtEw == -20.25 && mla.Points == 0, "makeloop at coordinates, default points"); + RouteRequest? mls = Json("{\"op\":\"makeloop\",\"name\":\"Hunt\",\"at\":\"10.5N, 20.25W\",\"radius\":250}"); + Check(mls != null && !mls.Here && mls.AtNs == 10.5 && mls.AtEw == -20.25, "makeloop at a coordinate string, radius at the cap"); + Check(Json("{\"op\":\"makeloop\",\"name\":\"Hunt\",\"at\":\"here\",\"radius\":20}")?.Here == true, "at here"); + + RouteRequest? mp = Json("{\"op\":\"makepath\",\"name\":\"Ridge\",\"type\":\"loop\",\"points\":[{\"ns\":1,\"ew\":2},\"1.1N, 2.1E\",{\"ns\":1.2,\"ew\":2}]}"); + Check(mp != null && mp.PathType == NavRouteType.Circular && mp.Path.Count == 3 && mp.Path[1] == (1.1, 2.1), "makepath loop with mixed points"); + Check(Json("{\"op\":\"makepath\",\"name\":\"R\",\"type\":\"line\",\"points\":[\"1N 1E\",\"1.1N 1E\"]}")?.PathType == NavRouteType.Linear, "type line = linear"); + Check(Json("{\"op\":\"makepath\",\"name\":\"R\",\"points\":[\"1N 1E\",\"1.1N 1E\"]}")?.PathType == NavRouteType.Once, "no type = once"); + + RouteRequest? at = Json("{\"op\":\"atlas\",\"search\":\" holt \",\"max\":5}"); + Check(at != null && at.Search == "holt" && at.Max == 5, "atlas"); + Check(Json("{\"op\":\"atlas\",\"search\":\"holt\"}")?.Max == RouteLimits.DefaultAtlas, "atlas: max defaults"); + Check(Json("{\"op\":\"info\",\"name\":\"Hunt.nav\"}")?.Name == "Hunt", "info"); + Check(Json("{\"op\":\"go\",\"to\":\"Holtburg\"}")?.Op == RouteOp.Go, "go"); + Check(Json("{\"op\":\"stop\"}")?.Op == RouteOp.Stop && Json("{\"op\":\"WHERE\"}")?.Op == RouteOp.Where, "stop, where (any case)"); + Check(Json("{\"op\":\"where\",\"something\":\"new\"}") != null, "unknown fields are ignored"); + } + + private static void RouteJsonRefusals() + { + string[] bad = + { + "", " ", "not json", "[1,2]", "{}", "{\"op\":3}", "{\"op\":\"teleport\"}", + "{\"op\":\"plan\"}", "{\"op\":\"plan\",\"to\":\"\"}", "{\"op\":\"plan\",\"to\":5}", "{\"op\":\"plan\",\"to\":{\"ns\":1}}", + "{\"op\":\"plan\",\"to\":{\"ns\":200,\"ew\":1}}", "{\"op\":\"plan\",\"to\":\"150N, 2E\"}", "{\"op\":\"plan\",\"to\":\"X\",\"portals\":\"yes\"}", + "{\"op\":\"makeroute\",\"to\":\"X\"}", "{\"op\":\"makeroute\",\"name\":\"A\"}", + "{\"op\":\"makeloop\",\"name\":\"A\"}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":\"80\"}", + "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":19}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":251}", + "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"points\":2}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"points\":17}", + "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"points\":4.5}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"at\":\"there\"}", + "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"at\":{\"ns\":1,\"ew\":-300}}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"overwrite\":1}", + "{\"op\":\"makepath\",\"name\":\"A\",\"points\":[\"1N 1E\"]}", "{\"op\":\"makepath\",\"name\":\"A\",\"points\":\"1N 1E; 2N 2E\"}", + "{\"op\":\"makepath\",\"name\":\"A\",\"type\":\"zigzag\",\"points\":[\"1N 1E\",\"2N 2E\"]}", + "{\"op\":\"makepath\",\"name\":\"A\",\"points\":[\"1N 1E\",\"somewhere\"]}", + "{\"op\":\"makepath\",\"name\":\"A\",\"points\":[\"1N 1E\",\"90N 90E\"]}", + "{\"op\":\"atlas\"}", "{\"op\":\"atlas\",\"search\":\" \"}", "{\"op\":\"atlas\",\"search\":\"a\",\"max\":0}", "{\"op\":\"atlas\",\"search\":\"a\",\"max\":51}", + "{\"op\":\"info\"}", "{\"op\":\"go\"}", + }; + foreach (string b in bad) + { + string why = JsonError(b); + Check(why.Length > 0, $"refused: {b}"); + } + var many = new System.Text.StringBuilder("{\"op\":\"makepath\",\"name\":\"A\",\"points\":["); + for (int i = 0; i < RouteLimits.MaxPathPoints + 1; i++) many.Append(i > 0 ? "," : "").Append("{\"ns\":1,\"ew\":").Append(1 + i * 0.01).Append('}'); + Check(JsonError(many.Append("]}").ToString()).Contains("too many"), "33 points: too many"); + Check(JsonError("{\"op\":\"where\",\"pad\":\"" + new string('x', RouteLimits.MaxJson) + "\"}").Contains("characters"), "a request over 16 KB"); + Check(JsonError("{\"op\":\"teleport\"}").Contains("makeloop"), "an unknown op lists the ones there are"); + Check(JsonError("{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":300}").Contains("20-250"), "out of range says the range"); + Check(RouteRequest.UsageFor("{\"op\":\"makeloop\"}").Contains("\"radius\""), "the usage for a known op is its JSON form"); + Check(RouteRequest.UsageFor("junk").Contains("makepath"), "...and the op list otherwise"); + string err = RouteJson.Error("why \"quoted\"", "use \\ this"); + using JsonDocument d = JsonDocument.Parse(err); + Check(d.RootElement.GetProperty("error").GetString() == "why \"quoted\"" && d.RootElement.GetProperty("usage").GetString() == "use \\ this", "the refusal is valid JSON, escaped"); + } + + // ── Chat in ────────────────────────────────────────────────────────── + + private static void RouteChatCommands() + { + RouteRequest? a = RouteRequest.FromCommand("makeroute", "To Town to Holtburg", out string e0); + Check(a != null && a.Op == RouteOp.MakeRoute && a.Name == "To Town" && a.To == "Holtburg" && a.FromChat && a.Show, "makeroute to : " + e0); + RouteRequest? b = RouteRequest.FromCommand("makeroute", "Cragstone run to Portal to Cragstone overwrite", out _); + Check(b != null && b.Name == "Cragstone run" && b.To == "Portal to Cragstone" && b.Overwrite, "the first \" to \" ends the name; overwrite at the end"); + RouteRequest? c = RouteRequest.FromCommand("makeroute", "\"Go to the hill\" to 42.1N, 33.6E", out _); + Check(c != null && c.Name == "Go to the hill" && c.To == "42.1N, 33.6E", "a quoted name may hold \" to \""); + Check(RouteRequest.FromCommand("makeroute", "Holtburg", out string e1) == null && e1.Contains(" to "), "makeroute without to: refused"); + Check(RouteRequest.FromCommand("makeroute", "A to 150N, 2E", out _) == null, "makeroute to coordinates off the map: refused"); + + RouteRequest? l1 = RouteRequest.FromCommand("makeloop", "Hunt at the lake radius 60", out _); + Check(l1 != null && l1.Name == "Hunt at the lake" && l1.Here && l1.Radius == 60 && l1.Points == 0, "a name with 'at' in it, round here"); + RouteRequest? l2 = RouteRequest.FromCommand("makeloop", "Hunt at 42.1N, 33.6E radius 80 points 6 overwrite", out string e2); + Check(l2 != null && l2.Name == "Hunt" && !l2.Here && l2.AtNs == 42.1 && l2.AtEw == 33.6 && l2.Radius == 80 && l2.Points == 6 && l2.Overwrite, "at coords, points, overwrite: " + e2); + RouteRequest? l3 = RouteRequest.FromCommand("makeloop", "Hunt radius 40 at 1.5S 2.5W", out _); + Check(l3 != null && !l3.Here && l3.AtNs == -1.5 && l3.AtEw == -2.5, "the options in any order"); + RouteRequest? l4 = RouteRequest.FromCommand("makeloop", "Hunt here radius 40", out _); + Check(l4 != null && l4.Here && l4.Name == "Hunt", "here"); + Check(RouteRequest.FromCommand("makeloop", "Hunt", out string e3) == null && e3.Contains("radius"), "no radius: refused (" + e3 + ")"); + Check(RouteRequest.FromCommand("makeloop", "Hunt radius 500", out string e4) == null && e4.Contains("20-250"), "radius over the cap: refused (" + e4 + ")"); + Check(RouteRequest.FromCommand("makeloop", "Hunt radius 50 points 40", out string e5) == null && e5.Contains("3-16"), "too many points: refused"); + Check(RouteRequest.FromCommand("makeloop", "Hunt radius fifty", out _) == null, "radius not a number: refused"); + Check(RouteRequest.FromCommand("makeloop", "Hunt at 999N 2E radius 50", out string e6) == null && e6.Contains("off the map"), "at coordinates off the map: refused (" + e6 + ")"); + RouteRequest? l5 = RouteRequest.FromCommand("makeloop", "Hunt at nowhere radius 50", out _); + Check(l5 != null && l5.Name == "Hunt at nowhere" && l5.Here, "'at' followed by words, not coordinates, is part of the name"); + Check(RouteRequest.FromCommand("makeloop", "radius 50", out _) == null, "no name: refused"); + RouteRequest? lq = RouteRequest.FromCommand("makeloop", "\"Hunt at 42N 33E\" radius 60 overwrite", out string eq); + Check(lq != null && lq.Name == "Hunt at 42N 33E" && lq.Here && lq.Radius == 60 && lq.Overwrite, "a quoted name holds anything: " + eq); + Check(RouteRequest.FromCommand("makeloop", "\"Hunt radius 60", out string eq2) == null && eq2.Contains("quote"), "an unclosed quote: refused"); + + RouteRequest? p1 = RouteRequest.FromCommand("makepath", "Ridge walk loop 42.1N 33.6E; 42.3N, 33.9E; 42.0N 34.0E overwrite", out string e7); + Check(p1 != null && p1.Name == "Ridge walk" && p1.PathType == NavRouteType.Circular && p1.Path.Count == 3 && p1.Overwrite + && p1.Path[0] == (42.1, 33.6) && p1.Path[2] == (42.0, 34.0), "makepath name, type, points, overwrite: " + e7); + RouteRequest? p2 = RouteRequest.FromCommand("makepath", "Route 1 42 33; 42.1 33.1", out _); + Check(p2 != null && p2.Name == "Route 1" && p2.PathType == NavRouteType.Once && p2.Path.Count == 2, "a number in the name; no type = once"); + RouteRequest? p3 = RouteRequest.FromCommand("makepath", "Back and forth line 1N 1E; 1.1N 1E;", out _); + Check(p3 != null && p3.PathType == NavRouteType.Linear && p3.Path.Count == 2, "line; a trailing ; is fine"); + Check(RouteRequest.FromCommand("makepath", "Solo 1N 1E", out string e8) == null && e8.Contains("at least"), "one point: refused"); + Check(RouteRequest.FromCommand("makepath", "Bad 1N 1E; up the hill", out string e9) == null && e9.Contains("point 2"), "a point that isn't coordinates: refused, naming it"); + Check(RouteRequest.FromCommand("makepath", "Far 0N 0E; 80N 80E", out string e10) == null && e10.Contains("leg 1"), "a leg too long: refused, naming it"); + Check(RouteRequest.FromCommand("makepath", "Nothing", out _) == null, "no points: refused"); + RouteRequest? pq = RouteRequest.FromCommand("makepath", "\"Ridge, east\" loop 1N 1E; 1.1N 1E", out string e11); + Check(pq != null && pq.Name == "Ridge, east" && pq.PathType == NavRouteType.Circular && pq.Path.Count == 2, "makepath with a quoted name: " + e11); + + Check(RouteRequest.FromCommand("routeinfo", "Hunt", out _)?.Op == RouteOp.Info, "routeinfo"); + Check(RouteRequest.FromCommand("routeinfo", "\"Hunt\" extra", out _) == null, "routeinfo takes only the name"); + Check(RouteRequest.Usage(RouteOp.MakeLoop, chat: true).StartsWith("/rnav makeloop"), "the chat usage line"); + } + + // ── Jobs ───────────────────────────────────────────────────────────── + + private static void RouteJobStates() + { + var t = new RouteJobTable(5000); + RouteJob? j1 = t.Add(Json("{\"op\":\"where\"}")!, 100, out string err); + Check(j1 != null && j1.Id == 5000 && j1.State == RouteJobState.Queued && err == "", "a new job is queued, with the first id"); + RouteJob? j2 = t.Add(Json("{\"op\":\"stop\"}")!, 100, out _); + Check(j2 != null && j2.Id == 5001, "ids go up"); + Check(t.Queued().Count == 2 && t.Queued()[0] == j1, "the queue, oldest first"); + + using (JsonDocument a = JsonDocument.Parse(t.Accepted(j1!))) + Check(a.RootElement.GetProperty("id").GetInt32() == 5000 && a.RootElement.GetProperty("state").GetString() == "queued" + && a.RootElement.GetProperty("op").GetString() == "where" && a.RootElement.GetProperty("result").ValueKind == JsonValueKind.Null, + "Request's answer: id, op, queued, no result yet"); + + t.Start(j1!, "working on it", 110); + using (JsonDocument w = JsonDocument.Parse(t.PollJson(5000, out bool known))) + Check(known && w.RootElement.GetProperty("state").GetString() == "working" && w.RootElement.GetProperty("detail").GetString() == "working on it", "working"); + t.Update(j1!, "nearly", "{\"partial\":1}"); + t.Finish(j1!, true, "done it", "{\"answer\":42}", 120); + using (JsonDocument d = JsonDocument.Parse(t.PollJson(5000, out _))) + Check(d.RootElement.GetProperty("state").GetString() == "done" && d.RootElement.GetProperty("result").GetProperty("answer").GetInt32() == 42, "done, with the result"); + t.Finish(j1!, false, "changed my mind", null, 130); + Check(j1!.State == RouteJobState.Done && j1.Detail == "done it", "a finished job stays as it ended"); + t.Start(j1, "again", 140); + Check(j1.State == RouteJobState.Done, "...and can't be started again"); + + t.Finish(j2!, false, "no player position yet", RouteJson.Error("no player position yet", ""), 150); + using (JsonDocument f = JsonDocument.Parse(t.PollJson(5001, out _))) + Check(f.RootElement.GetProperty("state").GetString() == "failed" && f.RootElement.GetProperty("result").GetProperty("error").GetString() == "no player position yet", "failed, with why"); + using (JsonDocument u = JsonDocument.Parse(t.PollJson(4999, out bool k2))) + Check(!k2 && u.RootElement.GetProperty("state").GetString() == "unknown" && u.RootElement.GetProperty("error").GetString()!.Length > 0, "an id never given: unknown"); + + // The last 32: finished jobs make room, oldest first; 32 unfinished refuse a 33rd. + var full = new RouteJobTable(1); + var first = full.Add(Json("{\"op\":\"where\"}")!, 0, out _)!; + full.Finish(first, true, "ok", null, 1); + for (int i = 1; i < RouteJobTable.Capacity; i++) full.Add(Json("{\"op\":\"where\"}")!, i, out _); + Check(full.Count == RouteJobTable.Capacity, "32 kept"); + RouteJob? next = full.Add(Json("{\"op\":\"where\"}")!, 99, out _); + Check(next != null && full.Get(first.Id) == null && full.Count == RouteJobTable.Capacity, "the 33rd drops the oldest finished job"); + RouteJob? refused = full.Add(Json("{\"op\":\"where\"}")!, 100, out string why); + Check(refused == null && why.Contains("32"), "with all 32 unfinished, a new one is refused: " + why); + Check(!full.PollJson(first.Id, out bool gone).Contains("\"done\"") && !gone, "a dropped job is unknown"); + Check(RouteJobTable.StateName(RouteJobState.Working) == "working" && RouteJobTable.StateName(RouteJobState.Failed) == "failed", "state names"); + + // A go job's end, from the goto's own lines (FinishGoto, Entrance, a stop). + Check(RouteJobTable.GoOutcome("arrived", out string o1) && o1 == "arrived", "arrived: done"); + Check(RouteJobTable.GoOutcome(Entrance.ArrivedText("Matron Hive", "Dungeon"), out string o2) && o2 == "arrived", "into a dungeon: arrived"); + Check(RouteJobTable.GoOutcome(Entrance.ArrivedText("Portal to X", "Portal"), out string o3) && o3 == "arrived", "through a portal: arrived"); + Check(RouteJobTable.GoOutcome("stopped", out string o4) && o4 == "stopped", "a stop: done, stopped"); + Check(!RouteJobTable.GoOutcome("stopped: no progress for 30 s, 12u short (off navmesh)", out string o5) && o5 == "failed", "the watchdog: failed"); + Check(!RouteJobTable.GoOutcome(Entrance.NoTeleportText("Matron Hive"), out _), "a portal that didn't take you in: failed"); + Check(!RouteJobTable.GoOutcome("stopped: logged out", out _) && !RouteJobTable.GoOutcome("recall step lost — stopped", out _), "logged out, a lost recall: failed"); + } + + // ── Loops: order and the nav file ──────────────────────────────────── + + private static void LoopOrderNoCrossings() + { + var c = new WorldPt(5000, 5000, 0); + var rnd = new Random(7); + for (int trial = 0; trial < 50; trial++) + { + int n = 3 + rnd.Next(14); + var pts = new List(); + for (int i = 0; i < n; i++) + { + double a = rnd.NextDouble() * 2 * Math.PI, r = 30 + rnd.NextDouble() * 120; + pts.Add(new WorldPt(c.X + Math.Sin(a) * r, c.Y + Math.Cos(a) * r, 0)); + } + int[] order = RouteShape.OrderLoop(pts, c); + Check(order.Length == n && order.Distinct().Count() == n, $"trial {trial}: every point once"); + var loop = order.Select(i => pts[i]).ToList(); + Check(RouteShape.Crossings(loop, closed: true) == 0, $"trial {trial}: no two legs cross ({n} points)"); + } + // A star-shaped set given in a tangled order comes out round the centre, from the north, clockwise. + var star = new List { new(5100, 5000, 0), new(4900, 5000, 0), new(5000, 5100, 0), new(5000, 4900, 0) }; // E, W, N, S + int[] o = RouteShape.OrderLoop(star, c); + Check(o.SequenceEqual(new[] { 2, 0, 3, 1 }), "N, E, S, W: " + string.Join(",", o)); + Check(RouteShape.Crossings(new List { new(0, 0, 0), new(10, 10, 0), new(10, 0, 0), new(0, 10, 0) }, closed: true) == 1, "a bow tie crosses once"); + Check(RouteShape.DefaultPoints(20) == 4 && RouteShape.DefaultPoints(80) == 11 && RouteShape.DefaultPoints(250) == 12, "default points: about one per 45 yd, 4 to 12"); + } + + private static void LoopNavWrittenAndReadBack() + { + // Three legs round a triangle, the last back to the start; corners and heights along them. + WorldPt a = WorldPt.FromMap(10, 10, 50), b = WorldPt.FromMap(10.3, 10, 52), cc = WorldPt.FromMap(10.15, 10.3, 51); + List Leg(WorldPt p, WorldPt q) + { + var l = new List(); + for (int i = 0; i <= 40; i++) { double t = i / 40.0; l.Add(new WorldPt(p.X + (q.X - p.X) * t + Math.Sin(t * Math.PI) * 6, p.Y + (q.Y - p.Y) * t, p.H + (q.H - p.H) * t)); } + return l; + } + var legs = new List> { Leg(a, b), Leg(b, cc), Leg(cc, a) }; + NavRouteParser route = RouteShape.Assemble(legs, NavRouteType.Circular, RouteShape.LoopSpacing, out double yards); + Check(route.RouteType == NavRouteType.Circular, "a circular route"); + Check(NavCoords.Distance(route.Points[0].NS, route.Points[0].EW, a.Ns, a.Ew) < 0.01, "it starts at the first point"); + Check(NavCoords.Distance(route.Points[^1].NS, route.Points[^1].EW, a.Ns, a.Ew) > 1, "and doesn't repeat it at the end (RynthAi walks back to it)"); + Check(route.Points.All(p => p.Type == NavPointType.Point), "all walking points"); + double gap = 0; + for (int i = 0; i < route.Points.Count; i++) + { + NavPoint p = route.Points[i], q = route.Points[(i + 1) % route.Points.Count]; + gap = Math.Max(gap, NavCoords.Distance(p.NS, p.EW, q.NS, q.EW)); + } + Check(gap <= RouteShape.LoopSpacing + 0.5, $"a point at least every {RouteShape.LoopSpacing} yd ({gap:F1})"); + Check(route.Points.Count < 3 * 41, "thinned, not every input point"); + Check(route.Points.All(p => p.Z > 49.0 / 240 && p.Z < 53.0 / 240), "heights as nav Z (metres / 240)"); + Check(Math.Abs(yards - RouteInfo.Length(route)) < 1.0, $"its yards are the file's walking length, the lap closed ({yards:F1} / {RouteInfo.Length(route):F1})"); + + string dir = Path.Combine(Path.GetTempPath(), "rnav-loop-" + Guid.NewGuid().ToString("N")); + try + { + Check(NavRouteExport.Save(dir, "Triangle", route, false, out string file, out _, out string err), "saved: " + err); + NavRouteParser back = NavRouteParser.Load(file); + Check(back.LoadWarning == null && back.RouteType == NavRouteType.Circular && back.Points.Count == route.Points.Count, "RynthAi's reader takes it whole"); + bool same = true; + for (int i = 0; i < back.Points.Count; i++) + same &= back.Points[i].Type == NavPointType.Point && Math.Abs(back.Points[i].NS - route.Points[i].NS) < 1e-9 + && Math.Abs(back.Points[i].EW - route.Points[i].EW) < 1e-9 && Math.Abs(back.Points[i].Z - route.Points[i].Z) < 1e-9; + Check(same, "every point the same after the round trip"); + string[] lines = File.ReadAllLines(file); + Check(lines[0] == "uTank2 NAV 1.2" && lines[1] == "1" && lines[2] == route.Points.Count.ToString(), "the VTank header: type 1 (circular), the count"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + + // Once and linear keep both ends. + var once = RouteShape.Assemble(new List> { Leg(a, b) }, NavRouteType.Once, 30, out _); + Check(NavCoords.Distance(once.Points[^1].NS, once.Points[^1].EW, b.Ns, b.Ew) < 0.01 && once.RouteType == NavRouteType.Once, "once ends at the last point"); + } + + // ── routeinfo ──────────────────────────────────────────────────────── + + private static void RouteInfoOnASampleFile() + { + // A trip: walk 3 points, a recall, walk 2, a portal, walk 2 more (in a dungeon landblock), a chat and a pause. + var r = new NavRouteParser { RouteType = NavRouteType.Once }; + void P(NavPointType t, double ns, double ew, Action? f = null) { var p = new NavPoint { Type = t, NS = ns, EW = ew }; f?.Invoke(p); r.Points.Add(p); } + P(NavPointType.Point, 10.0, 10.0); P(NavPointType.Point, 10.1, 10.0); P(NavPointType.Point, 10.1, 10.1); + P(NavPointType.Recall, 10.1, 10.1, p => p.SpellId = 1635); + P(NavPointType.Point, 40.0, 40.0); P(NavPointType.Point, 40.0, 40.2); + P(NavPointType.PortalNPC, 40.0, 40.25, p => { p.TargetName = "Portal to Somewhere"; p.ObjectClass = 14; }); + P(NavPointType.Point, 61.87, -100.98); P(NavPointType.Point, 61.88, -100.97); + P(NavPointType.Chat, 61.88, -100.97, p => p.ChatCommand = "@lifestone"); + P(NavPointType.Pause, 61.88, -100.97, p => p.PauseTimeMs = 20000); + uint dunLb = WorldPt.FromMap(61.87, -100.98).Landblock; + string dir = Path.Combine(Path.GetTempPath(), "rnav-info-" + Guid.NewGuid().ToString("N")); + try + { + Check(NavRouteExport.Save(dir, "Sample", r, false, out string file, out _, out _), "the sample is written"); + NavRouteParser back = NavRouteParser.Load(file); + RouteInfo info = RouteInfo.Describe(back, "Sample", file, lb => lb == dunLb, true, 10.0, 10.05, + id => id == 1635 ? "Lifestone Recall" : null); + Check(info.Type == "once" && info.Points == 11, "type and points"); + Check(info.Waypoints == 7 && info.Recalls == 1 && info.Portals == 1 && info.Chats == 1 && info.Pauses == 1, "the points by kind"); + // Walks: 10.0->10.1 (24 yd), 10.1,10.0->10.1,10.1 (24), 40,40->40,40.2 (48), 40,40.2->portal (12), the dungeon pair (~3.4). + double dun = NavCoords.Distance(61.87, -100.98, 61.88, -100.97); + Near(info.Yards, 24 + 24 + 48 + 12 + dun, 0.5, "yards: the walks only, not across the recall or the portal"); + Near(info.MinNs, 10.0, 1e-9, "box: south edge"); Near(info.MaxNs, 61.88, 1e-9, "box: north edge"); + Near(info.MinEw, -100.98, 1e-9, "box: west edge"); Near(info.MaxEw, 40.25, 1e-9, "box: east edge"); + Near(info.CentreNs, (10.0 + 61.88) / 2, 1e-9, "centre ns"); + Near(info.CentreEw, (-100.98 + 40.25) / 2, 1e-9, "centre ew"); + Check(info.HasStart && info.StartNs == 10.0 && info.StartEw == 10.0, "the start is the first point"); + Near(info.StartYards, NavCoords.Distance(10.0, 10.05, 10.0, 10.0), 0.01, "the player's distance to the start"); + Check(info.Landblocks.Contains(WorldPt.FromMap(10, 10).Landblock) && info.Landblocks.Contains(dunLb) && info.Landblocks.Contains(WorldPt.FromMap(40, 40.1).Landblock), "landblocks it covers"); + Check(info.Landblocks.SequenceEqual(info.Landblocks.OrderBy(x => x)) && info.Landblocks.Distinct().Count() == info.Landblocks.Count, "each once, in order"); + Check(!info.Dungeon && info.DungeonLandblocks.SequenceEqual(new[] { dunLb }), "partly in a dungeon (2 of 7 points): not a dungeon route, the landblock listed"); + Check(info.PortalNames.SequenceEqual(new[] { "Portal to Somewhere" }) && info.RecallNames.SequenceEqual(new[] { "Lifestone Recall" }) + && info.ChatCommands.SequenceEqual(new[] { "@lifestone" }), "portals, recalls and commands used"); + Check(info.NearestIndex == 0 || info.NearestIndex == 2, "the nearest waypoint to the player"); + + using JsonDocument d = JsonDocument.Parse(RouteJson.Write(info.WriteJson)); + JsonElement e = d.RootElement; + Check(e.GetProperty("type").GetString() == "once" && e.GetProperty("points").GetInt32() == 11 && e.GetProperty("counts").GetProperty("portals").GetInt32() == 1, "JSON: type, points, counts"); + Check(e.GetProperty("box").GetProperty("minEw").GetDouble() == -100.98 && e.GetProperty("centre").TryGetProperty("ew", out _), "JSON: box and centre"); + Check(e.GetProperty("landblocks").EnumerateArray().Any(x => x.GetString() == dunLb.ToString("X4")), "JSON: landblocks as hex"); + Check(e.GetProperty("dungeon").GetBoolean() == false && e.GetProperty("portals")[0].GetString() == "Portal to Somewhere", "JSON: dungeon, portals"); + Check(e.GetProperty("start").GetProperty("yards").ValueKind == JsonValueKind.Number, "JSON: the start's distance"); + List lines = info.ChatLines(); + Check(lines.Count >= 4 && lines[0].StartsWith("routeinfo Sample: once, 11 point(s)") && lines.Any(l => l.Contains("portals: Portal to Somewhere")), "chat lines: " + lines[0]); + + // A dungeon route: most of it in dungeon landblocks; no distance from a player on the landscape. + var dr = new NavRouteParser { RouteType = NavRouteType.Circular }; + foreach (double k in new[] { 0.0, 0.01, 0.02, 0.03 }) dr.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 61.87 + k, EW = -100.98 }); + RouteInfo di = RouteInfo.Describe(dr, "Crypt", "", lb => lb == dunLb, true, 10, 10, null); + Check(di.Dungeon && di.Type == "circular" && double.IsNaN(di.StartYards) && di.NearestIndex < 0, "a dungeon route: no map distance from the player"); + Near(di.Yards, 0.03 * 240 * 2, 0.01, "a circular route's yards include the way back to the start"); + RouteInfo none = RouteInfo.Describe(new NavRouteParser { RouteType = NavRouteType.Once }, "Empty", "", null, false, 0, 0, null); + Check(none.Points == 0 && !none.HasBox && none.Landblocks.Count == 0, "an empty route"); + Check(RouteInfo.Describe(r, "x", "", null, false, 0, 0, null).RecallNames[0] == "spell 1635", "a spell the caller can't name"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static HashSet? _realDungeons, _realMap; + + /// + /// A dungeon landblock as the plugin judges one for routeinfo (RynthNavPlugin.RouteMaker.cs InfoWork): + /// the Atlas's dungeon landblocks, and those with a dungeon navmesh and no places on the map. + /// + private static bool RealDungeon(string navData, uint lb) + { + if (_realDungeons == null || _realMap == null) + { + string loc = Path.Combine(navData, "locations.json"); + Atlas atlas = File.Exists(loc) ? Atlas.Load(loc) : Atlas.Empty; + _realDungeons = atlas.DungeonLandblocks(); + _realMap = new HashSet(); + foreach (AtlasLocation l in atlas.Locations) + if (l.OnMap && l.Cell.Length == 8 && uint.TryParse(l.Cell.AsSpan(0, 4), System.Globalization.NumberStyles.HexNumber, null, out uint m)) _realMap.Add(m); + } + return _realDungeons.Contains(lb) || (!_realMap.Contains(lb) && File.Exists(Path.Combine(navData, $"dun_{lb:X4}.tile"))); // DungeonTileFile.FileName (needs Detour: not linked here) + } + + /// The real NavProfiles (read only, when here): every route RynthAi has describes without a throw and adds up. + private static void RouteInfoOnRealNavProfiles() + { + string dir = Environment.GetEnvironmentVariable("RYNTHAI_NAVPROFILES") ?? @"C:\Games\RynthSuite\RynthAi\NavProfiles"; + if (!Directory.Exists(dir)) { Console.WriteLine(" (no NavProfiles here: skipped)"); return; } + string navData = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData"; + Func? dungeon = File.Exists(Path.Combine(navData, "locations.json")) ? lb => RealDungeon(navData, lb) : null; + int files = 0, dungeons = 0, points = 0; + foreach (string f in Directory.EnumerateFiles(dir, "*.nav")) + { + files++; + NavRouteParser route = NavRouteParser.Load(f); + RouteInfo info = RouteInfo.Describe(route, Path.GetFileNameWithoutExtension(f), f, dungeon, true, 42, 33, null); + points += info.Points; + if (info.Dungeon) dungeons++; + Check(info.Points == route.Points.Count && info.Waypoints + info.Portals + info.Recalls + info.Chats + info.Pauses + info.Others == info.Points, + $"route #{files}: the kinds add up"); + Check(double.IsFinite(info.Yards) && info.Yards >= 0, $"route #{files}: a length"); + Check(info.Points == 0 || info.HasBox, $"route #{files}: a box"); + using JsonDocument d = JsonDocument.Parse(RouteJson.Write(info.WriteJson)); + Check(d.RootElement.GetProperty("points").GetInt32() == info.Points, $"route #{files}: its JSON parses"); + } + Console.WriteLine($" {files} real nav file(s), {points} points in all, {dungeons} read as dungeon routes{(dungeon == null ? " (no Atlas here: none can be)" : "")}"); + } + + // ── plan's figures ─────────────────────────────────────────────────── + + private static void PlanSummaryFigures() + { + var steps = new List + { + new(10, 10, false, true, "Lifestone Recall", 0, 20, 20), + new(20.5, 20, true, false, "Portal to Far", -1, 50, 50), + new(50.4, 50.3, false, false, "walk"), + }; + var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List { new("Lifestone Recall", 1635, "", 13) }); + TripPath path = TripPathBuilder.Build(trip, FakeWalk, null); + TripSummary s = TripSummary.Of(trip, path); + Check(s.Steps.Select(x => x.Kind).SequenceEqual(new[] { "recall", "portal", "walk" }), "kinds: recall, portal, walk"); + Check(s.Steps[0].Name == "Lifestone Recall" && s.Steps[1].Name == "Portal to Far" && s.Steps[2].Name == "Far Goal", "names: the recall, the portal, the goal"); + Check(s.Steps[0].Yards == 0 && s.Steps[1].Yards > 120 && s.Steps[2].Yards > 96, "yards: none for a recall, the walked path for the rest"); + Check(s.Steps[0].LandNs == 20 && s.Steps[1].LandNs == 50 && double.IsNaN(s.Steps[2].LandNs), "where the teleports land"); + Check(s.Teleports == 2 && s.CastSeconds == 13, "two teleports, the recall's cast time"); + Near(s.Yards, s.Steps.Sum(x => x.Yards), 1e-9, "the yards add up"); + Near(s.Minutes, (s.Yards / PortalRoute.RunUnitsPerSecond + 2 * PortalRoute.TeleportOverheadUnits / PortalRoute.RunUnitsPerSecond + 13) / 60, 1e-9, "minutes: running, teleports, casting"); + TripSummary straight = TripSummary.Of(trip, null); + Near(straight.Steps[1].Yards, NavCoords.Distance(20, 20, 20.5, 20), 0.01, "without a path: the straight line"); + using JsonDocument d = JsonDocument.Parse(RouteJson.Write(w => { w.WriteStartObject(); s.WriteFields(w); w.WriteEndObject(); })); + Check(d.RootElement.GetProperty("steps").GetArrayLength() == 3 && d.RootElement.GetProperty("teleports").GetInt32() == 2 + && d.RootElement.GetProperty("steps")[1].GetProperty("land").GetProperty("ns").GetDouble() == 50, "plan JSON fields"); + Check(d.RootElement.GetProperty("steps")[2].TryGetProperty("land", out _) == false, "a walk has no landing"); + } + + // ── worldmap.vec ───────────────────────────────────────────────────── + + private static void BuildingOutlinesFile() + { + string dir = Path.Combine(Path.GetTempPath(), "rnav-vec-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + // Two buildings (in map cells, 24 yd): a square at cells (10..11, 10..11) and a triangle; then a road. + string file = Path.Combine(dir, BuildingOutlines.FileName); + using (var w = new BinaryWriter(File.Create(file))) + { + w.Write(new[] { (byte)'R', (byte)'V', (byte)'E', (byte)'C' }); w.Write(1u); w.Write(2u); w.Write(1u); + w.Write((byte)4); foreach (var (x, y) in new[] { (10f, 10f), (11f, 10f), (11f, 11f), (10f, 11f) }) { w.Write(x); w.Write(y); } + w.Write((byte)3); foreach (var (x, y) in new[] { (20f, 20f), (21f, 20f), (20f, 21f) }) { w.Write(x); w.Write(y); } + w.Write((ushort)0); w.Write((ushort)0); w.Write((ushort)1); w.Write((ushort)0); + } + BuildingOutlines? b = BuildingOutlines.Load(file); + Check(b != null && b.Count == 2, "two buildings read"); + Check(b!.Inside(10.5 * 24, 10.5 * 24) == 0, "inside the square"); + Check(b.Inside(11.2 * 24, 10.5 * 24) == -1, "4.8 yd outside: not inside"); + Check(b.Inside(11.2 * 24, 10.5 * 24, margin: 5) == 0, "...but within a 5 yd margin"); + Check(b.Inside(20.2 * 24, 20.2 * 24) == 1 && b.Inside(20.9 * 24, 20.9 * 24) == -1, "the triangle, not its bounding box"); + Check(b.Inside(-5, -5) == -1, "off the map: none"); + File.WriteAllBytes(Path.Combine(dir, "bad.vec"), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }); + Check(BuildingOutlines.Load(Path.Combine(dir, "bad.vec")) == null && BuildingOutlines.Load(Path.Combine(dir, "none.vec")) == null, "a bad or missing file: null"); + var fromPolys = BuildingOutlines.FromPolygons(new[] { new (double, double)[] { (0, 0), (10, 0), (10, 10), (0, 10) } }); + Check(fromPolys.Inside(5, 5) == 0 && fromPolys.Inside(15, 5) == -1, "outlines given in world units"); + + string real = Path.Combine(Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData", BuildingOutlines.FileName); + if (File.Exists(real)) + { + var sw = System.Diagnostics.Stopwatch.StartNew(); + BuildingOutlines? all = BuildingOutlines.Load(real); + Console.WriteLine($" the real {BuildingOutlines.FileName}: {all?.Count} buildings in {sw.ElapsedMilliseconds} ms"); + Check(all != null && all.Count > 1000, "the real file reads (thousands of buildings)"); + } + } + finally { try { Directory.Delete(dir, true); } catch { } } + } +} diff --git a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj index ff1a946..394dca0 100644 --- a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj +++ b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj @@ -39,6 +39,14 @@ + + + + + + +