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) ──
+
+ ///