diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs
index 7124cd9..d8864e9 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs
@@ -228,6 +228,18 @@ public partial class BuffManager
/// The plugin's death hold (and a 0-health read): a pending recall is dropped and the macro is
/// left off, so nothing re-sends /lifestone or restarts the macro after the respawn.
///
+ ///
+ /// A death or a portal dropped whatever the server had open: a wand use in flight is forgotten,
+ /// not judged a failed swap (see _directSwapMisses). RynthAiPlugin calls it with the death hold
+ /// and on entering portal space.
+ ///
+ internal void ForgetPendingWield(string why)
+ {
+ if (_pendingWieldId == 0) return;
+ _pendingWieldId = 0;
+ _host.Log($"[WieldGate] the wand's use in flight was cut short ({why}): not counted as a failed swap");
+ }
+
internal void CancelPendingRecall(string why)
{
if (!_recallPending) return;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
index b9335e1..17de8bb 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
@@ -388,7 +388,7 @@ public partial class BuffManager : IDisposable
private bool FightsWithMagic() => _combatManager?.FightsWithMagic ?? CurrentCombatMode == CombatMode.Magic;
/// Mana is under the line vitals refill at: the % line (Get Mana At in combat, Top Off
- /// Mana idle; 0 = off) or, for a caster, the reserve. : the line in points.
+ /// Mana idle; 0 = off) or the reserve. : the line in points.
internal bool ManaUnderLine(bool inCombat, out int line)
{
line = 0;
@@ -397,12 +397,12 @@ public partial class BuffManager : IDisposable
if (pctLine <= 0 || max <= 0) return false;
line = (int)Math.Ceiling(max * pctLine / 100.0);
bool under = _vitals.ManaPct < pctLine;
- if (FightsWithMagic())
- {
- int reserve = ManaReserve();
- if (reserve > line) line = reserve;
- if (reserve > 0 && _vitals.CurrentMana < reserve) under = true;
- }
+ // Every character, not only casters (2026-10-14): a melee character's buff chain spends mana
+ // too (Drakkon: 4% after a run of auras, under Stamina to Mana's own cost, so nothing could
+ // refill it and buffing sat waiting for regeneration).
+ int reserve = ManaReserve();
+ if (reserve > line) line = reserve;
+ if (reserve > 0 && _vitals.CurrentMana < reserve) under = true;
return under;
}
@@ -421,10 +421,17 @@ public partial class BuffManager : IDisposable
/// Stamina lets Stamina to Mana go: over 15%, or a stamina kit or listed stamina potion
/// can bring it there. Not Revitalize: it costs mana itself, and trading mana for stamina and
/// back while attacks wait could keep a caster from attacking for minutes.
- private bool StaminaAllowsStaminaToMana() => _vitals.StaminaPct > 15
+ private bool StaminaAllowsStaminaToMana() => _vitals.StaminaPct > StaminaToManaFloorPct()
|| BestPackStaminaKit() != null
|| (_settings.UsePotions && HasListedPotion("StaminaPotion", "Stamina"));
+ ///
+ /// Stamina to Mana goes only over this stamina %: Re-stam At (when on), at least 15. Under it,
+ /// stamina is refilled first (kit, potion, Revitalize). Was a flat 15%: each Stamina to Mana took
+ /// 110-126 stamina and Drakkon's stamina was run nearly out before anything refilled it (2026-10-14).
+ ///
+ internal int StaminaToManaFloorPct() => Math.Max(15, _settings.RestamAt);
+
///
/// Mana can't pay for Stamina to Mana: under the cost of its lowest known level when costs are
/// known (the highest level it can pay for is cast first, see AttemptVitalCast), or refused
@@ -598,8 +605,18 @@ public partial class BuffManager : IDisposable
// DoHandleActionGetAndWieldItem: "the client handles dequipping a lot of conflicting items
// automatically"). Drakkon's axe -> wand took 4.2 s with the pack move first (1.2 s for it,
// then the swap gate's flat 3 s). The pack move stays as the fallback: once a use hasn't
- // got the wand into the hand in WieldResolveTimeoutMs, this session moves the weapon first.
- private bool _directWandSwapFailed;
+ // got the wand into the hand in WieldResolveTimeoutMs, the weapon goes into a pack first.
+ // Not for the rest of the session on one miss (2026-10-14): a swap the server never finished
+ // because Drakkon died (13:40) set it, and every later heal from melee took the pack route, the
+ // move plus the swap gate's flat 3 s, 4+ s with nothing healing; he died twice more. Now one miss
+ // sends the next swap through the pack and the one after tries the use again; two misses in a
+ // row keep the pack route. A swap a death or a portal cut short counts for nothing
+ // (ForgetPendingWield).
+ private int _directSwapMisses; // direct swaps in a row that didn't get the wand into the hand
+ private bool _packFirstNext; // the next swap goes through the pack (one miss)
+ private bool _pendingWieldDirect; // the wand's use in flight was a direct swap (a weapon in hand)
+ internal const int DirectSwapMissesToStick = 2;
+ private bool PackFirst => _packFirstNext || _directSwapMisses >= DirectSwapMissesToStick;
// The swap gate's claim count when the wand's use went out: a later claim means another swap
// (combat putting the axe back, 12:39 on 10-06) changed the hands, so the result says nothing.
private long _pendingWieldClaim;
@@ -1539,7 +1556,7 @@ public partial class BuffManager : IDisposable
// Mana under Get Mana At left buffing waiting on natural regen - one buff every 1-2
// minutes (tester, 10-01: 85 minutes of "buffing waits", Stamina to Mana never cast).
// A low stamina is topped up first (kit, Revitalize, potion) so Stamina to Mana can run.
- if (_vitals.StaminaPct > 15 && AttemptVitalCast("Stamina to Mana Self"))
+ if (_vitals.StaminaPct > StaminaToManaFloorPct() && AttemptVitalCast("Stamina to Mana Self"))
{
_isRechargingMana = true;
return;
@@ -1830,14 +1847,14 @@ public partial class BuffManager : IDisposable
if (manaLow)
{
_vitalWhy = "";
- if ((curStamPct > 15 && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion"))
+ if ((curStamPct > StaminaToManaFloorPct() && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion"))
{
_isRechargingMana = true;
return true;
}
- // Stamina too low for Stamina to Mana: a stamina kit, Revitalize or a potion first,
- // whatever Re-stam At says (it may be under 15 or off).
- if (curStamPct <= 15 && TopStaminaToManaId() != 0
+ // 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")))
{
_isRechargingStamina = true;
@@ -1924,8 +1941,12 @@ public partial class BuffManager : IDisposable
bool stamToHealth = StaminaToHealthAllowed(_settings, curHealthPct, curStamPct);
if (!emergencyKit && !stamToHealth) return false;
- // 1. Out of Magic mode a kit first (no wand swap at critical health).
- if (CurrentCombatMode != CombatMode.Magic && AttemptHealthKitUse()) return true;
+ // 1. Out of Magic mode a kit first (no wand swap at critical health), then a health
+ // potion: Heal Self from melee is a wand swap, the Magic stance and the cast, 4-5 s
+ // with nothing healing. Drakkon, 2026-10-14: 69% to 15% in 0.2 s among Depraved
+ // Shadows, the kit at 3%, and the swap was still unanswered when he died 3.2 s later;
+ // the potion came after Heal Self in the chain, so it was never reached.
+ if (CurrentCombatMode != CombatMode.Magic && (AttemptHealthKitUse() || AttemptPotion("HealthPotion"))) return true;
// 2. Stamina to Health Self, by its own line and stamina floor.
if (stamToHealth && AttemptVitalCast("Stamina to Health Self")) return true;
// 3. Not handled: the normal Heal At chain (kit, Heal Self, potion) gets its turn.
@@ -2431,6 +2452,8 @@ public partial class BuffManager : IDisposable
("Lesser Stamina Kit", 100), ("Eternal Stamina Kit", 100),
};
private DateTime _lastKitChanceLog = DateTime.MinValue;
+ /// Kit Min Success % with a melee or missile weapon out, when Kit Min Success is higher.
+ internal const int WeaponOutKitMinPct = 30;
///
/// True when a kit may be used: KitMinSuccessPct is 0, or the kit's chance of working on
@@ -2440,6 +2463,11 @@ public partial class BuffManager : IDisposable
private bool KitChanceOk(int kitId, string kitName, uint missing, bool willBePeace)
{
int minPct = _settings.KitMinSuccessPct;
+ // A weapon out: the spell is a wand swap, the Magic stance and the cast first (4 s and more
+ // from melee), so a kit gets a lower bar. Drakkon, 2026-10-14 13:50: a 51% kit was skipped
+ // for Heal Self from melee and he died before the cast went out.
+ if (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile)
+ minPct = Math.Min(minPct, WeaponOutKitMinPct);
if (minPct <= 0 || _charSkills == null) return true;
int boost = 0;
@@ -4886,13 +4914,16 @@ public partial class BuffManager : IDisposable
_pendingWieldId = 0; // another swap since ours: not a failed wield
return false;
}
- int stillInHand = _directWandSwapFailed ? 0 : FindWieldedNonWandWeapon(wandId);
+ int stillInHand = _pendingWieldDirect ? FindWieldedNonWandWeapon(wandId) : 0;
if (stillInHand != 0 && IsWieldedLive(stillInHand))
{
- _directWandSwapFailed = true;
+ _directSwapMisses++;
+ _packFirstNext = true;
_pendingWieldId = 0;
_host.Log($"[WieldGate] using the wand didn't put 0x{(uint)stillInHand:X8} away in {WieldResolveTimeoutMs:0} ms; " +
- "from now on the weapon goes into a pack first");
+ (_directSwapMisses >= DirectSwapMissesToStick
+ ? $"{_directSwapMisses} in a row: from now on the weapon goes into a pack first"
+ : "the next swap puts the weapon into a pack first, then the use is tried again"));
return false;
}
_host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " +
@@ -4932,7 +4963,7 @@ public partial class BuffManager : IDisposable
// non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern,
// AV-safe), then UseObject(wand) once the hand is free. Fully bounded.
int bowId = FindWieldedNonWandWeapon(wandId);
- if (bowId != 0 && (_directWandSwapFailed || !IsWieldedLive(bowId))) // else the use swaps (see _directWandSwapFailed)
+ if (bowId != 0 && (PackFirst || !IsWieldedLive(bowId))) // else the use swaps (see _directSwapMisses)
{
if (_bowDequipPendingId == bowId
&& (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs
@@ -4965,7 +4996,8 @@ public partial class BuffManager : IDisposable
_bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand
}
- _host.UseFor((uint)wandId, "Buff", bowId != 0 && !_directWandSwapFailed ? "buffing: switch to the wand" : "buffing: wield the wand");
+ _pendingWieldDirect = bowId != 0 && !PackFirst;
+ _host.UseFor((uint)wandId, "Buff", _pendingWieldDirect ? "buffing: switch to the wand" : "buffing: wield the wand");
NoteStanceRequest();
_pendingWieldClaim = _weaponSwapGate?.Claims ?? 0;
_pendingWieldId = wandId;
@@ -4979,6 +5011,8 @@ public partial class BuffManager : IDisposable
{
_pendingWieldId = 0;
_wieldCooldownUntil = DateTime.MinValue;
+ if (_pendingWieldDirect) _directSwapMisses = 0; // the use swapped: back to direct swaps
+ _packFirstNext = false; // a pack-route swap done: the next one tries the use
}
// Deadlock episode tracking: wand wielded but mode refuses to flip.
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
index 7275a72..e2a9100 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
@@ -3076,8 +3076,12 @@ public partial class CombatManager : IDisposable
// on its own timers, a swing can't land inside a use's server turn because the use above holds
// every attack until it is answered, and waiting for each swing animation would cost DPS. A
// stance change still waits (ChangeCombatModeFor), and so does everything in peace/magic.
+ // The movement settle is for casts (a cast beside a stop or a turn was held 40.8 s by the server):
+ // only in Magic mode. From peace the next step is a stance change or a wield, and waiting out the
+ // nav stop first cost every fight's first swing up to 0.6 s (2026-10-14).
bool attackRepeat = CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile;
- if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _, animationGate: !attackRepeat, settleGate: !attackRepeat, attackRepeat: attackRepeat))
+ if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _, animationGate: !attackRepeat,
+ settleGate: CurrentCombatMode == CombatMode.Magic, attackRepeat: attackRepeat))
{
LastCombatSkipReason = "server-answering"; // D4 record-only
_tickWait = CombatLatencyTracker.Wait.Busy;
@@ -4234,6 +4238,8 @@ public partial class CombatManager : IDisposable
}
private (int TargetId, MonsterRule? Rule, List List, int Count, int Hand, DateTime At, WeaponPlan Plan)? _planCache;
+ // Listed weapons found not to be ours (logged once each).
+ private readonly HashSet _notCarriedNoted = new();
private const double PlanCacheMs = 250;
private WeaponPlan ComputePlan(WorldObject target, MonsterRule? rule)
@@ -4380,6 +4386,14 @@ public partial class CombatManager : IDisposable
if (r.Id == 0) continue;
var wo = _worldFilter[r.Id];
if (wo == null) continue;
+ // Sold, dropped or traded: still known to the client, but not ours to wield (a sold
+ // Flaming Greataxe was tried three times, the character standing in the fight, 2026-10-14).
+ if (r.Id != inHand && _worldFilter.PlayerHas(r.Id) == false)
+ {
+ if (_notCarriedNoted.Add(r.Id))
+ _host.Log($"[EquipDiag] listed weapon 0x{(uint)r.Id:X8} '{wo.Name}' isn't in your pack (sold, dropped or traded?): skipped");
+ continue;
+ }
if (!admitCasters && !IsUsableCombatWeapon(r.Id)) { (leftOut ??= new List()).Add(r.Id); continue; }
if (list.Any(c => c.Id == r.Id)) continue;
if (wo.ObjectClass == AcObjectClass.MissileWeapon && IsAmmoItem(wo)) continue; // listed arrows are the ammo choice, never a weapon to wield
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
index e7f4bd0..7481d3f 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
@@ -703,6 +703,21 @@ public class WorldObjectCache
private enum Holder { Unknown, Player, OtherWielder, OtherContainer, Nobody }
+ ///
+ /// The player has (wielded, main pack or a side pack): true; someone or
+ /// something else has it, or it lies on the ground: false; null when the engine can't say yet.
+ /// A sold, dropped or traded item stays known to the client for a while (2026-10-14: a sold
+ /// Flaming Greataxe was still tried three times as the listed weapon). Any thread.
+ ///
+ public bool? PlayerHas(int id)
+ {
+ lock (_gate)
+ {
+ Holder h = WhoHas(id);
+ return h == Holder.Unknown ? null : h == Holder.Player;
+ }
+ }
+
///
/// Who has the object: the player (wielded, in the main pack, or in a side pack), another
/// wielder (other players' and NPCs' gear), another container (a corpse, a chest), or
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
index ab2c34f..df0ae49 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
@@ -695,6 +695,40 @@ internal sealed class DungeonGeometry
return hit;
}
+ ///
+ /// Line of sight between two points on the floor (the Sweep patrol): no wall of the landblock
+ /// reaching into knee-to-head height between them (the same band
+ /// uses), whichever cells the walls belong to. Floors aren't looked at: a monster sees across
+ /// a gap.
+ ///
+ internal bool SightClear(double x0, double y0, double z0, double x1, double y1, double z1)
+ => !WallHit(x0, y0, x1, y1, Math.Min(z0, z1) + WallBandLow, Math.Max(z0, z1) + WallBandHigh, out _);
+
+ /// A point on the cell's floor: the centre of its biggest floor polygon. False when
+ /// the dats give the cell no floor (then its origin stands in).
+ internal bool TryCellFloorCentre(uint cell, out double x, out double y, out double z)
+ {
+ x = y = z = 0;
+ if (!_floors.TryGetValue(cell, out var list) || list.Count == 0) return false;
+ double bestArea = -1;
+ foreach (var v in list)
+ {
+ if (v.Length < 3) continue;
+ double area = 0, cx = 0, cy = 0, cz = 0;
+ for (int i = 0; i < v.Length; i++)
+ {
+ var a = v[i]; var b = v[(i + 1) % v.Length];
+ area += a.X * b.Y - b.X * a.Y;
+ cx += a.X; cy += a.Y; cz += a.Z;
+ }
+ area = Math.Abs(area) * 0.5;
+ if (area <= bestArea) continue;
+ bestArea = area;
+ x = cx / v.Length; y = cy / v.Length; z = cz / v.Length;
+ }
+ return bestArea > 0;
+ }
+
/// Walls (footprint and height range) within r of (x, y), for offline inspection.
internal List<(double X0, double Y0, double X1, double Y1, double ZMin, double ZMax, double Dist)> WallsNear(double x, double y, double r)
{
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
index 76bf7ad..f57283a 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
@@ -569,6 +569,8 @@ internal static partial class DungeonPathfinder
// short for an exit point and the next approach point (DoorwayStandoffs[0] each) without
// doubling back.
private const double RunGapMeters = 8.0;
+ // cos(~93 degrees): openings at right angles (a staircase) still continue a run.
+ private const double RightAngleSlack = 0.05;
private static bool Continues(DungeonGeometry geo, Step a, Step b)
{
@@ -578,9 +580,13 @@ internal static partial class DungeonPathfinder
if (dx * dx + dy * dy >= RunGapMeters * RunGapMeters || Math.Abs(da.Z - db.Z) >= 2.0) return false;
// A run goes on: through the next opening no more than 90 degrees off the last. Turning
// back (in at one opening, out at another beside it) is a visit to the room between.
+ // 90 degrees exactly counts (2026-10-14): a diagonal corridor is a staircase of square
+ // cells whose openings face north, east, north, east...; each failed the old "> 0" by a
+ // hair, got its own approach and exit point 4 m out along its facing, and the patrol
+ // walked the staircase (zig-zag) instead of the corridor's centre line.
var (ax, ay) = da.NormalFrom(a.From);
var (bx, by) = db.NormalFrom(b.From);
- return ax * bx + ay * by > 0.0;
+ return ax * bx + ay * by > -RightAngleSlack;
}
// The approach point before steps[i], the exit point after steps[j], and the opening centres
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Sweep.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Sweep.cs
new file mode 100644
index 0000000..2de2685
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Sweep.cs
@@ -0,0 +1,290 @@
+// DungeonPathfinder, sweep half: Settings > Dungeon Patrol > Coverage "Sweep" (2026-10-14).
+//
+// Why: Whole dungeon walks every doorway between rooms once. A pillar hall (0x00AE: a grid of
+// pillars built from 4.6 m corridor pieces, 1,700 cells, 386 tiny rooms) is all doorways, so
+// the patrol walked every lane between every pair of pillars (1,074 points a lap), though a
+// monster three lanes over has seen the character long before.
+//
+// Sweep walks the same cells (GetMainRouteNodes: Whole dungeon's, dead ends and hazards alike)
+// but only near enough that each is SEEN:
+// 1. Sight: a cell sees another when their floor centres are within SightMeters of each
+// other, on about the same level (SweepMaxRise), with no wall between them
+// (DungeonGeometry.SightClear). Corridors and crypts barely change: their walls block it.
+// 2. Stops: in the patrol's walking order (a depth-first walk from the start, nearest
+// neighbour first), each cell not yet seen gets a stop: of the cells it sees (itself
+// included), the one that sees the most cells still unseen. Its sight marks them seen.
+// 3. Tour: from the start, always the nearest stop not yet visited (by walking distance over
+// the cells), improved by 2-opt, and back to the start; each leg the shortest walk.
+// 4. Points: the tour's cell path turned into doorway steps and laid by EmitSteps, so
+// doorways, room crossings, the wall distance and the corner cutting are the ones every
+// other patrol uses.
+// No geometry, one stop, or a tour that never leaves one room: null, and the caller builds the
+// Whole dungeon patrol instead. The other coverages never come here.
+
+using System;
+using System.Collections.Generic;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi;
+
+internal static partial class DungeonPathfinder
+{
+ // Cells whose floors differ more than this (metres) are taken as different levels: a balcony
+ // over a hall, a ramp's other end. A monster on one notices the character on the other less.
+ internal const double SweepMaxRise = 3.0;
+
+ /// For PatrolProof and the tests: the stops the last sweep chose and the cells it covered.
+ [ThreadStatic] internal static int LastSweepStops, LastSweepCells, LastSweepSeen;
+
+ private static NavRouteParser? BuildSweepPatrol(
+ Dictionary graph, uint startCell, HashSet mainRoute,
+ IReadOnlySet? hazardCells, DungeonGeometry geo, DungeonPatrolOptions o)
+ {
+ LastSweepStops = LastSweepCells = LastSweepSeen = 0;
+ double sight = o.SightMeters;
+
+ // Floor centres, and the walkable neighbours within the patrol's cells.
+ var pos = new Dictionary();
+ foreach (uint c in mainRoute)
+ {
+ if (!graph.TryGetValue(c, out var n)) continue;
+ pos[c] = geo.TryCellFloorCentre(c, out double fx, out double fy, out double fz)
+ ? (fx, fy, fz)
+ : (DungeonGeometry.NavToWorld(n.EW), DungeonGeometry.NavToWorld(n.NS), n.Z);
+ }
+ if (pos.Count < 2) return null;
+ var adj = new Dictionary>();
+ foreach (uint c in pos.Keys)
+ {
+ var list = new List();
+ var cn = graph[c];
+ foreach (uint nb in cn.Neighbors)
+ {
+ if (!pos.ContainsKey(nb) || !graph.TryGetValue(nb, out var nbn) || IsDropEdge(cn, nbn)) continue;
+ list.Add(nb);
+ }
+ list.Sort((a, b) => Dist(pos[c], pos[a]).CompareTo(Dist(pos[c], pos[b])));
+ adj[c] = list;
+ }
+
+ uint start = pos.ContainsKey(startCell) ? startCell : NearestOf(pos, graph, startCell);
+ if (start == 0) return null;
+
+ // 1. Sight, worked out on demand (cells bucketed by SightMeters).
+ var buckets = new Dictionary>();
+ foreach (var (c, p) in pos)
+ {
+ long k = BucketKey(p.X, p.Y, sight);
+ if (!buckets.TryGetValue(k, out var b)) buckets[k] = b = new List();
+ b.Add(c);
+ }
+ var seenFrom = new Dictionary>();
+ List Sees(uint c)
+ {
+ if (seenFrom.TryGetValue(c, out var list)) return list;
+ list = new List { c };
+ var p = pos[c];
+ int bx = (int)Math.Floor(p.X / sight), by = (int)Math.Floor(p.Y / sight);
+ for (int gx = bx - 1; gx <= bx + 1; gx++)
+ for (int gy = by - 1; gy <= by + 1; gy++)
+ {
+ if (!buckets.TryGetValue(((long)gx << 32) ^ (uint)gy, out var b)) continue;
+ foreach (uint v in b)
+ {
+ if (v == c) continue;
+ var q = pos[v];
+ if (Math.Abs(q.Z - p.Z) > SweepMaxRise || Dist(p, q) > sight) continue;
+ if (geo.SightClear(p.X, p.Y, p.Z, q.X, q.Y, q.Z)) list.Add(v);
+ }
+ }
+ seenFrom[c] = list;
+ return list;
+ }
+
+ // 2. Stops, in the walking order.
+ var order = new List();
+ var visited = new HashSet { start };
+ var stack = new Stack();
+ stack.Push(start);
+ while (stack.Count > 0)
+ {
+ uint c = stack.Pop();
+ order.Add(c);
+ var nbs = adj[c];
+ for (int i = nbs.Count - 1; i >= 0; i--) // nearest neighbour first
+ if (visited.Add(nbs[i])) stack.Push(nbs[i]);
+ }
+ var covered = new HashSet();
+ var stops = new List();
+ foreach (uint u in order)
+ {
+ if (covered.Contains(u)) continue;
+ uint best = u;
+ int bestGain = -1;
+ foreach (uint v in Sees(u))
+ {
+ int gain = 0;
+ foreach (uint w in Sees(v)) if (!covered.Contains(w)) gain++;
+ if (gain > bestGain) { bestGain = gain; best = v; }
+ }
+ stops.Add(best);
+ foreach (uint w in Sees(best)) covered.Add(w);
+ covered.Add(u); // u sees best, so best sees u (sight is symmetric)
+ }
+ LastSweepStops = stops.Count;
+ LastSweepCells = order.Count;
+ LastSweepSeen = covered.Count;
+ if (stops.Count < 2) return null;
+
+ // 3. Tour: the start, then the nearest unvisited stop each time (by walking distance), then
+ // 2-opt (reverse any stretch whose ends are closer the other way round) to take out the
+ // criss-crossing a nearest-next tour leaves; each leg the shortest walk.
+ var tourCells = new List(stops.Count + 1) { start };
+ foreach (uint st in stops) if (st != start) tourCells.Add(st);
+ int stopCount = tourCells.Count;
+ var index = new Dictionary();
+ for (int i = 0; i < stopCount; i++) index[tourCells[i]] = i;
+ var walk = new double[stopCount, stopCount];
+ for (int i = 0; i < stopCount; i++)
+ {
+ var d = WalkDistances(adj, pos, tourCells[i]);
+ for (int j = 0; j < stopCount; j++) walk[i, j] = d.TryGetValue(tourCells[j], out double v) ? v : double.PositiveInfinity;
+ }
+ var tour = new List { 0 };
+ var left = new HashSet();
+ for (int i = 1; i < stopCount; i++) if (!double.IsPositiveInfinity(walk[0, i])) left.Add(i); // unreachable stops dropped
+ while (left.Count > 0)
+ {
+ int last = tour[^1], next = -1;
+ foreach (int j in left) if (next < 0 || walk[last, j] < walk[last, next]) next = j;
+ tour.Add(next);
+ left.Remove(next);
+ }
+ TwoOpt(tour, walk);
+
+ var path = new List { start };
+ for (int k = 0; k < tour.Count; k++)
+ {
+ uint from = tourCells[tour[k]], to = tourCells[tour[(k + 1) % tour.Count]];
+ if (from == to) continue;
+ var leg = WalkToNearest(adj, pos, from, new HashSet { to });
+ if (leg == null) continue;
+ for (int i = 1; i < leg.Count; i++) path.Add(leg[i]);
+ }
+
+ // 4. Points, through every doorway the tour takes.
+ var rooms = BuildRooms(graph, geo, hazardCells);
+ var steps = new List();
+ for (int i = 0; i + 1 < path.Count; i++)
+ {
+ uint a = path[i], b = path[i + 1];
+ if (!rooms.RoomOf.TryGetValue(a, out int ra) || !rooms.RoomOf.TryGetValue(b, out int rb) || ra == rb) continue;
+ steps.Add(new Step(a, b, EdgeKey(a, b)));
+ }
+ if (steps.Count == 0) return null;
+ if (PointLog != null)
+ MainRouteNote += $"; sweep: {stops.Count} stops see {covered.Count} of {order.Count} cells within {sight:0.#} m, "
+ + $"tour {path.Count} cells, {steps.Count} doorway steps";
+ var route = new NavRouteParser { RouteType = NavRouteType.Circular };
+ route.Points.AddRange(EmitSteps(graph, geo, rooms, steps, closed: true, null, 0, null, 0, o, out _));
+ return route;
+ }
+
+ private static double Dist((double X, double Y, double Z) a, (double X, double Y, double Z) b)
+ {
+ double dx = a.X - b.X, dy = a.Y - b.Y;
+ return Math.Sqrt(dx * dx + dy * dy);
+ }
+
+ private static long BucketKey(double x, double y, double size)
+ => ((long)(int)Math.Floor(x / size) << 32) ^ (uint)(int)Math.Floor(y / size);
+
+ private static uint NearestOf(Dictionary pos, Dictionary graph, uint cell)
+ {
+ if (!graph.TryGetValue(cell, out var n)) return 0;
+ var p = (DungeonGeometry.NavToWorld(n.EW), DungeonGeometry.NavToWorld(n.NS), n.Z);
+ uint best = 0;
+ double bestD = double.MaxValue;
+ foreach (var (c, q) in pos)
+ {
+ double d = Dist(p, q) + Math.Abs(q.Z - n.Z);
+ if (d < bestD) { bestD = d; best = c; }
+ }
+ return best;
+ }
+
+ // Dijkstra from src: the walking distance to every cell it reaches.
+ private static Dictionary WalkDistances(Dictionary> adj,
+ Dictionary pos, uint src)
+ {
+ var dist = new Dictionary { [src] = 0 };
+ var pq = new PriorityQueue();
+ pq.Enqueue(src, 0);
+ while (pq.TryDequeue(out uint c, out double d))
+ {
+ if (d > dist[c]) continue;
+ foreach (uint nb in adj[c])
+ {
+ double nd = d + Dist(pos[c], pos[nb]) + Math.Abs(pos[c].Z - pos[nb].Z);
+ if (dist.TryGetValue(nb, out double old) && old <= nd) continue;
+ dist[nb] = nd;
+ pq.Enqueue(nb, nd);
+ }
+ }
+ return dist;
+ }
+
+ // 2-opt over a closed tour (tour[0], the start, stays first): reverse tour[i..j] whenever that
+ // shortens it, until no reversal does (bounded passes). Walking distances need not be symmetric
+ // to the metre (levels), so each reversal is judged on the full stretch.
+ internal static void TwoOpt(List tour, double[,] walk)
+ {
+ int n = tour.Count;
+ if (n < 4) return;
+ double Leg(int a, int b) => walk[tour[a], tour[b % n]];
+ for (int pass = 0; pass < 50; pass++)
+ {
+ bool improved = false;
+ for (int i = 1; i < n - 1; i++)
+ for (int j = i + 1; j < n; j++)
+ {
+ double before = Leg(i - 1, i) + Leg(j, j + 1);
+ double after = walk[tour[i - 1], tour[j]] + walk[tour[i], tour[(j + 1) % n]];
+ if (after + 1e-6 >= before) continue;
+ tour.Reverse(i, j - i + 1);
+ improved = true;
+ }
+ if (!improved) break;
+ }
+ }
+
+ // Dijkstra from src (by the distance between floor centres) to the nearest cell in goals; the path, src first.
+ private static List? WalkToNearest(Dictionary> adj, Dictionary pos,
+ uint src, HashSet goals)
+ {
+ var dist = new Dictionary { [src] = 0 };
+ var prev = new Dictionary();
+ var pq = new PriorityQueue();
+ pq.Enqueue(src, 0);
+ while (pq.TryDequeue(out uint c, out double d))
+ {
+ if (d > dist[c]) continue;
+ if (c != src && goals.Contains(c))
+ {
+ var path = new List();
+ for (uint at = c; ; at = prev[at]) { path.Add(at); if (at == src) break; }
+ path.Reverse();
+ return path;
+ }
+ foreach (uint nb in adj[c])
+ {
+ double nd = d + Dist(pos[c], pos[nb]) + Math.Abs(pos[c].Z - pos[nb].Z);
+ if (dist.TryGetValue(nb, out double old) && old <= nd) continue;
+ dist[nb] = nd;
+ prev[nb] = c;
+ pq.Enqueue(nb, nd);
+ }
+ }
+ return null;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
index 5a698e0..4d07397 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
@@ -508,7 +508,8 @@ internal static partial class DungeonPathfinder
else
{
result = TrimDeadEndPockets(graph, reachable, startCell, o.MaxDeadEndCells, rooms, o.LookInRoomMeters);
- how = (o.Coverage == PatrolCoverage.LoopsOnly ? "loops only, but hazards cut the loops: " : "")
+ how = (o.Coverage == PatrolCoverage.LoopsOnly ? "loops only, but hazards cut the loops: "
+ : o.Coverage == PatrolCoverage.Sweep ? "sweep, over " : "")
+ $"all reachable cells but dead-end areas of <= {o.MaxDeadEndCells} cells{(rooms != null ? " (by room)" : "")} ({result.Count} kept)";
}
if (PointLog != null)
@@ -807,6 +808,14 @@ internal static partial class DungeonPathfinder
var rooms = geo != null && geo.DoorwayCount > 0 ? BuildRooms(graph, geo, hazardCells) : null;
var mainRoute = GetMainRouteNodes(graph, startCell, hazardCells, o, rooms);
+ // Sweep (DungeonPathfinder.Sweep.cs): the same cells, walked only near enough to be seen.
+ // Falls through to the room patrol below when it can't build one. No other coverage comes here.
+ if (o.Coverage == PatrolCoverage.Sweep && geo != null && geo.DoorwayCount > 0)
+ {
+ var sweep = BuildSweepPatrol(graph, startCell, mainRoute, hazardCells, geo, o);
+ if (sweep != null && sweep.Points.Count > 0) return sweep;
+ }
+
// With the dungeon map geometry: the same coverage over rooms instead of cells, rooms
// crossed directly, doorways taken straight on (DungeonPathfinder.Rooms.cs).
if (geo != null && geo.DoorwayCount > 0)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPatrolOptions.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPatrolOptions.cs
index b5e2c46..fd971f9 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPatrolOptions.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPatrolOptions.cs
@@ -19,6 +19,11 @@ internal enum PatrolCoverage
LoopsOnly = 1,
/// Every reachable cell, every dead end included.
Everything = 2,
+ /// The Whole dungeon cells, but walked only close enough that every one is seen: a
+ /// stop within SightMeters, on about the same level, with no wall between (2026-10-14: a pillar
+ /// hall, 0x00AE, is 1,700 cells of corridor pieces, and Whole dungeon walked every lane).
+ /// DungeonPathfinder.Sweep.cs.
+ Sweep = 3,
}
internal sealed record DungeonPatrolOptions
@@ -26,6 +31,7 @@ internal sealed record DungeonPatrolOptions
public const int MaxDeadEndCellsMin = 0, MaxDeadEndCellsMax = 30, MaxDeadEndCellsDefault = 10;
public const double WallClearanceMin = 0.5, WallClearanceMax = 2.0, WallClearanceDefault = 1.0;
public const double LookInRoomMin = 3.0, LookInRoomMax = 40.0, LookInRoomDefault = 10.0;
+ public const double SightMin = 5.0, SightMax = 60.0, SightDefault = 20.0;
public static readonly DungeonPatrolOptions Default = new();
@@ -51,6 +57,10 @@ internal sealed record DungeonPatrolOptions
/// skirts or leaves by the doorway it came in by gets a walk to its middle and back.
public double LookInRoomMeters { get; init; } = LookInRoomDefault;
+ /// Sweep: how far (metres) a monster notices the character, so how far apart the
+ /// patrol's lanes may be. Settings "Sight Distance (yd)". Unused by the other coverages.
+ public double SightMeters { get; init; } = SightDefault;
+
/// The options with every value in range (a hand-edited profile or a remote setting).
public DungeonPatrolOptions Clamped() => this with
{
@@ -58,12 +68,14 @@ internal sealed record DungeonPatrolOptions
MaxDeadEndCells = Math.Clamp(MaxDeadEndCells, MaxDeadEndCellsMin, MaxDeadEndCellsMax),
WallClearance = double.IsFinite(WallClearance) ? Math.Clamp(WallClearance, WallClearanceMin, WallClearanceMax) : WallClearanceDefault,
LookInRoomMeters = double.IsFinite(LookInRoomMeters) ? Math.Clamp(LookInRoomMeters, LookInRoomMin, LookInRoomMax) : LookInRoomDefault,
+ SightMeters = double.IsFinite(SightMeters) ? Math.Clamp(SightMeters, SightMin, SightMax) : SightDefault,
};
public static string CoverageName(PatrolCoverage c) => c switch
{
PatrolCoverage.LoopsOnly => "loops only",
PatrolCoverage.Everything => "everything",
+ PatrolCoverage.Sweep => "sweep",
_ => "whole dungeon",
};
@@ -72,6 +84,7 @@ internal sealed record DungeonPatrolOptions
{
var inv = CultureInfo.InvariantCulture;
string spurs = Coverage == PatrolCoverage.Everything ? "" : $", skip dead ends <= {MaxDeadEndCells}";
+ if (Coverage == PatrolCoverage.Sweep) spurs += $", sight {SightMeters.ToString("0.#", inv)} m";
return $"coverage {CoverageName(Coverage)}{spurs}, lava/acid floors {(AvoidHazardFloors ? "avoided" : "walked")}, "
+ $"walls {WallClearance.ToString("0.0#", inv)} m, look into rooms >= {LookInRoomMeters.ToString("0.#", inv)} m";
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
index 2ac5958..4326187 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
@@ -1032,6 +1032,9 @@ internal sealed partial class LegacyDashboardRenderer
DeathRecallSpellId = s.DeathRecallSpellId,
DeathRecallItem = s.DeathRecallItem,
StopMacroOnNoComponents = s.StopMacroOnNoComponents,
+ LowCompsRecall = s.LowCompsRecall,
+ LowCompsTaperMin = s.LowCompsTaperMin,
+ LowCompsScarabMin = s.LowCompsScarabMin,
StopLootingWhenPackFull = s.StopLootingWhenPackFull,
StopMacroWhenPackFull = s.StopMacroWhenPackFull,
RestamAt = s.RestamAt,
@@ -1107,6 +1110,7 @@ internal sealed partial class LegacyDashboardRenderer
DunPatrolAvoidFloors = s.DunPatrolAvoidFloors,
DunPatrolWallDistance = s.DunPatrolWallDistance,
DunPatrolLookInSize = s.DunPatrolLookInSize,
+ DunPatrolSightYd = s.DunPatrolSightYd,
T2Speed = s.T2Speed,
T2WalkWithinYd = s.T2WalkWithinYd,
T2DistanceTo = s.T2DistanceTo,
@@ -1264,6 +1268,9 @@ internal sealed partial class LegacyDashboardRenderer
if (p.DeathRecallSpellId is int recallSpell && recallSpell > 0) s.DeathRecallSpellId = recallSpell;
if (p.DeathRecallItem is string recallItem) s.DeathRecallItem = recallItem.Trim();
s.StopMacroOnNoComponents = p.StopMacroOnNoComponents;
+ if (p.LowCompsRecall is bool lowComps) s.LowCompsRecall = lowComps;
+ if (p.LowCompsTaperMin is int taperMin) s.LowCompsTaperMin = Math.Clamp(taperMin, 0, 1000);
+ if (p.LowCompsScarabMin is int scarabMin) s.LowCompsScarabMin = Math.Clamp(scarabMin, 0, 100);
s.StopLootingWhenPackFull = p.StopLootingWhenPackFull;
s.StopMacroWhenPackFull = p.StopMacroWhenPackFull;
s.RestamAt = p.RestamAt;
@@ -1335,11 +1342,12 @@ internal sealed partial class LegacyDashboardRenderer
s.NavTier1TurnSpeed = p.NavTier1TurnSpeed;
s.PostPortalDelaySec = p.PostPortalDelaySec;
// Dungeon patrol: absent (an older engine) = unchanged.
- if (p.DunPatrolCoverage is int patrolCoverage) s.DunPatrolCoverage = Math.Clamp(patrolCoverage, 0, 2);
+ if (p.DunPatrolCoverage is int patrolCoverage) s.DunPatrolCoverage = Math.Clamp(patrolCoverage, 0, (int)PatrolCoverage.Sweep);
if (p.DunPatrolSkipDeadEnds is int patrolSpurs) s.DunPatrolSkipDeadEnds = Math.Clamp(patrolSpurs, DungeonPatrolOptions.MaxDeadEndCellsMin, DungeonPatrolOptions.MaxDeadEndCellsMax);
if (p.DunPatrolAvoidFloors is bool patrolFloors) s.DunPatrolAvoidFloors = patrolFloors;
if (p.DunPatrolWallDistance is float patrolWalls) s.DunPatrolWallDistance = (float)Math.Clamp(patrolWalls, DungeonPatrolOptions.WallClearanceMin, DungeonPatrolOptions.WallClearanceMax);
if (p.DunPatrolLookInSize is float patrolLookIn) s.DunPatrolLookInSize = (float)Math.Clamp(patrolLookIn, DungeonPatrolOptions.LookInRoomMin, DungeonPatrolOptions.LookInRoomMax);
+ if (p.DunPatrolSightYd is float patrolSight) s.DunPatrolSightYd = (float)Math.Clamp(patrolSight, DungeonPatrolOptions.SightMin, DungeonPatrolOptions.SightMax);
s.T2Speed = p.T2Speed;
s.T2WalkWithinYd = p.T2WalkWithinYd;
s.T2DistanceTo = p.T2DistanceTo;
@@ -1697,6 +1705,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.DunPatrolAvoidFloors = tmp.DunPatrolAvoidFloors;
dst.DunPatrolWallDistance = tmp.DunPatrolWallDistance;
dst.DunPatrolLookInSize = tmp.DunPatrolLookInSize;
+ dst.DunPatrolSightYd = tmp.DunPatrolSightYd;
dst.T2Speed = tmp.T2Speed;
dst.T2DistanceTo = tmp.T2DistanceTo;
dst.T2ReissueMs = tmp.T2ReissueMs;
@@ -1764,6 +1773,9 @@ internal sealed partial class LegacyDashboardRenderer
dst.DeathRecallSpellId = tmp.DeathRecallSpellId > 0 ? tmp.DeathRecallSpellId : 48;
dst.DeathRecallItem = tmp.DeathRecallItem ?? string.Empty;
dst.StopMacroOnNoComponents = tmp.StopMacroOnNoComponents;
+ dst.LowCompsRecall = tmp.LowCompsRecall;
+ dst.LowCompsTaperMin = Math.Clamp(tmp.LowCompsTaperMin, 0, 1000);
+ dst.LowCompsScarabMin = Math.Clamp(tmp.LowCompsScarabMin, 0, 100);
dst.StopLootingWhenPackFull = tmp.StopLootingWhenPackFull;
dst.StopMacroWhenPackFull = tmp.StopMacroWhenPackFull;
dst.RestamAt = tmp.RestamAt;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
index e0f2c6f..b86c7c2 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
@@ -56,11 +56,12 @@ public sealed class LegacyUiSettings
// Dungeon patrol (/ra dunnav-patrol, Settings > Navigation > Dungeon Patrol; DungeonPatrolOptions).
// The defaults are the patrol as it was before these settings (2026-10-12). A running patrol
// is rebuilt when one changes (RynthAiCommands.TickDunPatrolReroute).
- public int DunPatrolCoverage; // PatrolCoverage: 0 whole dungeon, 1 loops only, 2 everything
+ public int DunPatrolCoverage; // PatrolCoverage: 0 whole dungeon, 1 loops only, 2 everything, 3 sweep
public int DunPatrolSkipDeadEnds = 10; // whole dungeon: dead-end areas of up to this many cells are skipped (0 = none)
public bool DunPatrolAvoidFloors = true; // lava/acid floor cells (HazardTextures.txt) kept out of the patrol
public float DunPatrolWallDistance = 1.0f; // metres every patrol point keeps from walls where there is room
public float DunPatrolLookInSize = 10.0f; // rooms this big (m) the patrol only skirts get a walk to their middle
+ public float DunPatrolSightYd = 20.0f; // sweep: how far a monster notices you, so how far apart the lanes may be
// 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
@@ -163,6 +164,11 @@ public sealed class LegacyUiSettings
public int DeathRecallSpellId = 48; // Primary Portal Recall
public string DeathRecallItem = string.Empty;
public bool StopMacroOnNoComponents = false;
+ // Recall When Low On Components (RynthAiPlugin.LowComponents.cs): tapers at or under LowCompsTaperMin,
+ // or a scarab kind (not Diamond) at or under LowCompsScarabMin, stops the macro and recalls home.
+ public bool LowCompsRecall = false;
+ public int LowCompsTaperMin = 10;
+ public int LowCompsScarabMin = 2;
public bool StopLootingWhenPackFull = true;
public bool StopMacroWhenPackFull = false;
public int RestamAt = 30;
@@ -960,6 +966,7 @@ public sealed class SettingsBridgePayload
public bool? DunPatrolAvoidFloors { get; set; }
public float? DunPatrolWallDistance { get; set; }
public float? DunPatrolLookInSize { get; set; }
+ public float? DunPatrolSightYd { 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; }
@@ -993,6 +1000,9 @@ public sealed class SettingsBridgePayload
public bool StopMacroOnDeath { get; set; }
public bool StopMacroOnNoComponents { get; set; }
// Absent from an older engine: null keeps the plugin's values.
+ public bool? LowCompsRecall { get; set; }
+ public int? LowCompsTaperMin { get; set; }
+ public int? LowCompsScarabMin { get; set; }
public int? DeathRecallMode { get; set; }
public int? DeathRecallSpellId { get; set; }
public string? DeathRecallItem { get; set; }
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
index f8897dd..02b4591 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
@@ -2813,11 +2813,12 @@ public sealed partial class RynthAiPlugin
/// The Dungeon Patrol settings (Settings > Navigation) as patrol options, in range.
internal static DungeonPatrolOptions PatrolOptionsFrom(LegacyUiSettings s) => new DungeonPatrolOptions
{
- Coverage = (PatrolCoverage)Math.Clamp(s.DunPatrolCoverage, 0, 2),
+ Coverage = (PatrolCoverage)Math.Clamp(s.DunPatrolCoverage, 0, (int)PatrolCoverage.Sweep),
MaxDeadEndCells = s.DunPatrolSkipDeadEnds,
AvoidHazardFloors = s.DunPatrolAvoidFloors,
WallClearance = s.DunPatrolWallDistance,
LookInRoomMeters = s.DunPatrolLookInSize,
+ SightMeters = s.DunPatrolSightYd,
}.Clamped();
///
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LowComponents.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LowComponents.cs
new file mode 100644
index 0000000..fd73d45
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LowComponents.cs
@@ -0,0 +1,91 @@
+using System;
+using System.Collections.Generic;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi;
+
+///
+/// Recall When Low On Components (2026-10-14; off by default): with the macro running, tapers
+/// (all kinds together) at or under Low Tapers At, or any one kind of scarab except Diamond at or
+/// under Low Scarabs At, stop the macro and recall to the lifestone, saying which ran low. Lucy died
+/// that day with every heal spell refused for components, so the bot goes home before that.
+///
+/// A kind only counts once it has been seen in the pack this session: a character that never
+/// carries a Mana Scarab (or no tapers at all, a pure fighter) isn't "low" on it; one that runs a
+/// kind out entirely (0, gone from the pack) still is. Checked every LowCompsCheckMs; it fires once
+/// and re-arms when the macro is started again.
+///
+public sealed partial class RynthAiPlugin
+{
+ private const long LowCompsCheckMs = 5_000;
+ private long _lowCompsCheckedAt;
+ private bool _lowCompsFired;
+ private bool _lowCompsWasRunning;
+ // Component kinds seen in the pack this session ("taper" for all tapers together, else the scarab's name).
+ private readonly HashSet _compsSeen = new(StringComparer.OrdinalIgnoreCase);
+
+ internal const string TaperKey = "tapers";
+
+ /// Every tick with the safety checks; does the work every LowCompsCheckMs.
+ private void CheckLowComponents(LegacyUiSettings s)
+ {
+ if (s.IsMacroRunning && !_lowCompsWasRunning) _lowCompsFired = false; // a new run re-arms it
+ _lowCompsWasRunning = s.IsMacroRunning;
+ if (!s.LowCompsRecall || !s.IsMacroRunning || _lowCompsFired || _objectCache == null) return;
+ long now = Environment.TickCount64;
+ if (now - _lowCompsCheckedAt < LowCompsCheckMs) return;
+ _lowCompsCheckedAt = now;
+
+ var counts = CountComponents(_objectCache.GetInventory());
+ string? low = LowComponents(counts, _compsSeen, s.LowCompsTaperMin, s.LowCompsScarabMin);
+ if (low == null) return;
+
+ _lowCompsFired = true;
+ HandleMacroRunCommand("stop", Array.Empty());
+ bool recalled = Host.HasInvokeChatParser;
+ if (recalled) Host.InvokeChatParser("/lifestone");
+ string line = $"Low on components ({low}): macro stopped" + (recalled ? ", recalling to the lifestone" : "") +
+ " (Recall When Low On Components is on).";
+ ChatLine("[RynthAi] " + line);
+ Log("[RynthAi] " + line);
+ }
+
+ /// Tapers (every kind together, under ) and each scarab kind but Diamond, by stack size.
+ internal static Dictionary CountComponents(IEnumerable inventory)
+ {
+ var counts = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var wo in inventory)
+ {
+ string name = wo?.Name ?? "";
+ string? key = name.EndsWith(" Taper", StringComparison.OrdinalIgnoreCase) ? TaperKey
+ : name.EndsWith(" Scarab", StringComparison.OrdinalIgnoreCase)
+ && !name.StartsWith("Diamond", StringComparison.OrdinalIgnoreCase) ? name
+ : null;
+ if (key == null) continue;
+ int n = Math.Max(1, wo!.Values(LongValueKey.StackCount, 1));
+ counts[key] = counts.TryGetValue(key, out int c) ? c + n : n;
+ }
+ return counts;
+ }
+
+ ///
+ /// "tapers 9, Lead Scarab 2" for the kinds at or under their line, or null. Kinds in
+ /// join ; a seen kind missing now counts as 0.
+ /// A line of 0 or less is off for that kind.
+ ///
+ internal static string? LowComponents(Dictionary counts, HashSet seen, int taperMin, int scarabMin)
+ {
+ foreach (var k in counts.Keys) seen.Add(k);
+ var low = new List();
+ foreach (string kind in seen)
+ {
+ int have = counts.TryGetValue(kind, out int c) ? c : 0;
+ bool taper = kind.Equals(TaperKey, StringComparison.OrdinalIgnoreCase);
+ int line = taper ? taperMin : scarabMin;
+ if (line > 0 && have <= line) low.Add($"{(taper ? "tapers" : kind)} {have}");
+ }
+ if (low.Count == 0) return null;
+ low.Sort(StringComparer.OrdinalIgnoreCase);
+ return string.Join(", ", low);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs
index a3c9a09..02a1ea4 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs
@@ -62,7 +62,11 @@ public sealed partial class RynthAiPlugin
private void NotePortalForPacer()
{
bool portaling = Host.HasIsPortaling && Host.IsPortaling();
- if (portaling && !_wasPortalingForPacer) RynthCore.Plugin.Shared.ActionPacer.Forget("portal space");
+ if (portaling && !_wasPortalingForPacer)
+ {
+ RynthCore.Plugin.Shared.ActionPacer.Forget("portal space");
+ _buffManager?.ForgetPendingWield("portal space");
+ }
_wasPortalingForPacer = portaling;
}
@@ -95,6 +99,7 @@ public sealed partial class RynthAiPlugin
_navigationEngine?.Stop();
RynthCore.Plugin.Shared.ActionPacer.Forget("death"); // the server dropped whatever was open
_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
}
else
{
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
index dc87279..ce42892 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
@@ -1021,9 +1021,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10),
["NavLookaheadYards"] = (0, 30), ["NavShortcutYards"] = (0, 10), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30),
["NavOffTrackYards"] = (160, 1000), ["NavMaxDetourAttempts"] = (1, 10),
- ["DunPatrolCoverage"] = (0, 2), ["DunPatrolSkipDeadEnds"] = (DungeonPatrolOptions.MaxDeadEndCellsMin, DungeonPatrolOptions.MaxDeadEndCellsMax),
+ ["DunPatrolCoverage"] = (0, (int)PatrolCoverage.Sweep), ["DunPatrolSkipDeadEnds"] = (DungeonPatrolOptions.MaxDeadEndCellsMin, DungeonPatrolOptions.MaxDeadEndCellsMax),
["DunPatrolWallDistance"] = (DungeonPatrolOptions.WallClearanceMin, DungeonPatrolOptions.WallClearanceMax),
["DunPatrolLookInSize"] = (DungeonPatrolOptions.LookInRoomMin, DungeonPatrolOptions.LookInRoomMax),
+ ["DunPatrolSightYd"] = (DungeonPatrolOptions.SightMin, DungeonPatrolOptions.SightMax),
["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),
@@ -1621,7 +1622,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_vitals.MaxMana = maxMp;
}
}
- if (_dashboard?.Settings is { } safetySettings) CheckPlayerDeath(safetySettings);
+ if (_dashboard?.Settings is { } safetySettings)
+ {
+ CheckPlayerDeath(safetySettings);
+ CheckLowComponents(safetySettings);
+ }
// Dead or on the way back from a death: do nothing (HoldForDeath). The
// finally below still submits the nav markers.
RynthCore.Plugin.Shared.ActionPacer.NoteFrame();
diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs
index f80fa5b..9e6ef65 100644
--- a/Plugins/Shared/ActionPacer.cs
+++ b/Plugins/Shared/ActionPacer.cs
@@ -130,6 +130,13 @@ internal static class ActionPacer
public const long GestureEmergencyMaxMs = 1500;
/// A heal behind a stance change: once the client has read the new mode this long.
public const long HealAfterModeReadMs = 300;
+ ///
+ /// A melee/missile swing behind the stance change into that mode: once the client has read the
+ /// mode this long, not the full ModeSettleMs (2026-10-14: the first swing of every fight came
+ /// 0.8 s after the stance; the settle is there for uses, whose server turn a stance stops, and a
+ /// swing is no use: the server plays it after the stance, as when a player attacks from peace).
+ ///
+ public const long AttackAfterModeReadMs = 300;
/// An engine without UseDone: an action counts as answered after this (no real pacing).
public const long NoUseDoneFallbackMs = 600;
@@ -383,18 +390,22 @@ internal static class ActionPacer
return false;
}
lock (Gate) _settleLogged.Clear();
- if (!OutstandingAllows(host, who, heal, out why)) return false;
+ if (!OutstandingAllows(host, who, heal, out why, attackRepeat)) return false;
if (animationGate && GestureHolds(host, who, heal, out why)) return false;
return true;
}
- private static bool OutstandingAllows(RynthCoreHost host, string who, HealNeed heal, out string why)
+ private static bool OutstandingAllows(RynthCoreHost host, string who, HealNeed heal, out string why, bool attack = false)
{
why = "";
PacedAction? a = Current(host);
if (a == null) return true;
long age = NowMs() - a.SentMs;
+ // The first swing after the change into Melee/Missile mode (see AttackAfterModeReadMs).
+ if (attack && a.Kind == PacedKind.CombatMode && a.ModeSeenMs != 0 && NowMs() - a.ModeSeenMs >= AttackAfterModeReadMs)
+ return true;
+
if (heal != HealNeed.None)
{
if (a.Kind == PacedKind.WorldUse && heal == HealNeed.Emergency && age >= EmergencyAfterWorldUseMs)
diff --git a/Tools/RynthCore.PatrolProof/RynthCore.PatrolProof.csproj b/Tools/RynthCore.PatrolProof/RynthCore.PatrolProof.csproj
index 48fa4b5..157b701 100644
--- a/Tools/RynthCore.PatrolProof/RynthCore.PatrolProof.csproj
+++ b/Tools/RynthCore.PatrolProof/RynthCore.PatrolProof.csproj
@@ -28,6 +28,7 @@
+
diff --git a/Tools/RynthCore.PatrolProof/Waypoints.cs b/Tools/RynthCore.PatrolProof/Waypoints.cs
index 0d79fff..fe10471 100644
--- a/Tools/RynthCore.PatrolProof/Waypoints.cs
+++ b/Tools/RynthCore.PatrolProof/Waypoints.cs
@@ -20,7 +20,7 @@ namespace RynthCore.PatrolProof;
// summary summary lines only tiny only waypoints in rooms of <= 5 cells
// The patrol settings (Settings > Navigation > Dungeon Patrol; DungeonPatrolOptions), default
// as in the game:
-// coverage whole|loops|all spurs N (0-30: dead-end areas of <= N cells skipped) floors on|off walls M (0.5-2) lookin M (3-40)
+// coverage whole|loops|all|sweep sight M (5-60, sweep's sight distance) spurs N (0-30: dead-end areas of <= N cells skipped) floors on|off walls M (0.5-2) lookin M (3-40)
// floors off keeps the surface cells out of the hazards unless hzfile/hz also list them, as
// BuildDunPatrol does with the cells in DungeonHazards/.txt.
// modes for each start, one line per setting variant (coverage modes, dead-end limits,
@@ -51,7 +51,8 @@ internal static class Waypoints
else if (a == "modes") modes = true;
else if (a == "pockets") pocketList = true;
else if (a == "coverage" && i + 1 < args.Length)
- opt = opt with { Coverage = args[++i] switch { "loops" => PatrolCoverage.LoopsOnly, "all" or "everything" => PatrolCoverage.Everything, _ => PatrolCoverage.WholeDungeon } };
+ opt = opt with { Coverage = args[++i] switch { "loops" => PatrolCoverage.LoopsOnly, "all" or "everything" => PatrolCoverage.Everything, "sweep" => PatrolCoverage.Sweep, _ => PatrolCoverage.WholeDungeon } };
+ else if (a == "sight" && i + 1 < args.Length) opt = opt with { SightMeters = double.Parse(args[++i], inv) };
else if (a == "spurs" && i + 1 < args.Length) opt = opt with { MaxDeadEndCells = int.Parse(args[++i], inv) };
else if (a == "floors" && i + 1 < args.Length) opt = opt with { AvoidHazardFloors = args[++i] != "off" };
else if (a == "walls" && i + 1 < args.Length) opt = opt with { WallClearance = double.Parse(args[++i], inv) };
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
index bead1b3..18310e5 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
@@ -53,6 +53,7 @@ internal static class ActionPacingTests
r.Add("pacing (stop burst): a stop for our own autorun goes through however long ago it was turned on", OldAutorunStopGoesThrough);
r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits);
r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules);
+ r.Add("pacing: the first swing goes 300 ms after the client reads Melee, not the full stance settle; a use still waits for it", FirstSwingAfterStance);
r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone);
r.Add("refusal: a refused mode change begins no paced action, and the next one is not held by it", RefusedBeginsNothing);
r.Add("refusal: the engine refusing for 5 s burns nothing; a streak past 30 s counts as a failure again, with one log line each end", RefusalStreakFailsOpen);
@@ -352,6 +353,25 @@ internal static class ActionPacingTests
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff waits for the full 800 ms settle");
});
+ // 2026-10-14: every fight's first swing came 0.8 s after the stance change (ModeSettleMs).
+ private static void FirstSwingAfterStance() => Paced(() =>
+ {
+ var host = World(combatMode: 1);
+ host.ChangeCombatModeFor(CombatMode.Melee, "Combat", "target: Melee mode");
+ _t += 60;
+ Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, attackRepeat: true), "the client hasn't read Melee: no swing");
+ FakeHost.CombatModeValue = 2;
+ Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, attackRepeat: true), "Melee just read: not yet");
+ _t += 299;
+ Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, attackRepeat: true), "299 ms after the read: not yet");
+ _t += 1;
+ Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true),
+ "300 ms after the read: the swing goes");
+ Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "a use still waits for the full 800 ms settle");
+ _t += 500;
+ Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "settled: the use goes");
+ });
+
// ── BuffManager ──────────────────────────────────────────────────────────────
private sealed class BuffRig
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs
index 8c4568f..cbd78c1 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
@@ -30,6 +31,69 @@ internal static class HpFailsafeTests
r.Add("hp failsafe: a failed recall does not switch the macro back on past a VTank yield", VTankYieldRespected);
r.Add("hp failsafe: our name unreadable: the recall line is taken as ours, and that is logged once", RecallNameUnreadable);
r.Add("vitals (L8):a heal the server leaves unanswered is not re-sent at the 2.5 s give-up after a 'too busy' answer", VitalResendObeysLatch);
+ r.Add("vitals: under Emergency Heal At with a weapon out and no usable kit, a health potion before Heal Self's wand swap", EmergencyPotionBeforeWandSwap);
+ r.Add("low components: tapers at 10, a scarab at 2 (not Diamond), kinds never carried ignored, a kind run out still counts", LowComponentsRule);
+ }
+
+ // Recall When Low On Components (RynthAiPlugin.LowComponents.cs), the rule itself.
+ private static void LowComponentsRule()
+ {
+ var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var counts = new Dictionary(StringComparer.OrdinalIgnoreCase)
+ {
+ [RynthAiPlugin.TaperKey] = 250, ["Lead Scarab"] = 12, ["Iron Scarab"] = 3,
+ };
+ Check.Null(RynthAiPlugin.LowComponents(counts, seen, 10, 2), "plenty of everything: nothing low");
+ counts[RynthAiPlugin.TaperKey] = 10;
+ Check.Eq(RynthAiPlugin.LowComponents(counts, seen, 10, 2), "tapers 10", "10 tapers: at the line");
+ counts[RynthAiPlugin.TaperKey] = 11;
+ counts["Iron Scarab"] = 2;
+ Check.Eq(RynthAiPlugin.LowComponents(counts, seen, 10, 2), "Iron Scarab 2", "2 Iron Scarabs: low");
+ counts.Remove("Iron Scarab"); // used the last ones: gone from the pack
+ Check.Eq(RynthAiPlugin.LowComponents(counts, seen, 10, 2), "Iron Scarab 0", "run out entirely: still low (seen before)");
+ Check.Null(RynthAiPlugin.LowComponents(counts, seen, 10, 0), "Low Scarabs At 0: scarabs aren't checked");
+
+ var fighter = new HashSet(StringComparer.OrdinalIgnoreCase);
+ Check.Null(RynthAiPlugin.LowComponents(new Dictionary(StringComparer.OrdinalIgnoreCase), fighter, 10, 2),
+ "a character that never carried tapers or scarabs is never low");
+
+ var inv = new[]
+ {
+ new WorldObject(1, "Prismatic Taper"), new WorldObject(2, "Red Taper"),
+ new WorldObject(3, "Diamond Scarab"), new WorldObject(4, "Mana Scarab"), new WorldObject(5, "Scarab Shell Armor"),
+ };
+ var c = RynthAiPlugin.CountComponents(inv);
+ Check.Eq(c.GetValueOrDefault(RynthAiPlugin.TaperKey), 2, "every kind of taper counts together");
+ Check.False(c.ContainsKey("Diamond Scarab"), "Diamond Scarabs never count");
+ Check.Eq(c.GetValueOrDefault("Mana Scarab"), 1, "a Mana Scarab counts");
+ Check.Eq(c.Count, 2, "only tapers and scarabs (not 'Scarab Shell Armor')");
+ }
+
+ // Drakkon, 2026-10-14: 15% health in melee among Depraved Shadows, the kit at 3% (under Kit Min
+ // Success), and the chain went to Heal Self: a wand swap still unanswered when he died 3.2 s later.
+ // The potion came after Heal Self, so it was never reached. Now the emergency step drinks first.
+ private static void EmergencyPotionBeforeWandSwap()
+ {
+ const uint Potion = 0x80001234;
+ try
+ {
+ var r = new Rig(healthPct: 15);
+ FakeHost.CombatModeValue = CombatMode.Melee;
+ FakeHost.Names[Potion] = "Healing Elixir";
+ r.S.UsePotions = true;
+ r.S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Potion), Name = "Healing Elixir", Type = "HealthPotion" });
+ var cache = new WorldObjectCache(r.Host);
+ cache.SetPlayerId(Player);
+ cache.OnCreateObject(Player);
+ _ = cache[unchecked((int)Potion)];
+ cache.Tick();
+ r.B.SetWorldObjectCache(cache);
+
+ r.Run(0, 0.3);
+ Check.True(FakeHost.Uses.Contains(Potion), "the health potion is drunk: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("Vitals")).Take(10)));
+ Check.Eq(FakeHost.Casts.Count, 0, "no Heal Self cast (no wand swap) while the potion goes");
+ }
+ finally { Done(); }
}
// No re-send into a busy server: a client log re-sent a heal every 2.5 s (the vitals give-up) into a server
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ManaReserveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ManaReserveTests.cs
index 9717823..0f2b38f 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/ManaReserveTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/ManaReserveTests.cs
@@ -28,7 +28,7 @@ internal static class ManaReserveTests
r.Add("mana reserve: under 1.5x Stamina to Mana's cost, Stamina to Mana is chosen over an attack", ReserveChoosesStaminaToMana);
r.Add("mana reserve: under Stamina to Mana's cost, no attack spam and no 15 s park on 'not enough Mana'", StarvedNoSpamNoPark);
r.Add("mana reserve: as mana regenerates, the level it can pay for goes, then attacks resume", RecoversAsManaRegenerates);
- r.Add("mana reserve: stamina too low for Stamina to Mana - stamina is refilled first", StaminaFirst);
+ r.Add("mana reserve: stamina too low for Stamina to Mana (under Re-stam At, at least 15%) - stamina is refilled first", StaminaFirst);
r.Add("mana reserve: combat holds an attack it can't pay for, and casts once mana is back", CombatHoldsCast);
r.Add("mana reserve: a melee fighter's attacks aren't held; Get Mana At off means no reserve", MeleeAndOff);
r.Add("mana reserve: the dat's BaseMana is read (when this PC has a portal.dat)", DatBaseMana);
@@ -212,6 +212,18 @@ internal static class ManaReserveTests
off.S.RestamAt = 0;
Check.True(off.B.CheckVitals(), "Re-stam At 0: still refilled for Stamina to Mana");
Check.Eq(FamilyOfCast(0), Family("Revitalize Self I"), "Revitalize");
+
+ // 2026-10-14: the floor is Re-stam At (when over 15): at 25% stamina with Re-stam At 30,
+ // stamina is refilled before Stamina to Mana (each one cost Drakkon 110-126 stamina).
+ var floor = new Rig(mana: 50, stamina: 96); // 25%
+ floor.S.RestamAt = 30;
+ Check.Eq(floor.B.StaminaToManaFloorPct(), 30, "the floor is Re-stam At");
+ Check.True(floor.B.CheckVitals(), "vitals act");
+ Check.Eq(FamilyOfCast(0), Family("Revitalize Self I"), $"25% under Re-stam At 30: stamina first ({NameOf(FakeHost.Casts[0].SpellId)})");
+ var over = new Rig(mana: 50, stamina: 134); // 35%
+ over.S.RestamAt = 30;
+ Check.True(over.B.CheckVitals(), "vitals act");
+ Check.Eq(FamilyOfCast(0), Family("Stamina to Mana Self I"), $"35%: Stamina to Mana ({NameOf(FakeHost.Casts[0].SpellId)})");
}
private static void CombatHoldsCast()
@@ -262,11 +274,14 @@ internal static class ManaReserveTests
private static void MeleeAndOff()
{
- // A melee fighter (no combat manager: the stance decides) at low mana: no reserve, no hold.
+ // A melee fighter (no combat manager: the stance decides) at low mana: no hold of the fight.
var melee = new Rig(mana: 1, combatMode: CombatMode.Melee);
Check.False(melee.B.WantsManaNow(), "melee: vitals don't hold the fight for mana");
- melee.V.CurrentMana = 85; // 22%: over Get Mana At 20%, under a caster's reserve (90)
- Check.False(melee.B.ManaUnderLine(true, out int line), $"melee: only Get Mana At ({line})");
+ // But the reserve is its refill line too (2026-10-14: a melee character's buffs spent mana under
+ // Stamina to Mana's cost and nothing could refill it).
+ melee.V.CurrentMana = 85; // 22%: over Get Mana At 20%, under the reserve (90)
+ Check.True(melee.B.ManaUnderLine(true, out int line), $"melee: under the reserve ({line})");
+ Check.Eq(line, 90, "the line is the reserve");
// Get Mana At 0 (mana recharge off in combat): no reserve, nothing held.
var off = new Rig(mana: 100, getManaAt: 0);
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolDoorwayTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolDoorwayTests.cs
index 6f274b5..a8c5070 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolDoorwayTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolDoorwayTests.cs
@@ -76,6 +76,8 @@ internal static class PatrolDoorwayTests
r.Add("dungeon doorways: in a short chamfered bend (crypt corner) the points come off the bend's outer wall", ChamferedBend);
r.Add("dungeon patrol: a dead end's look-in point comes out of the end cap onto the floor", DeadEndLookInOnFloor);
r.Add("dungeon legs: a leg cutting an inside corner gets a corner put in", LegAroundInsideCorner);
+ r.Add("dungeon patrol (sweep): a pillar hall is walked in lanes, every cell within sight of the route; far fewer points than Whole dungeon", SweepPillarHall);
+ r.Add("dungeon patrol (sweep): a wall blocks sight, so two corridors side by side are both walked", SweepWallBlocksSight);
}
// ── Fixture builder ──────────────────────────────────────────────────────
@@ -143,6 +145,93 @@ internal static class PatrolDoorwayTests
new V3((float)x1, (float)y1, 3f), new V3((float)x0, (float)y0, 3f),
};
+ // A 10 x 10 hall of 5 m cells joined by 3 m openings (doorways, so 100 rooms): to the patrol,
+ // what the 0x00AE pillar hall is (2026-10-14).
+ private static (Dungeon D, uint[,] Cells) PillarHall(int n = 10, double size = 5)
+ {
+ var d = new Dungeon();
+ var c = new uint[n, n];
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++)
+ c[i, j] = d.Cell(i * size, j * size, (i + 1) * size, (j + 1) * size);
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++)
+ {
+ double x0 = i * size, y0 = j * size;
+ if (i + 1 < n) d.OpenX(c[i, j], c[i + 1, j], x0 + size, y0 + 1, y0 + 4);
+ if (j + 1 < n) d.OpenY(c[i, j], c[i, j + 1], y0 + size, x0 + 1, x0 + 4);
+ }
+ return (d, c);
+ }
+
+ private static void SweepPillarHall()
+ {
+ var (d, c) = PillarHall();
+ var geo = d.Geo();
+ var whole = DungeonPathfinder.BuildPatrolRoute(d.Graph, c[0, 0], null, geo);
+ var sweep = DungeonPathfinder.BuildPatrolRoute(d.Graph, c[0, 0], null, geo,
+ new DungeonPatrolOptions { Coverage = PatrolCoverage.Sweep, SightMeters = 15 });
+ Check.True(sweep.Points.Count > 0 && sweep.Points.Count * 2 < whole.Points.Count,
+ $"sweep {sweep.Points.Count} points, whole dungeon {whole.Points.Count}");
+ Check.Eq(DungeonPathfinder.LastSweepSeen, DungeonPathfinder.LastSweepCells, "every cell is seen by a stop");
+ Check.True(DungeonPathfinder.LastSweepStops > 1 && DungeonPathfinder.LastSweepStops < 40, $"{DungeonPathfinder.LastSweepStops} stops for 100 cells");
+ // Every cell's middle within the sight distance of the route (its points or the legs between them).
+ double worst = 0;
+ foreach (var node in d.Graph.Values)
+ {
+ double cx = DungeonGeometry.NavToWorld(node.EW), cy = DungeonGeometry.NavToWorld(node.NS), best = double.MaxValue;
+ for (int i = 0; i < sweep.Points.Count; i++)
+ {
+ var a = sweep.Points[i]; var b = sweep.Points[(i + 1) % sweep.Points.Count];
+ best = Math.Min(best, SegDist(cx, cy, X(a), Y(a), X(b), Y(b)));
+ }
+ worst = Math.Max(worst, best);
+ }
+ // The route goes through a stop's doorways, not its exact middle: within half a cell of the sight.
+ Check.True(worst <= 15.0 + 2.5, $"the farthest cell is {worst:F1} m from the route (sight 15, cells 5 m)");
+ int stops15 = DungeonPathfinder.LastSweepStops;
+ DungeonPathfinder.BuildPatrolRoute(d.Graph, c[0, 0], null, geo,
+ new DungeonPatrolOptions { Coverage = PatrolCoverage.Sweep, SightMeters = 30 });
+ Check.True(DungeonPathfinder.LastSweepStops < stops15, $"a longer sight, fewer stops ({DungeonPathfinder.LastSweepStops} vs {stops15})");
+ }
+
+ private static void SweepWallBlocksSight()
+ {
+ // Two corridors of 8 cells (y 0..5 and 5..10), joined only at their two ends, a wall all along
+ // between them. Without the wall one corridor's walk would see the other at 15 m.
+ var d = new Dungeon();
+ var a = new uint[8]; var b = new uint[8];
+ for (int i = 0; i < 8; i++) { a[i] = d.Cell(i * 5, 0, i * 5 + 5, 5); b[i] = d.Cell(i * 5, 5, i * 5 + 5, 10); }
+ for (int i = 0; i + 1 < 8; i++) { d.OpenX(a[i], a[i + 1], i * 5 + 5, 1, 4); d.OpenX(b[i], b[i + 1], i * 5 + 5, 6, 9); }
+ d.OpenY(a[0], b[0], 5, 1, 4);
+ d.OpenY(a[7], b[7], 5, 36, 39);
+ for (int i = 1; i < 7; i++) { d.Wall(a[i], i * 5, 5, i * 5 + 5, 5); d.Wall(b[i], i * 5, 5, i * 5 + 5, 5); }
+ var geo = d.Geo();
+ var sweep = DungeonPathfinder.BuildPatrolRoute(d.Graph, a[0], null, geo,
+ new DungeonPatrolOptions { Coverage = PatrolCoverage.Sweep, SightMeters = 15 });
+ Check.Eq(DungeonPathfinder.LastSweepSeen, DungeonPathfinder.LastSweepCells, "every cell seen");
+ // A leg along each corridor through its middle (x 20).
+ bool Leg(Func side)
+ {
+ for (int i = 0; i < sweep.Points.Count; i++)
+ {
+ var p = sweep.Points[i]; var q = sweep.Points[(i + 1) % sweep.Points.Count];
+ if (Math.Min(X(p), X(q)) < 20 && Math.Max(X(p), X(q)) > 20 && side(Y(p)) && side(Y(q))) return true;
+ }
+ return false;
+ }
+ bool south = Leg(y => y < 5), north = Leg(y => y > 5);
+ Check.True(south && north, "both corridors walked in the middle: " + string.Join(" ", sweep.Points.Select(p => $"({X(p):F0},{Y(p):F0})")));
+ }
+
+ private static double SegDist(double px, double py, double ax, double ay, double bx, double by)
+ {
+ double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
+ double t = l2 < 1e-9 ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / l2, 0, 1);
+ double qx = ax + dx * t - px, qy = ay + dy * t - py;
+ return Math.Sqrt(qx * qx + qy * qy);
+ }
+
private static double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW);
private static double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS);
@@ -554,8 +643,13 @@ internal static class PatrolDoorwayTests
var (d, west, corner, north) = ChamferDungeon();
var geo = d.Geo();
var pts = Path(d, geo, -8, 1.67, 5, 15, west, corner, north);
- var inBend = pts.Where(p => X(p) > 0 && Y(p) < 6.67).ToList();
- Check.True(inBend.Count >= 1, $"points in the bend ({inBend.Count})");
+ // The bend is walked through: a point at or past the west opening and one at or before the
+ // north one. Since 2026-10-14 the two openings (at right angles) are one run: their centres,
+ // and the leg between cuts the chamfer (the checks below keep it on the floor and off the walls).
+ string path = string.Join(" ", pts.Select(p => $"({X(p):F2},{Y(p):F2})"));
+ Check.True(pts.Any(p => X(p) >= -0.01 && Y(p) < 6.67) && pts.Any(p => X(p) > 0 && Y(p) <= 6.68),
+ "the path goes through the bend: " + path);
+ Check.True(pts.Count <= 5, "no doubling back in the bend: " + path);
foreach (var p in pts)
Check.True(Clear(geo, p) >= 0.98, $"({X(p):F2}, {Y(p):F2}) is 1 m from every wall ({Clear(geo, p):F2})");
// Before: the exit point on the west opening's centre line, 1 m in: 0.47 m from the outer wall.
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolSettingsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolSettingsTests.cs
index 5f4f79a..adc9319 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolSettingsTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolSettingsTests.cs
@@ -154,39 +154,47 @@ internal static class PatrolSettingsTests
var s = new LegacyUiSettings
{
DunPatrolCoverage = 7, DunPatrolSkipDeadEnds = 99, DunPatrolAvoidFloors = false,
- DunPatrolWallDistance = 9f, DunPatrolLookInSize = -4f,
+ DunPatrolWallDistance = 9f, DunPatrolLookInSize = -4f, DunPatrolSightYd = 200f,
};
var o = RynthAiPlugin.PatrolOptionsFrom(s);
- Check.Eq(o.Coverage, PatrolCoverage.Everything, "coverage 7 -> 2 (everything)");
+ Check.Eq(o.Coverage, PatrolCoverage.Sweep, "coverage 7 -> 3 (sweep, the last)");
+ Check.Near(o.SightMeters, 60.0, 1e-9, "sight 200 -> 60 m");
Check.Eq(o.MaxDeadEndCells, 30, "dead ends 99 -> 30");
Check.False(o.AvoidHazardFloors, "floors off");
Check.Near(o.WallClearance, 2.0, 1e-9, "walls 9 -> 2 m");
Check.Near(o.LookInRoomMeters, 3.0, 1e-9, "look-in -4 -> 3 m");
- s.DunPatrolCoverage = 1; s.DunPatrolSkipDeadEnds = 5; s.DunPatrolWallDistance = 1.5f; s.DunPatrolLookInSize = 20f;
+ s.DunPatrolCoverage = 1; s.DunPatrolSkipDeadEnds = 5; s.DunPatrolWallDistance = 1.5f; s.DunPatrolLookInSize = 20f; s.DunPatrolSightYd = 25f;
o = RynthAiPlugin.PatrolOptionsFrom(s);
- Check.True(o.Coverage == PatrolCoverage.LoopsOnly && o.MaxDeadEndCells == 5 && o.WallClearance == 1.5 && o.LookInRoomMeters == 20,
+ Check.True(o.Coverage == PatrolCoverage.LoopsOnly && o.MaxDeadEndCells == 5 && o.WallClearance == 1.5 && o.LookInRoomMeters == 20 && o.SightMeters == 25,
"in-range values pass through: " + o.Describe());
+ s.DunPatrolCoverage = 3;
+ o = RynthAiPlugin.PatrolOptionsFrom(s);
+ Check.True(o.Coverage == PatrolCoverage.Sweep && o.Describe().Contains("sight 25 m"), "sweep, and its sight in the description: " + o.Describe());
}
private static void EnginePayload()
{
- var s = new LegacyUiSettings { DunPatrolCoverage = 1, DunPatrolSkipDeadEnds = 6, DunPatrolAvoidFloors = false, DunPatrolWallDistance = 1.25f, DunPatrolLookInSize = 15f };
+ var s = new LegacyUiSettings { DunPatrolCoverage = 1, DunPatrolSkipDeadEnds = 6, DunPatrolAvoidFloors = false, DunPatrolWallDistance = 1.25f, DunPatrolLookInSize = 15f, DunPatrolSightYd = 30f };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(sent.DunPatrolCoverage == 1 && sent.DunPatrolSkipDeadEnds == 6 && sent.DunPatrolAvoidFloors == false
- && sent.DunPatrolWallDistance == 1.25f && sent.DunPatrolLookInSize == 15f, "every patrol setting sent to the engine face");
+ && sent.DunPatrolWallDistance == 1.25f && sent.DunPatrolLookInSize == 15f && sent.DunPatrolSightYd == 30f, "every patrol setting sent to the engine face");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.DunPatrolCoverage == 1 && s.DunPatrolSkipDeadEnds == 6 && !s.DunPatrolAvoidFloors && s.DunPatrolWallDistance == 1.25f
- && s.DunPatrolLookInSize == 15f, "a save from an engine without them leaves them alone");
+ && s.DunPatrolLookInSize == 15f && s.DunPatrolSightYd == 30f, "a save from an engine without them leaves them alone");
+ dash.ApplySettingsJson("{\"DunPatrolCoverage\":3,\"DunPatrolSightYd\":40}");
+ Check.True(s.DunPatrolCoverage == 3 && s.DunPatrolSightYd == 40f, "sweep and its sight applied");
+ dash.ApplySettingsJson("{\"DunPatrolSightYd\":1}");
+ Check.True(s.DunPatrolSightYd == 5f, "sight 1 -> 5 (clamped)");
dash.ApplySettingsJson("{\"DunPatrolCoverage\":2,\"DunPatrolSkipDeadEnds\":0,\"DunPatrolAvoidFloors\":true,\"DunPatrolWallDistance\":0.75,\"DunPatrolLookInSize\":30}");
Check.True(s.DunPatrolCoverage == 2 && s.DunPatrolSkipDeadEnds == 0 && s.DunPatrolAvoidFloors && s.DunPatrolWallDistance == 0.75f
&& s.DunPatrolLookInSize == 30f, "a save with them applies them");
dash.ApplySettingsJson("{\"DunPatrolCoverage\":9,\"DunPatrolSkipDeadEnds\":40,\"DunPatrolWallDistance\":0.1,\"DunPatrolLookInSize\":100}");
- Check.True(s.DunPatrolCoverage == 2 && s.DunPatrolSkipDeadEnds == 30 && s.DunPatrolWallDistance == 0.5f && s.DunPatrolLookInSize == 40f,
+ Check.True(s.DunPatrolCoverage == 3 && s.DunPatrolSkipDeadEnds == 30 && s.DunPatrolWallDistance == 0.5f && s.DunPatrolLookInSize == 40f,
$"out of range clamped ({s.DunPatrolCoverage}, {s.DunPatrolSkipDeadEnds}, {s.DunPatrolWallDistance}, {s.DunPatrolLookInSize})");
}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs
index 0f5e119..73f0fa9 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs
@@ -51,6 +51,7 @@ internal static class WeaponTests
r.Add("refusal: a refused stance change in combat's equip pass sets no backoff and starts no stuck clock", StanceRefusedKeepsBackoff);
r.Add("weapon choice: an unlisted wand is never picked (Damage tab, learned, pack, name)", UnlistedNeverPicked);
r.Add("Items list: a listed item no longer carried is reported missing (pack, hand, unknown)", MissingFromPack);
+ r.Add("weapon choice: a listed weapon someone else now has (sold) is skipped, even as this monster's Damage tab pick", SoldWeaponSkipped);
r.Add("weapon swap: one in flight, confirmed, retry cap, then what's in hand", SwapOneInFlight);
r.Add("weapon swap: no flip-flop between two weapons", SwapNoFlipFlop);
r.Add("weapon swap: a new target that wants the weapon just swapped away from gets it at once (Drakkon 2026-10-12)", SwapBackForNewTarget);
@@ -670,6 +671,46 @@ internal static class WeaponTests
}
}
+ // 2026-10-14: a sold Flaming Greataxe, still listed and still known to the client, was the weapon
+ // chosen for the monster; three wield tries over 13 s with the character standing in the fight.
+ private static void SoldWeaponSkipped()
+ {
+ const uint Vendor = 0x80099999;
+ FakeHost.Reset();
+ FakeHost.WeaponCalls = true;
+ FakeHost.CombatModeValue = CombatMode.Magic;
+ FakeHost.Names[ListedWand] = "Wand"; FakeHost.ItemTypes[ListedWand] = 0x8000;
+ FakeHost.Ints[(ListedWand, 45)] = 0x40; // Lightning
+ FakeHost.Names[FireWand] = "Fire Wand"; FakeHost.ItemTypes[FireWand] = 0x8000;
+ FakeHost.Ints[(FireWand, 18)] = 0x20; // Fire
+ FakeHost.Wcids[Monster] = 1535;
+ FakeHost.Containers[ListedWand] = Player; // ours
+ FakeHost.Containers[FireWand] = Vendor; // sold: the vendor has it now
+ var host = FakeHost.Create();
+ var cache = FakeHost.MakeCache(host, Player, new[] { ListedWand, FireWand });
+ var s = new LegacyUiSettings();
+ var store = new MonsterDamageStore();
+ var c = new CombatManager(host, s, cache);
+ c.SetPlayerId(Player);
+ c.SetDamageStores(null, store);
+ c.CanCastOverride = e => e != "Nether";
+ s.ItemRules = new List
+ {
+ new() { Id = unchecked((int)ListedWand), Name = "Wand", Element = "Lightning", ElementSource = "properties" },
+ new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "properties" },
+ };
+ store.SetManualWeapon(1535, FireWand); // the Damage tab's pick for this monster
+ var target = new WorldObject(unchecked((int)Monster), "Ethereal Wisp", AcObjectClass.Monster);
+
+ var plan = c.PlanFor(target, null);
+ Check.Eq(unchecked((uint)plan.WeaponId), ListedWand, "the carried wand, not the sold Damage tab pick");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("isn't in your pack")), "the skip is logged: " + string.Join(" | ", FakeHost.Logs.Take(10)));
+ Check.Eq(c.ListedCandidates().Count, 1, "the sold weapon isn't a candidate at all");
+
+ FakeHost.Containers[FireWand] = Player; // bought back
+ Check.Eq(c.ListedCandidates().Count, 2, "back in the pack: a candidate again");
+ }
+
private static void MissingFromPack()
{
// 2026-10-11: Drakkon's buff wand left his pack and the Items slot still just said "Wand".