Snapshot for release 2026.10.8.1 (internal f3d67ec)

This commit is contained in:
Tom Bohar 2026-10-08 17:29:51 -04:00
commit 0daf0a44a3
49 changed files with 2802 additions and 121 deletions

View file

@ -158,6 +158,15 @@ public class BuffManager : IDisposable
private readonly Dictionary<int, DateTime> _buffFailCooldownUntil = new();
private const double BuffFailCooldownSec = 120.0;
// A vital spell LEVEL the server refused for missing components (Revitalize, Heal, Stamina
// to Mana...): that level is passed over for NoComponentsLevelSec and the next lower level
// with components is cast instead. It used to park the whole family, then retry the same
// top level the character had no components for (2026-10-08).
private readonly Dictionary<int, DateTime> _noComponentsUntil = new();
private const double NoComponentsLevelSec = 600.0;
private bool LevelLacksComponents(int spellId)
=> _noComponentsUntil.TryGetValue(spellId, out DateTime until) && DateTime.Now < until;
// Per-family SILENT no-show counter. Distinct from _buffFailCooldownUntil
// (which catches chat-explicit hard rejects). This catches the /god case:
// skill is Trained → IsSkillUsable says yes → BuildDynamicBuffList includes
@ -476,6 +485,27 @@ public class BuffManager : IDisposable
{ AcSkillType.Summoning, "Summoning Mastery" },
};
/// <summary>
/// The prots and banes the Buffing settings let the player untick (LegacyUiSettings.DisabledBuffs),
/// paired by element for the two-column grid: (buff base name, label). Armor Self and
/// Impenetrability head the columns. The cast order stays BuildDynamicBuffList's.
/// </summary>
internal static readonly (string Buff, string Label)[] ToggleProtections =
{
("Armor Self", "Armor"), ("Fire Protection Self", "Fire"), ("Cold Protection Self", "Cold"),
("Acid Protection Self", "Acid"), ("Lightning Protection Self", "Lightning"),
("Blade Protection Self", "Blade"), ("Piercing Protection Self", "Piercing"),
("Bludgeoning Protection Self", "Bludgeoning"),
};
internal static readonly (string Buff, string Label)[] ToggleBanes =
{
("Impenetrability", "Impenetrability"), ("Flame Bane", "Flame"), ("Frost Bane", "Frost"),
("Acid Bane", "Acid"), ("Lightning Bane", "Lightning"),
("Blade Bane", "Blade"), ("Piercing Bane", "Piercing"),
("Bludgeoning Bane", "Bludgeoning"),
};
public BuffManager(RynthCoreHost host, LegacyUiSettings settings, SpellManager spellManager, PlayerVitalsCache vitals)
{
_host = host;
@ -1620,7 +1650,7 @@ public class BuffManager : IDisposable
_healWaitKind = "server finishing the last cast";
return true;
}
int spellId = FindBestSpellId(baseName, AcSkillType.LifeMagic);
int spellId = _spellManager.GetDynamicSelfBuffId(baseName, AcSkillType.LifeMagic, LevelLacksComponents);
// A heal with nothing known at the allowed tiers: the lowest known tier above them.
// Vitae can drop Life Magic under a tier line while only higher tiers are known.
if (spellId == 0 && baseName is "Heal Self" or "Stamina to Health Self")
@ -3107,6 +3137,12 @@ public class BuffManager : IDisposable
final.AddRange(step5_LifeAndItem);
final.AddRange(step6_WeaponAuras);
final.AddRange(step7_ArmorBanes);
// Buffs the player unticked (Buffing settings: prots and banes) leave the list here, so
// the cast loop never casts them and NeedsAnyBuff never waits on them: a skipped buff
// can't hold the bot in Buffing.
if (_settings.DisabledBuffs.Count > 0)
final.RemoveAll(_settings.IsBuffDisabled);
return final;
}
@ -3316,7 +3352,15 @@ public class BuffManager : IDisposable
if (_pendingSpellId != 0)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
if (pendingSpell != null)
bool noCompsVital = _pendingSpellId == _pendingVitalSpellId
&& (lower.Contains("components") || lower.Contains("missing some required"));
if (pendingSpell != null && noCompsVital)
{
// A vital spell: pass over this level only; the next lower one goes next.
_noComponentsUntil[_pendingSpellId] = DateTime.Now.AddSeconds(NoComponentsLevelSec);
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 60:0} min.", 2);
}
else if (pendingSpell != null)
{
if (IsItemEnchantment(pendingSpell.Name))
{

View file

@ -184,6 +184,60 @@ public partial class CombatManager : IDisposable
private DateTime _faceSettledAt = DateTime.MinValue;
private const double FACE_SETTLE_MS = 140.0; // let the turn-stop reach the server (≥ one 30Hz tick) before the cast packet
// ── Wall facing (2026-10-08) ─────────────────────────────────────────────
// A wall is untargeted: ACE launches it along the caster's facing and never turns the caster
// for it (see CountMonstersInWallPath). So before a wall the bot turns the character itself:
// an instant heading snap (TurnToHeading) when it is more than WallFaceToleranceDeg off the
// target, then no cast until WallFaceSettleMs later so the server has the new heading. The
// snap changes only the client's heading; the client tells the server in its next position
// event, which goes out at most once per second while the position or heading keeps
// changing (CommandInterpreter::ShouldSendPositionEvent 0x006B5520; the 1.0 s interval is set
// in the constructor 0x006B4D80), so the settle covers a full second plus a frame. Only ever
// inside AttackWithMagic, i.e. after the cadence guard and the gesture gate: never while a
// cast is resolving, and nothing turns during the wall's windup. Targeted shapes are unchanged.
// Always face the target exactly before a wall (owner, 2026-10-08: "for walls he always has to
// turn to the target"): a wall flies straight, so a few degrees off misses at range. Only a
// facing within WallFaceToleranceDeg casts without a turn.
internal const double WallFaceToleranceDeg = 1.0;
internal const double WallFaceSettleMs = 1100.0;
// After the settle the wall goes if the target is still within this of the snapped heading;
// further (it moved during the second) the bot turns again, at most WallFaceMaxSnaps times
// per wall, then casts anyway rather than chase a running monster forever.
internal const double WallFaceDriftDeg = 5.0; // the most allowed (close in)
internal const int WallFaceMaxSnaps = 3;
// How far to the side of the wall's centre line the target may have moved during the settle
// (metres): at 70 yd, 5 degrees is 6 m off - wider than half the wall (owner, 2026-10-08).
internal const double WallAimSlackMeters = 1.8;
/// <summary>The drift allowed after the settle for a target this far away: the angle that puts
/// it <see cref="WallAimSlackMeters"/> to the side, between the tolerance and WallFaceDriftDeg.</summary>
internal static double WallDriftAllowedDeg(double distanceMeters)
{
if (distanceMeters <= 0.1) return WallFaceDriftDeg;
double deg = Math.Atan2(WallAimSlackMeters, distanceMeters) * 180.0 / Math.PI;
return Math.Clamp(deg, WallFaceToleranceDeg, WallFaceDriftDeg);
}
private double WallDriftAllowedDeg(int targetId)
{
try
{
if (_host.TryGetPlayerPose(out _, out float px, out float py, out _, out _, out _, out _, out _)
&& _host.TryGetObjectPosition((uint)targetId, out _, out float tx, out float ty, out _))
return WallDriftAllowedDeg(Math.Sqrt((tx - px) * (tx - px) + (ty - py) * (ty - py)));
}
catch { }
return WallFaceToleranceDeg;
}
private int _wallFaceSnaps;
private int _wallFaceTarget;
private DateTime _wallFaceAt = DateTime.MinValue;
// Set by AttackWithMagic when it held a wall for its turn: Think then ends the tick without
// counting it as an attack (no attack interval starts, so the wall goes once settled).
private bool _wallFaceHeld;
/// <summary>Tests: the clock the wall facing reads.</summary>
internal Func<DateTime> WallClock { get; set; } = () => DateTime.Now;
// ── Magic cast cadence guard ────────────────────────────────────────────
// Don't issue the next combat cast until the previous one's server windup
// has resolved (a UseDone arrived, or a hard timeout). Re-casting into the
@ -214,7 +268,7 @@ public partial class CombatManager : IDisposable
private DateTime _lastNoSpellChatAt = DateTime.MinValue;
private readonly Dictionary<string, DateTime> _ringMissingChatAt = new(StringComparer.OrdinalIgnoreCase);
private const double NoSpellChatIntervalMs = 30_000;
private bool _lastCastWasRing = false;
private bool _lastCastWasRing = false; // the last attack hit an area: a ring, or a wall (2026-10-08)
private const double ATTACK_SPELL_COOLDOWN_MS = 100.0;
private bool _returnToPhysicalCombat = false;
@ -535,6 +589,7 @@ public partial class CombatManager : IDisposable
public int Id;
public double Distance;
public double Angle; // absolute facing error to target, degrees (0 = directly ahead)
public double Bearing; // heading from the player to it, degrees (0 = north, clockwise); NaN = unknown
public string Name;
}
@ -860,16 +915,18 @@ public partial class CombatManager : IDisposable
}
double angle = 180.0;
double bearing = double.NaN;
if (hasPose && hasMobPos) // the mob's position was read for the distance above
{
double desired = Math.Atan2(tx - ppx, ty - ppy) * (180.0 / Math.PI);
if (desired < 0) desired += 360.0;
bearing = desired;
double err = desired - playerHeadingDeg;
while (err > 180.0) err -= 360.0;
while (err < -180.0) err += 360.0;
angle = Math.Abs(err);
}
_scannedTargets.Add(new ScannedTarget { Id = wo.Id, Distance = dist, Angle = angle, Name = wo.Name });
_scannedTargets.Add(new ScannedTarget { Id = wo.Id, Distance = dist, Angle = angle, Bearing = bearing, Name = wo.Name });
}
// Primary: closest first. Tiebreaker within 0.5yd: smallest facing angle first.
@ -1023,8 +1080,22 @@ public partial class CombatManager : IDisposable
{ "Yield", new[] { "Magic Yield Other", "Yield" } },
};
// Shape index into the SpellShapes / VoidSpellShapes rows.
internal const int ShapeArc = 0, ShapeRing = 1, ShapeStreak = 2, ShapeBolt = 3, ShapeBlast = 4;
// Shape index into the SpellShapes / VoidSpellShapes rows. ShapeWall (2026-10-08) has no row:
// walls have no tiered base names and are found by spell category (WallCategories).
internal const int ShapeArc = 0, ShapeRing = 1, ShapeStreak = 2, ShapeBolt = 3, ShapeBlast = 4, ShapeWall = 5;
// Wall spells per element: ACE SpellCategory AcidWall 229, BludgeoningWall 230, ColdWall 231,
// ElectricWall 232, FireWall 233, PiercingWall 234, SlashingWall 235 (column 3 of SpellData.txt).
// Retail has one per element (Blistering Creeper, Hammering Crawler, Foon-Ki's Glacial Floe,
// Os' Wall, Slithering Flames, Spike Strafe, Bed of Blades: power 200, so level 5 by ACE's
// server formula); the categories also hold other spells (Demon's Tongues, Burning Earth, the
// "... Whip" spells) that a character on some server may know, so a wall is picked by category,
// not by name. Void (Nether) has no walls.
private static readonly Dictionary<string, int> WallCategories = new(StringComparer.OrdinalIgnoreCase)
{
{ "Acid", 229 }, { "Bludgeon", 230 }, { "Cold", 231 }, { "Lightning", 232 },
{ "Fire", 233 }, { "Pierce", 234 }, { "Blade", 235 }, { "Slash", 235 },
};
// Base names per element, by shape: Arc, Ring, Streak, Bolt, Blast. Every non-ring base has
// "{base} I".."VI" (blasts: III-VI only, retail has no blast I/II) and "Incantation of {base}"
@ -2290,6 +2361,9 @@ public partial class CombatManager : IDisposable
/// the full interval anyway.</summary>
internal const double NewTargetCastFloorMs = 300;
/// <summary>The least Attack Spell Delay on an engine without the server gates.</summary>
internal const double NoGatesAttackFloorMs = 250;
/// <summary>True when <see cref="BusyCount"/> is positive only because AC lowered it inline at a
/// server UseDone the busy hook can't see (see <see cref="CombatBusyGate"/>).</summary>
internal bool BusyIsLeftover()
@ -2314,7 +2388,12 @@ public partial class CombatManager : IDisposable
internal static double AttackIntervalMs(int combatMode, int attackSpellIntervalMs, bool hasServerGates, bool newTarget)
{
if (combatMode != CombatMode.Magic) return 1000.0;
double interval = attackSpellIntervalMs > 0 ? attackSpellIntervalMs : 1500;
// 0 is allowed (2026-10-08): no delay of its own, the server gates (UseDone and the cast
// gesture) alone hold the next cast until the last one is done. A file without the setting
// keeps 1500 (the payload is nullable). An engine without those gates keeps a 250 ms floor,
// the old slider minimum, so casts can't be sent back to back into "You're too busy!".
double interval = attackSpellIntervalMs >= 0 ? attackSpellIntervalMs : 1500;
if (!hasServerGates) interval = Math.Max(interval, NoGatesAttackFloorMs);
if (newTarget && hasServerGates) return Math.Min(interval, NewTargetCastFloorMs);
return interval;
}
@ -2687,6 +2766,9 @@ public partial class CombatManager : IDisposable
// MELEE the same: ACE's HandleActionTargetedMeleeAttack_Inner rotates to the
// target (past melee_max_angle) before the swing, so the servo made the same
// swing-spin-swing with a knife in an Olthoi swarm (2026-09-29, Lucy).
// The one exception is a WALL spell (2026-10-08): untargeted, so the server doesn't
// turn for it. AttackWithMagic snaps the heading before a wall (HoldForWallFacing),
// behind the cadence guard above, and never during a windup.
if (CurrentCombatMode == CombatMode.Magic || CurrentCombatMode == CombatMode.Missile
|| CurrentCombatMode == CombatMode.Melee)
{
@ -2775,6 +2857,15 @@ public partial class CombatManager : IDisposable
AttackWithMagic(targetObj);
// A wall held for its turn (2026-10-08): nothing was sent but a heading snap. End
// the tick here so it doesn't count as an attack: the attack interval doesn't start
// and the wall goes the first tick after the settle (HoldForWallFacing).
if (_wallFaceHeld)
{
_tickWait = CombatLatencyTracker.Wait.Face;
return true;
}
// Don't restore the physical weapon on top of a cast just issued this tick
// (AttackWithMagic → MarkCombatCastIssued): the UseObject + re-equip below would
// truncate the in-flight gesture and strand Player.IsBusy. Defer one windup
@ -4625,6 +4716,64 @@ public partial class CombatManager : IDisposable
catch { }
}
/// <summary>
/// Before a wall at <paramref name="targetId"/>: true = don't cast this tick. Facing within
/// <see cref="WallFaceToleranceDeg"/>: false, cast (no turn). Further off: snap the heading to
/// the target and hold for <see cref="WallFaceSettleMs"/>, then cast, unless the target has
/// since drifted more than <see cref="WallFaceDriftDeg"/> off (then snap again).
/// </summary>
internal bool HoldForWallFacing(int targetId)
{
DateTime now = WallClock();
if (_wallFaceAt != DateTime.MinValue && _wallFaceTarget == targetId)
{
if ((now - _wallFaceAt).TotalMilliseconds < WallFaceSettleMs) return true; // the server catching up
_wallFaceAt = DateTime.MinValue;
if (GetFacingError(targetId) <= WallDriftAllowedDeg(targetId) || _wallFaceSnaps >= WallFaceMaxSnaps)
{
_wallFaceSnaps = 0;
return false; // turned and settled: cast
}
}
else _wallFaceSnaps = 0;
_wallFaceAt = DateTime.MinValue;
if (!TryGetHeadingTo(targetId, out double desiredDeg, out double error)) return false; // can't tell: cast as is
if (error <= WallFaceToleranceDeg) return false;
if (!_host.HasTurnToHeading) return false; // FindBestShapedSpell doesn't pick a wall then
if (!_host.TurnToHeadingBy("Combat", (float)desiredDeg)) return true; // held by the pacer: next tick
_wallFaceTarget = targetId;
_wallFaceAt = now;
_wallFaceSnaps++;
_host.Log($"[CombatCast] wall: facing 0x{(uint)targetId:X8} first ({error:0} deg off), casting in {WallFaceSettleMs:0} ms");
return true;
}
/// <summary>The heading from the player to <paramref name="targetId"/> (0 = north, clockwise)
/// and how far the player's facing is off it (absolute degrees).</summary>
private bool TryGetHeadingTo(int targetId, out double desiredDeg, out double absError)
{
desiredDeg = 0; absError = 180.0;
try
{
if (!_host.TryGetPlayerPose(out _, out float px, out float py, out _,
out float qw, out _, out _, out float qz))
return false;
if (!_host.TryGetObjectPosition((uint)targetId, out _, out float tx, out float ty, out _))
return false;
desiredDeg = Math.Atan2(tx - px, ty - py) * (180.0 / Math.PI);
if (desiredDeg < 0) desiredDeg += 360.0;
double physYawDeg = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
double currentDeg = ((-physYawDeg) % 360.0 + 720.0) % 360.0;
double error = desiredDeg - currentDeg;
while (error > 180.0) error -= 360.0;
while (error < -180.0) error += 360.0;
absError = Math.Abs(error);
return true;
}
catch { return false; }
}
private void ClearCombatTurnMotions()
{
_host.SetMotionBy("Combat", MotionTurnRight, false);
@ -4888,6 +5037,7 @@ public partial class CombatManager : IDisposable
private void AttackWithMagic(WorldObject target)
{
_wallFaceHeld = false;
if (_spellManager == null || target == null) return;
// Hard safety veto: never cast offensive magic at something AC's combat
@ -4988,7 +5138,7 @@ public partial class CombatManager : IDisposable
if (rule != null && PickBaseShape(rule) < 0)
{
_host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast all false) — no offensive cast");
_host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast/Wall all false) — no offensive cast");
LastCombatSkipReason = "no-attack-shapes"; // D4 record-only
return;
}
@ -5013,6 +5163,16 @@ public partial class CombatManager : IDisposable
}
}
LogArcChoice(rule, target, castShape);
// A wall flies along the caster's facing and the server doesn't turn the caster for it:
// face the target first and let the new heading reach the server (2026-10-08).
if (offensiveSpellId != 0 && castShape == ShapeWall && HoldForWallFacing(activeTargetId))
{
_wallFaceHeld = true;
LastCombatSkipReason = "wall-face"; // D4 record-only
return;
}
// A ring or a wall hits several monsters: its damage isn't the fight target's alone.
bool multiTarget = isRing || castShape == ShapeWall;
if (offensiveSpellId != 0)
{
LastCombatSkipReason = "cast"; // D4 record-only: offensive cast issued this tick
@ -5028,7 +5188,8 @@ public partial class CombatManager : IDisposable
SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal
CastsSinceLastKill++; // reset in OnKillNotification when a kill lands
_lastSpellCast = DateTime.Now;
_lastCastWasRing = isRing;
_lastCastWasRing = multiTarget; // walls too: area casts (2026-10-08)
_wallFaceAt = DateTime.MinValue; // the next wall checks its facing afresh
// _offensiveCastThisCycle is NOT set here anymore — a cast
// attempt that the server refuses (e.g. "You're too busy!")
// must not count toward the blacklist miss streak. The
@ -5051,10 +5212,16 @@ public partial class CombatManager : IDisposable
// castable tier (which made every magic kill record tier 8). Fall back to the
// old max-tier only if the level can't be derived, so it never regresses to blank.
int castLevel = SpellTableStub.GetById(offensiveSpellId)?.Level ?? 0;
// Walls have no tier in their names: their level from their power (2026-10-08).
if (castLevel <= 0 && SpellDatabase.TryGetCategoryAndPower(offensiveSpellId, out _, out int castPower))
castLevel = SpellDatabase.LevelFromPower(castPower);
int castTierMag = castLevel > 0 ? castLevel : Math.Max(warTier, voidTier);
// Ring spells are stored as a NEGATIVE tier so the Damage tab can render them as
// "R<level>" (e.g. a level-2 ring = -2 -> "R2"); non-ring stays positive; 0 = none.
_lastCastTier = isRing ? -castTierMag : castTierMag;
// Walls are filed with the rings (2026-10-08): an area cast's kills and casts-to-kill
// must not mix with the single-target tier of the same level. (The Damage tab shows
// them as "R<level>" until it has a label of its own for walls.)
_lastCastTier = multiTarget ? -castTierMag : castTierMag;
// Record the latest tier used vs this monster so the Damage tab's collapsed row
// reflects it immediately (covers ring casts, which skip RecordHit).
if (_fightTargetWcid != 0) _damageStore?.NoteCast(_fightTargetWcid, _lastCastTier, _fightTargetName);
@ -5071,7 +5238,7 @@ public partial class CombatManager : IDisposable
_lastFightCount = _fightCastCount;
StampRecentFight();
}
EvaluateKillShot(_lastCastWeaponId, element, _lastCastTier, isRing);
EvaluateKillShot(_lastCastWeaponId, element, _lastCastTier, multiTarget);
}
catch { }
}
@ -5214,7 +5381,11 @@ public partial class CombatManager : IDisposable
name = name.Trim();
int id = TrySpellByName(name);
if (id != 0) return id;
int maxTier = Math.Max(EffectiveMaxTier(AcSkillType.CreatureEnchantment), EffectiveMaxTier(AcSkillType.LifeMagic));
// Void too (2026-10-08): "Corruption" with Corruption V and VII known cast V, because only
// Creature and Life set the cap and the search started below VII. Debuffs come from these
// three schools; a level the character doesn't know is never picked.
int maxTier = Math.Max(Math.Max(EffectiveMaxTier(AcSkillType.CreatureEnchantment), EffectiveMaxTier(AcSkillType.LifeMagic)),
EffectiveMaxTier(AcSkillType.VoidMagic));
if (maxTier >= 8) { id = TrySpellByName($"Incantation of {name}"); if (id != 0) { tier = 8; return id; } }
for (int t = Math.Min(maxTier, 7); t >= 1; t--)
{
@ -5345,7 +5516,8 @@ public partial class CombatManager : IDisposable
/// <summary>
/// The base shape a rule asks for when no ring is due: Arc, then Streak, then Blast, then
/// Bolt (the first one on wins; Blast beats Bolt so turning Blast on next to the default Bolt
/// does something). A ring-only rule casts Bolt between rings. -1 = no shape on at all.
/// does something). A ring-only rule casts Bolt between rings, and a wall-only rule (or ring and
/// wall only) Bolt between walls. -1 = no shape on at all.
/// </summary>
internal static int PickBaseShape(MonsterRule? rule)
{
@ -5354,7 +5526,7 @@ public partial class CombatManager : IDisposable
if (rule.UseStreak) return ShapeStreak;
if (rule.UseBlast) return ShapeBlast;
if (rule.UseBolt) return ShapeBolt;
return rule.UseRing ? ShapeBolt : -1;
return rule.UseRing || rule.UseWall ? ShapeBolt : -1;
}
/// <summary>
@ -5385,9 +5557,83 @@ public partial class CombatManager : IDisposable
return count;
}
// ── Wall spells (2026-10-08) ─────────────────────────────────────────────────
// A wall is 10 projectiles in a block 5 wide and 2 high (ACE spell table: dims 5x1x2, padding
// 0.8, created 2 m ahead of the caster) that fly straight along the caster's facing: it is an
// UNTARGETED spell (the client sends CastUntargetedSpell for it even with a target selected,
// and ACE launches it along the caster's forward vector), so the server never turns the caster
// to the target as it does for bolts and blasts. Its swath is therefore a corridor a few metres
// wide, not a fan: monsters are counted when they are ahead of the caster, within the range,
// and within WallHalfWidth of the line to the target (the target included). We turn to face
// the target before the cast (HoldForWallFacing), so that line is where the wall goes.
internal const double WallHalfWidth = 4.0;
/// <summary>Tests: the wall-path count instead of the scan (the scan needs a live world).</summary>
internal Func<int>? WallPathCountOverride { get; set; }
/// <summary>Monsters (the target included) in a wall's path toward <paramref name="targetId"/>:
/// ahead of the caster, within <paramref name="rangeYards"/>, and within <see cref="WallHalfWidth"/>
/// of the line to the target. From the combat scan: LOS-clear and attackable. 0 when the target
/// isn't in the scan (its bearing is unknown).</summary>
private int CountMonstersInWallPath(double rangeYards, int targetId)
{
if (WallPathCountOverride != null) return WallPathCountOverride();
double toTarget = double.NaN;
foreach (var c in _scannedTargets)
if (c.Id == targetId) { toTarget = c.Bearing; break; }
if (double.IsNaN(toTarget)) return 0;
int count = 0;
foreach (var c in _scannedTargets)
{
if (c.Distance > rangeYards || double.IsNaN(c.Bearing) || _recentlyKilled.ContainsKey(c.Id)) continue;
if (InWallPath(c.Distance, c.Bearing - toTarget)) count++;
}
return count;
}
/// <summary>Is a monster <paramref name="distance"/> away, <paramref name="offDeg"/> degrees off the
/// line to the target, in the wall's path: ahead of the caster and within <see cref="WallHalfWidth"/>
/// of that line.</summary>
internal static bool InWallPath(double distance, double offDeg)
{
double rad = offDeg * (Math.PI / 180.0);
double ahead = distance * Math.Cos(rad);
double aside = Math.Abs(distance * Math.Sin(rad));
return ahead >= 0 && aside <= WallHalfWidth;
}
/// <summary>
/// The wall of <paramref name="element"/> to cast: among the known spells of its wall category
/// (<see cref="WallCategories"/>), the highest level the War tier allows (the level by ACE's
/// server formula from the spell's power, <see cref="SpellDatabase.LevelFromPower"/>: the same
/// tier limit the tiered shapes use), then the highest power, then the lowest id (the retail
/// wall). 0 = none: Nether, an element without walls, War untrained, or no wall known.
/// </summary>
internal int FindBestWallSpell(string element)
{
if (_spellManager == null || !_spellManager.IsKnownSnapshotWarm) return 0; // cold: don't guess
if (!WallCategories.TryGetValue(element, out int category)) return 0;
if (_charSkills != null && _charSkills[AcSkillType.WarMagic].Training < 2) return 0;
int maxTier = EffectiveMaxTier(AcSkillType.WarMagic);
int best = 0, bestLevel = 0, bestPower = -1;
foreach (int id in SpellDatabase.IdsInCategory(category))
{
if (!_spellManager.IsKnownSpellId(id)) continue;
SpellDatabase.TryGetCategoryAndPower(id, out _, out int power);
int level = SpellDatabase.LevelFromPower(power);
if (level < 1 || level > maxTier) continue;
if (level > bestLevel || (level == bestLevel && power > bestPower))
{
best = id; bestLevel = level; bestPower = power;
}
}
return best;
}
internal static string ShapeName(int shape) => shape switch
{
ShapeArc => "Arc", ShapeRing => "Ring", ShapeStreak => "Streak", ShapeBolt => "Bolt", ShapeBlast => "Blast", _ => "?",
ShapeArc => "Arc", ShapeRing => "Ring", ShapeStreak => "Streak", ShapeBolt => "Bolt", ShapeBlast => "Blast",
ShapeWall => "Wall", _ => "?",
};
/// <summary>
@ -5441,16 +5687,24 @@ public partial class CombatManager : IDisposable
/// 2. Blast override (Blast Range on): Blast when its fan count is met, else the rule's
/// other shape (<paramref name="blastConditional"/>, <paramref name="blastFanMet"/>);
/// 3. Ring override (Ring Range on): Ring when its count is met (<paramref name="ringDue"/>);
/// 3b. Wall override (Wall Range on, 2026-10-08): Wall when its path count is met and a wall
/// is known (<paramref name="wallDue"/>), unless a ring is due. So with several due: Ring,
/// then Wall, then Blast, then the base shape. A ring hits all around and needs no turn;
/// a wall reaches further along a line but costs a turn, and outdoes a blast's 3 bolts;
/// 4. Arc when clear: an Arc whose flight path to the target is blocked (a wall, or a
/// ceiling the arc rises into) gives way to the rule's other shape: Streak, then Blast
/// (when Blast isn't conditional), then Bolt. An Arc-only rule casts Bolt, as a ring-only
/// rule does between rings.
/// <paramref name="arcBlocked"/> is asked only in step 4, so a ring or a non-arc rule costs
/// no ray test; null (no test, or it can't tell: raycasting off or not ready) casts the Arc
/// as before. <paramref name="arcGaveWay"/> says step 4 replaced the Arc.
/// <paramref name="arcBlocked"/> is asked only in step 4, so a ring, a wall or a non-arc rule
/// costs no ray test; null (no test, or it can't tell: raycasting off or not ready) casts the
/// Arc as before. <paramref name="arcGaveWay"/> says step 4 replaced the Arc.
/// </summary>
internal static int ChooseCastShape(MonsterRule? rule, bool blastConditional, bool blastFanMet, bool ringDue,
Func<bool?>? arcBlocked, out bool arcGaveWay)
=> ChooseCastShape(rule, blastConditional, blastFanMet, ringDue, wallDue: false, arcBlocked, out arcGaveWay);
internal static int ChooseCastShape(MonsterRule? rule, bool blastConditional, bool blastFanMet, bool ringDue,
bool wallDue, Func<bool?>? arcBlocked, out bool arcGaveWay)
{
arcGaveWay = false;
int shape = PickBaseShape(rule);
@ -5459,6 +5713,8 @@ public partial class CombatManager : IDisposable
shape = blastFanMet ? ShapeBlast : PickBaseShapeWithoutBlast(rule);
if (ringDue)
return ShapeRing;
if (wallDue)
return ShapeWall;
if (shape == ShapeArc && arcBlocked != null && arcBlocked() == true)
{
arcGaveWay = true;
@ -5549,7 +5805,7 @@ public partial class CombatManager : IDisposable
_host.Log($"[CombatCast] rule '{rule.Name}': Arc when its flight path is clear, else {other}" +
(_settings.EnableRaycasting ? "" : " (raycasting off: arcs are always cast)"));
}
if (castShape == ShapeRing) return; // the ring override won: no arc question this cast
if (castShape == ShapeRing || castShape == ShapeWall) return; // an override won: no arc question this cast
string state = _lastShapeArcGaveWay
? $"arc blocked ({(ArcBlockedOverride != null ? "test" : DescribeArcBlock(in _arcVerdictDetail))}): {(castShape >= 0 ? ShapeName(castShape) : "nothing")} instead"
: "arc clear";
@ -5596,10 +5852,31 @@ public partial class CombatManager : IDisposable
bool ringDue = rule != null && rule.UseRing && _settings.RingRange > 0
&& CountMonstersInRange(_settings.RingRange) >= Math.Max(1, _settings.MinRingTargets);
int shapeIdx = ChooseCastShape(rule, blastConditional, blastFanMet, ringDue,
// Wall override (Wall Range on): a wall when enough monsters are in its path toward the
// target and the character knows a wall of this element (none for Nether). Asked only for a
// real cast (an element probe has no target, so no path), and only when no ring is due.
// Without the host's heading snap the character can't be turned, so a wall is cast only
// when it already faces the target.
int wallId = 0;
bool wallDue = false;
if (!ringDue && arcTargetId != 0 && rule != null && rule.UseWall && _settings.WallRange > 0
&& CountMonstersInWallPath(_settings.WallRange, arcTargetId) >= Math.Max(1, _settings.MinWallTargets)
&& (_host.HasTurnToHeading || GetFacingError(arcTargetId) <= WallFaceToleranceDeg))
{
wallId = FindBestWallSpell(element);
wallDue = wallId != 0;
}
int shapeIdx = ChooseCastShape(rule, blastConditional, blastFanMet, ringDue, wallDue,
arcTargetId != 0 ? () => IsArcBlockedTo(arcTargetId) : null, out bool arcGaveWay);
if (arcTargetId != 0) _lastShapeArcGaveWay = arcGaveWay;
if (shapeIdx == ShapeWall)
{
castShape = ShapeWall;
return wallId;
}
if (!TryGetShapeBase(element, shapeIdx, useVoid, out string baseName, out string? t7, out bool forcedWar)) return 0;
if (forcedWar) skill = AcSkillType.WarMagic;

View file

@ -8,6 +8,11 @@ namespace RynthCore.Plugin.RynthAi;
public static class SpellDatabase
{
private static readonly Dictionary<int, string> _spellNames = new();
// The data's category (ACE SpellCategory, column 3) and power (difficulty, column 7) per id,
// and the ids of each category. Read for wall spells (2026-10-08): they have no tier in their
// names ("Slithering Flames"), so a wall is found by its category and ranked by its power.
private static readonly Dictionary<int, (int Category, int Power)> _spellMeta = new();
private static readonly Dictionary<int, List<int>> _idsByCategory = new();
private static bool _loaded = false;
private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string>
@ -38,6 +43,8 @@ public static class SpellDatabase
public static void Load(Action<string>? log = null)
{
_spellNames.Clear();
_spellMeta.Clear();
_idsByCategory.Clear();
_loaded = false;
try
@ -59,7 +66,17 @@ public static class SpellDatabase
if (string.IsNullOrWhiteSpace(line)) continue;
string[] columns = line.Split('\t');
if (columns.Length >= 2 && int.TryParse(columns[0].Trim(), out int spellId))
{
_spellNames[spellId] = columns[1].Trim();
if (columns.Length >= 7 && int.TryParse(columns[2].Trim(), out int category)
&& int.TryParse(columns[6].Trim(), out int power))
{
_spellMeta[spellId] = (category, power);
if (!_idsByCategory.TryGetValue(category, out List<int>? ids))
_idsByCategory[category] = ids = new List<int>();
ids.Add(spellId);
}
}
}
_loaded = _spellNames.Count > 0;
@ -93,6 +110,30 @@ public static class SpellDatabase
return _spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
}
/// <summary>The spell's category (ACE SpellCategory) and power from the data; false when the
/// spell isn't in it.</summary>
public static bool TryGetCategoryAndPower(int spellId, out int category, out int power)
{
if (_spellMeta.TryGetValue(spellId, out var m)) { category = m.Category; power = m.Power; return true; }
category = 0; power = 0;
return false;
}
/// <summary>Every spell id of a category (ACE SpellCategory), in data order.</summary>
public static IReadOnlyList<int> IdsInCategory(int category)
=> _idsByCategory.TryGetValue(category, out List<int>? ids) ? ids : Array.Empty<int>();
/// <summary>
/// A spell's level by ACE's server formula (Spell.Level): the highest level whose minimum power
/// it reaches, 1/50/100/150/200/250/300/400 for levels 1-8 (SpellFormula.MinPower). The tiered
/// war lines have exactly those powers (Flame Bolt V 200, the tier-7 lore 300, Incantations
/// 400; blasts +25), so it is the same tier limit the other shapes use. 0 = no power.
/// </summary>
public static int LevelFromPower(int power) => power switch
{
>= 400 => 8, >= 300 => 7, >= 250 => 6, >= 200 => 5, >= 150 => 4, >= 100 => 3, >= 50 => 2, >= 1 => 1, _ => 0,
};
/// <summary>Builds a name→id reverse map for SpellManager initialisation.</summary>
public static Dictionary<string, int> BuildNameToIdMap()
{

View file

@ -194,7 +194,9 @@ public class SpellManager
return 0;
}
public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill)
/// <param name="skip">Levels to pass over (a level the server refused for missing components):
/// the next lower known level is returned instead.</param>
public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill, Func<int, bool>? skip = null)
{
RefreshKnownSpells(); // keep the authoritative inventory current (throttled)
@ -207,8 +209,8 @@ public class SpellManager
for (int tier = maxTier; tier >= 1; tier--)
{
if (TryGetTierId(cleanBase, tier, out int id)) return id;
if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias;
if (TryGetTierId(cleanBase, tier, out int id) && (skip == null || !skip(id))) return id;
if (alias != null && TryGetTierId(alias, tier, out int idAlias) && (skip == null || !skip(idAlias))) return idAlias;
}
return 0;
}

View file

@ -1840,6 +1840,24 @@ public class WorldObjectCache
get { lock (_gate) return _hazardVersion; }
}
/// <summary>
/// A dungeon cell the character took hotspot damage in ("You suffer 32 damage from acid!"):
/// registered and persisted like a sighted hazard, so the patrol reroutes around it now and
/// on every later visit. Outdoor cells (a 24 m land cell) are never registered. True when new.
/// </summary>
public bool RegisterDamageHazardCell(uint cellId, string source)
{
if (cellId == 0 || (cellId & 0xFFFF) < 0x0100) return false;
lock (_gate)
{
if (!_hazardCells.Add(cellId)) return false;
_hazardVersion++;
}
DungeonHazardStore.Append(cellId >> 16, cellId);
_host.Log($"[Hazard] took {source} damage in cell 0x{cellId:X8} (persisted)");
return true;
}
public bool IsHazardCell(uint cellId)
{
lock (_gate)

View file

@ -98,6 +98,8 @@ public sealed partial class RynthAiPlugin
private bool _corpseAutorunActive;
private int _currentLootItemMoveAttempts;
private long _currentLootItemStillSince;
private long _currentLootItemLeftAt;
private bool _currentLootItemSawAnim;
private long _pickupAnimSince;
private string _currentLootItemActionLabel = string.Empty;
private string _currentLootItemName = string.Empty;
@ -1285,7 +1287,9 @@ public sealed partial class RynthAiPlugin
pendingDataCount++;
continue;
}
// Still nameless well past the window — skip this item.
// Still nameless well past the window — skip this item (and say so: it used to
// leave nothing in the log, so a missed item couldn't be traced).
LootDiag($"[LootEval] 0x{(uint)item.Id:X8} on 0x{(uint)corpseId:X8} still has no name after the wait (value={item.Values(19, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)}) -> left");
_processedCorpseItems.Add(item.Id);
continue;
}
@ -1325,7 +1329,7 @@ public sealed partial class RynthAiPlugin
// once the assess window expires, so an unappraised item can match a
// rule it should not. If keeps correlate with appraised=False, that
// is the cause.
LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " +
LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} id=0x{(uint)item.Id:X8} value={item.Values(19, 0)} stack={item.Values(12, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " +
(classified ? $"KEEP [{actionLabel}] rule='{ruleLabel}'" : "leave"));
if (classified)
@ -1463,6 +1467,20 @@ public sealed partial class RynthAiPlugin
/// <summary>Longest a pickup waits on the motion queue (the engine's own hold is 2.5 s).</summary>
internal const long PickupAnimMaxMs = 3000;
/// <summary>After the item leaves the corpse: how long to wait for its bend-down to start.</summary>
internal const long PickupSettleMs = 1000;
/// <summary>Off the corpse but not seen in the inventory: counted after this anyway.</summary>
internal const long PickupArriveMaxMs = 4000;
/// <summary>The container is the character or a pack it carries.</summary>
private bool InPlayerInventory(int containerId)
{
if (containerId == 0 || _playerId == 0 || _objectCache == null) return false;
int player = unchecked((int)_playerId);
return containerId == player || _objectCache.GetContainerId(containerId) == player;
}
/// <summary>
/// The character still has motions queued (the engine's cast gate, GetCastBusyState):
/// the bend-down of the last pickup is playing. False after PickupAnimMaxMs of it, so a
@ -1495,10 +1513,24 @@ public sealed partial class RynthAiPlugin
int currentContainer = currentItem?.Container ?? 0;
bool stillVisibleOnCorpse = IsCorpseItemVisible(_openedContainerId, _currentLootItemId);
// Check every tick — confirm immediately as soon as the item leaves the corpse.
// Don't gate this on a timer; the timer only applies to the RETRY path below.
// Watch for this pickup's bend-down (the server plays it once the move reaches it).
bool animating = PickupAnimating(now);
if (animating) _currentLootItemSawAnim = true;
// Off the corpse is not done yet: confirming then closed the corpse while the pickup was
// still under way, and the character picked the last item up after the corpse closed
// (2026-10-07). It counts once the item shows up in the inventory (the main pack, a side
// pack, or merged into a stack already there: the picked object is gone) and its
// bend-down has played out. Off the corpse but never seen in the inventory: counted
// after PickupArriveMaxMs anyway, so looting can't stall on it.
if (currentItem == null || !stillVisibleOnCorpse || (currentContainer != 0 && currentContainer != _openedContainerId))
{
if (_currentLootItemLeftAt == 0) _currentLootItemLeftAt = now;
bool inInventory = currentItem == null || InPlayerInventory(currentContainer);
long since = now - _currentLootItemLeftAt;
bool settled = !animating && (_currentLootItemSawAnim || since >= PickupSettleMs);
if (!(inInventory && settled) && since < PickupArriveMaxMs)
return;
ConfirmCurrentLootItemMoved(
now,
currentItem == null
@ -2339,6 +2371,8 @@ public sealed partial class RynthAiPlugin
_currentLootItemMoveRequestedAt = 0;
_currentLootItemMoveAttempts = 0;
_currentLootItemStillSince = 0;
_currentLootItemLeftAt = 0;
_currentLootItemSawAnim = false;
_currentLootItemActionLabel = string.Empty;
_currentLootItemName = string.Empty;
_currentLootItemIsSalvage = false;

View file

@ -184,6 +184,14 @@ internal sealed class LegacyAdvancedSettingsUi
catch { return false; }
}
/// <summary>One cell of the Protections and Banes grid: ticked = cast it.</summary>
private void BuffToggle((string Buff, string Label) toggle)
{
bool on = !_settings.IsBuffDisabled(toggle.Buff);
if (ImGui.Checkbox($"{toggle.Label}##buff_{toggle.Buff}", ref on))
_settings.SetBuffEnabled(toggle.Buff, on);
}
private void RenderTabContent(int tabIndex)
{
if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length)
@ -265,6 +273,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Patrol On Login", ref _settings.PatrolOnLogin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically starts dungeon patrol when RynthAi loads.");
ImGui.Checkbox("Escape Acid and Lava", ref _settings.EscapeHazards);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose.");
ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting);
ImGui.Separator();
@ -496,12 +507,12 @@ internal sealed class LegacyAdvancedSettingsUi
"Below 200ms may cause fizzles or dropped casts on laggy servers.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 250, 5000);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Delay between offensive (war/void) COMBAT casts only.\n" +
"Spacing casts ~1-2s (1500ms default) stops back-to-back\n" +
"\"You're too busy!\" refusals that drop casts and cost kills.\n" +
"Least time between offensive (war/void) COMBAT casts at one target.\n" +
"The next cast also waits until the last one is finished (the server's\n" +
"answer and the casting animation), so 0 = cast again as soon as it is.\n" +
"Does NOT affect buffing speed.");
ImGui.Spacing();
@ -515,6 +526,12 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.InputInt("Min Blast Targets", ref _settings.MinBlastTargets);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak.");
ImGui.InputInt("Wall Range (0 = off)", ref _settings.WallRange);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Monster rules with Wall on cast their element's wall spell when enough monsters\n" +
"are within this many yards in the wall's path toward the target.\n" +
"The character turns to face the target first. 0 = no walls.");
ImGui.InputInt("Min Wall Targets", ref _settings.MinWallTargets);
ImGui.Spacing();
ImGui.Separator();
@ -727,6 +744,31 @@ internal sealed class LegacyAdvancedSettingsUi
"For servers with buff augments, where your own cast is stronger or\n" +
"lasts longer. On by default: on retail it costs a few extra casts.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Protections and Banes");
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Untick a protection or bane to stop the bot casting it.\n" +
"Unticked buffs are skipped and never hold the bot in Buffing.\n" +
"All on by default.");
if (ImGui.BeginTable("##protsBanes", 2, ImGuiTableFlags.SizingStretchSame))
{
ImGui.TableSetupColumn("Protections");
ImGui.TableSetupColumn("Banes");
ImGui.TableHeadersRow();
int rows = Math.Max(BuffManager.ToggleProtections.Length, BuffManager.ToggleBanes.Length);
for (int i = 0; i < rows; i++)
{
ImGui.TableNextRow();
ImGui.TableSetColumnIndex(0);
if (i < BuffManager.ToggleProtections.Length) BuffToggle(BuffManager.ToggleProtections[i]);
ImGui.TableSetColumnIndex(1);
if (i < BuffManager.ToggleBanes.Length) BuffToggle(BuffManager.ToggleBanes[i]);
}
ImGui.EndTable();
}
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Buff Difficulty (Min Buffed Skill)");

View file

@ -989,6 +989,8 @@ internal sealed class LegacyDashboardRenderer
MinRingTargets = s.MinRingTargets,
BlastRange = s.BlastRange,
MinBlastTargets = s.MinBlastTargets,
WallRange = s.WallRange,
MinWallTargets = s.MinWallTargets,
MinSkillLevelTier1 = s.MinSkillLevelTier1,
MinSkillLevelTier2 = s.MinSkillLevelTier2,
MinSkillLevelTier3 = s.MinSkillLevelTier3,
@ -1039,6 +1041,7 @@ internal sealed class LegacyDashboardRenderer
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
DisabledBuffs = new List<string>(s.DisabledBuffs),
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
@ -1060,6 +1063,7 @@ internal sealed class LegacyDashboardRenderer
LootJumpHeight = s.LootJumpHeight,
LootOwnership = s.LootOwnership,
LootOwnCorpse = s.LootOwnCorpse,
EscapeHazards = s.EscapeHazards,
TravelToOwnCorpse = s.TravelToOwnCorpse,
ItemInfoOnSelect = s.ItemInfoOnSelect,
EnableAutostack = s.EnableAutostack,
@ -1192,11 +1196,13 @@ internal sealed class LegacyDashboardRenderer
s.PetMinMonsters = p.PetMinMonsters;
// Spell Combat
s.SpellCastIntervalMs = p.SpellCastIntervalMs;
s.AttackSpellIntervalMs = p.AttackSpellIntervalMs;
if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged
s.CastDispelSelf = p.CastDispelSelf;
s.MinRingTargets = p.MinRingTargets;
s.BlastRange = p.BlastRange;
s.MinBlastTargets = p.MinBlastTargets;
if (p.WallRange is int wallRange) s.WallRange = wallRange; // null = an engine without walls
if (p.MinWallTargets is int minWall) s.MinWallTargets = minWall;
s.MinSkillLevelTier1 = p.MinSkillLevelTier1;
s.MinSkillLevelTier2 = p.MinSkillLevelTier2;
s.MinSkillLevelTier3 = p.MinSkillLevelTier3;
@ -1247,6 +1253,7 @@ internal sealed class LegacyDashboardRenderer
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List<string>(disabledBuffs); // absent = unchanged
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
@ -1264,6 +1271,7 @@ internal sealed class LegacyDashboardRenderer
s.LootJumpEnabled = p.LootJumpEnabled;
s.LootJumpHeight = p.LootJumpHeight;
s.LootOwnership = p.LootOwnership;
if (p.EscapeHazards is bool escape) s.EscapeHazards = escape; // absent = unchanged
if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged
if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged
if (p.ItemInfoOnSelect is bool infoOnSelect) s.ItemInfoOnSelect = infoOnSelect; // absent = unchanged
@ -1647,6 +1655,8 @@ internal sealed class LegacyDashboardRenderer
dst.MinRingTargets = tmp.MinRingTargets;
dst.BlastRange = tmp.BlastRange;
dst.MinBlastTargets = tmp.MinBlastTargets;
dst.WallRange = tmp.WallRange;
dst.MinWallTargets = tmp.MinWallTargets;
dst.FollowNavMin = tmp.FollowNavMin;
dst.NavRingThickness = tmp.NavRingThickness;
dst.NavLineThickness = tmp.NavLineThickness;
@ -1668,6 +1678,7 @@ internal sealed class LegacyDashboardRenderer
dst.AutoUnlockDoors = tmp.AutoUnlockDoors;
dst.LootOwnership = tmp.LootOwnership;
dst.LootOwnCorpse = tmp.LootOwnCorpse;
dst.EscapeHazards = tmp.EscapeHazards;
dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse;
dst.ItemInfoOnSelect = tmp.ItemInfoOnSelect;
dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses;
@ -1676,6 +1687,7 @@ internal sealed class LegacyDashboardRenderer
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
dst.DisabledBuffs = tmp.DisabledBuffs;
dst.BlacklistAttempts = tmp.BlacklistAttempts;
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
@ -2101,28 +2113,41 @@ internal sealed class LegacyDashboardRenderer
_selectedNavIdx = sel;
}
private DateTime _navFolderStamp;
private DateTime _navFolderStamp, _lootFolderStamp, _metaFolderStamp, _profileFolderStamp;
private long _nextNavFolderCheckMs;
/// <summary>
/// Lists NavProfiles again when the folder changed since the last look (a route saved there by
/// RynthNav's "save as nav route", or a file copied in), so the Nav picker shows it without a
/// relog. One folder time check every 3 s. Plugin tick.
/// Lists a folder again when it changed since the last look (a file added, removed or renamed:
/// a route saved by RynthNav's "save as nav route", a loot profile or meta copied in, a settings
/// profile saved), so its picker shows it without a relog or a reload. NavProfiles since
/// 2026-10; LootProfiles, MetaFiles and the character's settings profiles since 2026-10-08
/// (a loot profile copied in didn't show until a hot reload). One folder time check each every
/// 3 s. Plugin tick.
/// </summary>
public void TickNavFolder()
{
long now = Environment.TickCount64;
if (now < _nextNavFolderCheckMs) return;
_nextNavFolderCheckMs = now + 3000;
if (FolderChanged(_navFolder, ref _navFolderStamp)) RefreshNavFiles();
if (FolderChanged(_lootFolder, ref _lootFolderStamp)) RefreshLootFiles();
if (FolderChanged(_metaFolder, ref _metaFolderStamp)) RefreshMetaFiles();
if (FolderChanged(_charFolder, ref _profileFolderStamp)) RefreshProfilesList();
}
/// <summary>True when <paramref name="folder"/>'s write time moved since the last call (never on
/// the first look, which only records it: the lists were built at load).</summary>
private static bool FolderChanged(string? folder, ref DateTime stamp)
{
try
{
DateTime stamp = Directory.Exists(_navFolder) ? Directory.GetLastWriteTimeUtc(_navFolder) : DateTime.MinValue;
if (stamp == _navFolderStamp) return;
bool first = _navFolderStamp == default;
_navFolderStamp = stamp;
if (!first) RefreshNavFiles();
DateTime now = !string.IsNullOrEmpty(folder) && Directory.Exists(folder) ? Directory.GetLastWriteTimeUtc(folder) : DateTime.MinValue;
if (now == stamp) return false;
bool first = stamp == default;
stamp = now;
return !first;
}
catch { }
catch { return false; }
}
/// <summary>Save button and /ra nav save [name]. Returns the chat line.</summary>

View file

@ -143,7 +143,7 @@ internal sealed class LegacyNavigationUi
for (int ri = 0; ri < ids.Length; ri++)
{
string name = $"Spell {ids[ri]}";
string name = NavPoint.RecallName(ids[ri]);
if (ImGui.Selectable($"{name} ({ids[ri]})"))
{
if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _))

View file

@ -159,6 +159,12 @@ public sealed class LegacyUiSettings
// degrees) toward the target; otherwise its other shape. 0 = off: Blast is just a shape.
public int BlastRange = 0;
public int MinBlastTargets = 3;
// Wall spells (2026-10-08): with WallRange > 0, a rule with Wall on casts its element's wall
// (Slithering Flames, Os' Wall...) when MinWallTargets monsters are within WallRange in the
// wall's path toward the target, turning to face the target first (a wall flies along the
// caster's facing). Below a due ring, above a due blast. 0 = off: no walls at all.
public int WallRange = 0;
public int MinWallTargets = 3;
// Nav point reach (VTank "Follow/Nav Min Distance"), yards: how close nav gets to each
// nav point before moving on to the next, and how close Follow gets to its leader.
// Metas set it as FollowNavMin (yards) or VTank's NavCloseStopRange (landblock units,
@ -202,6 +208,13 @@ public sealed class LegacyUiSettings
/// </summary>
public bool LootOwnCorpse = true;
/// <summary>
/// Out of acid or lava at once (RynthAiPlugin.HazardEscape.cs): the first hotspot hit stops
/// everything and walks back out, and the spot becomes a hazard the patrol avoids. On by
/// default (2026-10-07); off for characters that walk through acid on purpose (then the spot
/// isn't learned either). A profile saved before this setting loads it as on.
/// </summary>
public bool EscapeHazards = true;
/// <summary>
/// After a death and respawn, travel back to where you died (RynthNav, outdoors only), fight
/// on the way as usual, recover the corpse, then carry on. Off by default.
/// </summary>
@ -237,6 +250,35 @@ public sealed class LegacyUiSettings
/// as on for good (the behaviour before 2026-10-05).
/// </summary>
public bool CastBuffsOverItemBuffs = true;
/// <summary>
/// Buff base names the player unticked in Buffing settings (the Protections and Banes grid,
/// e.g. "Fire Protection Self", "Flame Bane"): left out of the buff list, so never cast and
/// never waited on. Empty = every buff on, which is also what a profile saved before this
/// setting existed loads as. Replaced, not edited in place (SetBuffEnabled), so a reader
/// holding the old list never sees it change under it.
/// </summary>
public List<string> DisabledBuffs
{
get => _disabledBuffs;
set => _disabledBuffs = value ?? new List<string>();
}
private List<string> _disabledBuffs = new();
public bool IsBuffDisabled(string buffBaseName)
{
foreach (string b in _disabledBuffs)
if (string.Equals(b, buffBaseName, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
public void SetBuffEnabled(string buffBaseName, bool enabled)
{
if (enabled == !IsBuffDisabled(buffBaseName)) return;
var next = new List<string>(_disabledBuffs);
if (enabled) next.RemoveAll(b => string.Equals(b, buffBaseName, StringComparison.OrdinalIgnoreCase));
else next.Add(buffBaseName);
_disabledBuffs = next;
}
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
/// <summary>
@ -631,6 +673,10 @@ public sealed class MonsterRule
/// <summary>Blast spells (Flame Blast, Frost Blast...: a spread of projectiles). Off in files
/// from before 2026-10-03. Wins over Bolt when both are on; see CombatManager.PickBaseShape.</summary>
public bool UseBlast { get; set; }
/// <summary>Wall spells (Slithering Flames, Os' Wall...: a row of projectiles flying straight
/// ahead). An override like the ring, cast only with Wall Range on and enough monsters in the
/// wall's path; a wall-only rule casts Bolt between walls. Off in files from before 2026-10-08.</summary>
public bool UseWall { get; set; }
public string ExVuln { get; set; } = "None";
/// <summary>The off hand for this rule: 0 = the global setting (OffhandDefault), 1 Auto,
/// 2 Shield, 3 Offhand weapon, 4 None (OffhandRules.Rule*); any other value is a listed
@ -822,11 +868,16 @@ public sealed class SettingsBridgePayload
// Spell Combat
public int SpellCastIntervalMs { get; set; }
public int AttackSpellIntervalMs { get; set; }
// Nullable since 0 became a real value (2026-10-08): a file without it keeps the default.
public int? AttackSpellIntervalMs { get; set; }
public bool CastDispelSelf { get; set; }
public int MinRingTargets { get; set; }
public int BlastRange { get; set; }
public int MinBlastTargets { get; set; } = 3; // absent from an older engine: keep the default
// Walls (2026-10-08): null = sent by an engine without the Wall Range control, which then
// leaves the plugin's own values alone (a profile's or a meta's) instead of zeroing them.
public int? WallRange { get; set; }
public int? MinWallTargets { get; set; }
public int MinSkillLevelTier1 { get; set; }
public int MinSkillLevelTier2 { get; set; }
public int MinSkillLevelTier3 { get; set; }
@ -883,6 +934,8 @@ public sealed class SettingsBridgePayload
// Nullable: an engine that predates the setting doesn't send it, and a save from its
// Settings face must leave the setting alone rather than force it either way.
public bool? CastBuffsOverItemBuffs { get; set; }
// Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all.
public List<string>? DisabledBuffs { get; set; }
public int BuffMinSkillLevelTier1 { get; set; }
public int BuffMinSkillLevelTier2 { get; set; }
public int BuffMinSkillLevelTier3 { get; set; }
@ -908,6 +961,7 @@ public sealed class SettingsBridgePayload
// Nullable, as CastBuffsOverItemBuffs: an engine that predates them doesn't send them,
// and its save must leave them alone.
public bool? LootOwnCorpse { get; set; }
public bool? EscapeHazards { get; set; }
public bool? TravelToOwnCorpse { get; set; }
public bool? ItemInfoOnSelect { get; set; }
public bool EnableAutostack { get; set; }

View file

@ -74,12 +74,24 @@ public sealed class NavPoint
/// </summary>
public bool Doorway { get; set; }
/// <summary>"Lifestone Recall": a recall step by its spell's name (it showed "Spell 1635",
/// 2026-10-08); the id when the spell table doesn't know it.</summary>
internal static string RecallName(int spellId)
{
string? name = SpellNameLookup?.Invoke(spellId);
return string.IsNullOrEmpty(name) ? $"Spell {spellId}" : name;
}
/// <summary>The spell table's name for an id; RynthAi sets it (this file is also compiled into
/// tools without the spell table, which keep "Spell N").</summary>
internal static Func<int, string?>? SpellNameLookup { get; set; }
public override string ToString()
{
return Type switch
{
NavPointType.Point => $"[Point] {NS:F3}, {EW:F3}",
NavPointType.Recall => $"[Recall] Spell {SpellId}",
NavPointType.Recall => $"[Recall] {RecallName(SpellId)}",
NavPointType.Pause => $"[Pause] {PauseTimeMs / 1000.0:F1}s",
NavPointType.Chat => $"[Chat] {ChatCommand}",
NavPointType.OpenVendor => $"[Vendor] {TargetName}",

View file

@ -182,8 +182,10 @@ internal sealed class LootEditorBridge
if (id == 0) return Refuse(d, "No item selected. Click an item first.");
d.ItemId = id;
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like);
d.IncludeT11 = req.IncludeT11;
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like, req.IncludeT11);
if (facts == null) return Refuse(d, $"RynthAi doesn't know item 0x{id:X8} yet. Select it again in a moment.");
d.IsT11 = facts.T11?.IsT11 == true;
d.ItemName = facts.Name;
d.ClassName = LootItemRules.ClassName(facts.ObjectClass);
d.Stackable = facts.Stackable;
@ -207,6 +209,7 @@ internal sealed class LootEditorBridge
Action = req.Action == 0 ? null : (VTankLootAction)req.Action,
KeepCount = req.KeepCount < 0 ? null : req.KeepCount,
RuleName = req.RuleName,
IncludeT11 = req.IncludeT11,
};
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
if (draft == null) return Refuse(d, error);
@ -336,8 +339,11 @@ internal sealed class LootItemHooks
{
/// <summary>The item selected in the game, or 0.</summary>
public Func<uint> SelectedItemId { get; set; } = () => 0;
/// <summary>The item's facts from the object cache, or null. The bool: "items like this" (ask for an ID if it isn't identified).</summary>
public Func<uint, bool, LootItemFacts?> Facts { get; set; } = (_, _) => null;
/// <summary>
/// The item's facts from the object cache, or null. The bools: "items like this" and
/// "include T11 attributes"; either asks for an ID when the item isn't identified.
/// </summary>
public Func<uint, bool, bool, LootItemFacts?> Facts { get; set; } = (_, _, _) => null;
/// <summary>The first rule of the .utl profile that matches the item now, or -1.</summary>
public Func<uint, VTankLootProfile, int> FirstMatchUtl { get; set; } = (_, _) => -1;
/// <summary>The first rule of the native profile that matches the item now, or -1.</summary>

View file

@ -110,8 +110,11 @@ internal sealed class ManaStoneManager
// off or the macro is stopped must leave the set too.
PruneLootedForTap(NowMs);
// An Eternal Mana Charge refills gear for free, so it works with tapping off too.
if (!_settings.EnableManaTapping && !HasEternalCharge()) { Reset(); return; }
// Refilling worn gear from a charged stone (or a free Eternal charge) works with tapping
// off too; only draining loot into empty stones needs tapping on. It used to need tapping
// on for any refill, so charged stones and bought Mana Charges were never used with it
// off (2026-10-08).
if (!_settings.EnableManaTapping && !HasChargedRefillStone()) { Reset(); return; }
if (!_settings.IsMacroRunning) { Reset(); return; }
long now = NowMs;
@ -487,12 +490,23 @@ internal sealed class ManaStoneManager
if (hasRule) return false; // explicit rules → match by name only
if (!_settings.EnableManaTapping) return false; // no rules → auto-detect only when tapping is on
if (item.ObjectClass == AcObjectClass.ManaStone) return true;
return !string.IsNullOrEmpty(item.Name)
&& (item.Name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase)
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase));
// Only the ordinary tapping stones and mana charges. Retail also has special stones
// (Aligned, Aetheria, Unstable, Enchanted, Adjanite Mana Stone) that are not for
// draining or recharging: an Aligned Mana Stone was used on a wand (2026-10-08). A
// special stone is only touched when a ManaStone consumable rule names it.
if (string.IsNullOrEmpty(item.Name))
return item.ObjectClass == AcObjectClass.ManaStone; // unnamed yet: the class decides (looting)
return OrdinaryStoneNames.Contains(item.Name)
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
}
/// <summary>The retail tapping stones (ACE world data names), smallest to largest.</summary>
internal static readonly HashSet<string> OrdinaryStoneNames = new(StringComparer.OrdinalIgnoreCase)
{
"Minor Mana Stone", "Lesser Mana Stone", "Moderate Mana Stone", "Mana Stone",
"Greater Mana Stone", "Major Mana Stone",
};
/// <summary>
/// An unlimited mana charge (Eternal Mana Charge: 10,000 mana, never used up). Always
/// "charged", never an empty stone to drain into, and preferred for refilling gear.
@ -500,6 +514,35 @@ internal sealed class ManaStoneManager
private static bool IsEternal(WorldObject item) =>
!string.IsNullOrEmpty(item.Name) && item.Name.StartsWith("Eternal Mana", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// A stone that may refill worn gear when charged: what <see cref="IsManaStone"/> takes, but
/// with tapping off as well (no rules: the ordinary stones and mana charges; with ManaStone
/// rules: the named ones).
/// </summary>
internal bool IsRefillStone(WorldObject item)
{
if (IsManaStone(item)) return true;
if (_settings.EnableManaTapping || string.IsNullOrEmpty(item.Name)) return false;
foreach (var rule in _settings.ConsumableRules)
if (rule.Type.Equals("ManaStone", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(rule.Name))
return false; // rules decide (IsManaStone already said no)
return OrdinaryStoneNames.Contains(item.Name)
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
}
// FindChargedStone walks every known object; with tapping off it gates the whole tick, so
// the answer is kept for a few seconds.
private long _chargedCheckAt;
private bool _chargedCached;
private bool HasChargedRefillStone()
{
long now = NowMs;
if (now - _chargedCheckAt < 5000) return _chargedCached;
_chargedCheckAt = now;
_chargedCached = HasEternalCharge() || FindChargedStone() != 0;
return _chargedCached;
}
private bool HasEternalCharge()
{
int playerId = unchecked((int)_host.GetPlayerId());
@ -608,7 +651,7 @@ internal sealed class ManaStoneManager
foreach (var item in _objectCache.AllKnownObjects())
{
if (!IsManaStone(item)) continue;
if (!IsRefillStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
// Skip stones that timed out on use-on-player recently.
@ -617,7 +660,6 @@ internal sealed class ManaStoneManager
// Eternal: always charged (its mana often can't be read), never used up — first choice.
if (IsEternal(item)) return item.Id;
if (!_settings.EnableManaTapping) continue; // tapping off: only the free charge
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur))
continue;

View file

@ -344,7 +344,7 @@ internal static class AfFileWriter
5543 => "Neftet Recall",
6321 => "Rynthid Recall",
6322 => "Viridian Rise Recall",
_ => $"Spell {spellId}"
_ => NavPoint.RecallName(spellId)
};
}
}

View file

@ -349,7 +349,8 @@ internal sealed class ExpressionEngine
"wobjectfindallinventorybynamerx" => EvalWobjectFindAllInventoryByNameRx(Tmpl(0)),
"wobjectfindininventorybyname" => EvalWobjectFindInInventoryByName(Tmpl(0)),
"wobjectfindininventorybynamerx" => EvalWobjectFindInInventoryByNameRx(Tmpl(0)),
"wobjectfindalllandscapebytemplatetype" => EvalWobjectFindAllLandscapeByTemplateType(A(0)),
"wobjectfindalllandscapebyobjectclass" => EvalWobjectFindAllLandscapeByObjectClass(A(0)),
"wobjectfindalllandscapebytemplatetype" =>EvalWobjectFindAllLandscapeByTemplateType(A(0)),
"wobjectfindalllandscapebynamerx" => EvalWobjectFindAllLandscapeByNameRx(Tmpl(0)),
"wobjectfindallbycontainer" => EvalWobjectFindAllByContainer(A(0)),
"wobjectgetselection" => EvalWobjectGetSelection(),
@ -1642,6 +1643,24 @@ internal sealed class ExpressionEngine
return NewList(items);
}
private string EvalWobjectFindAllLandscapeByObjectClass(string arg)
{
if (_worldObjectCache == null) return "[]";
if (!int.TryParse(arg.Trim(), out int targetClass)) return "[]";
var items = new List<string>();
var seen = new System.Collections.Generic.HashSet<int>();
void Check(WorldObject wo)
{
if (!seen.Add(wo.Id)) return;
if (ResolveEffectiveObjectClass(wo) == targetClass)
items.Add(MakeWobjectHandle(unchecked((uint)wo.Id), wo.Name));
}
foreach (var wo in _worldObjectCache.GetLandscapeObjects()) Check(wo);
foreach (var wo in _worldObjectCache.GetLandscape()) Check(wo);
return NewList(items);
}
private string EvalWobjectFindAllLandscapeByTemplateType(string arg)
{
if (_worldObjectCache == null || !_host.HasGetObjectWcid) return "[]";
@ -2420,8 +2439,7 @@ internal sealed class ExpressionEngine
if (!TryParseWobjectHandle(arg, out uint uid, out _) || uid == 0) return "0";
if (!_host.HasSelectItem) return "0";
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(uid);
_host.SelectItem(uid);
return "0";
return _host.SelectItem(uid) ? "1" : "0";
}
private string EvalActionTryUseItem(string arg)
@ -3318,6 +3336,7 @@ internal sealed class ExpressionEngine
["StopMacroOnNoComponents"] = (() => B(s.StopMacroOnNoComponents), v => s.StopMacroOnNoComponents = ToDouble(v) != 0),
["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0),
["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0),
["EscapeHazards"] = (() => B(s.EscapeHazards), v => s.EscapeHazards = ToDouble(v) != 0),
["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0),
["ItemInfoOnSelect"] = (() => B(s.ItemInfoOnSelect), v => s.ItemInfoOnSelect = ToDouble(v) != 0),
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
@ -3338,6 +3357,8 @@ internal sealed class ExpressionEngine
["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }),
["BlastRange"] = (() => I(s.BlastRange), v => { if (int.TryParse(v, out int i)) s.BlastRange = i; }),
["MinBlastTargets"] = (() => I(s.MinBlastTargets), v => { if (int.TryParse(v, out int i)) s.MinBlastTargets = i; }),
["WallRange"] = (() => I(s.WallRange), v => { if (int.TryParse(v, out int i)) s.WallRange = i; }),
["MinWallTargets"] = (() => I(s.MinWallTargets), v => { if (int.TryParse(v, out int i)) s.MinWallTargets = i; }),
["HealAt"] = (() => I(s.HealAt), v => { if (int.TryParse(v, out int i)) s.HealAt = i; }),
["RestamAt"] = (() => I(s.RestamAt), v => { if (int.TryParse(v, out int i)) s.RestamAt = i; }),
["RestamTo"] = (() => I(s.RestamTo), v => { if (int.TryParse(v, out int i)) s.RestamTo = i; }),

View file

@ -1761,7 +1761,7 @@ internal sealed class NavigationEngine
// teleport happened but wasn't seen, or the route stays on this side).
if (NextWalkTargetBeyond(route, _settings.ActiveNavIndex, OffTrackYards, out int farIdx, out double farYd))
{
string what = pt.Type == NavPointType.Recall ? $"the recall (spell {pt.SpellId})" : $"the portal '{pt.TargetName}'";
string what = pt.Type == NavPointType.Recall ? $"the recall ({NavPoint.RecallName(pt.SpellId)})" : $"the portal '{pt.TargetName}'";
string msg = $"Nav: {what} didn't teleport within {ActionTimeoutMs / 1000:F0}s, and the next waypoint [{farIdx}] is {farYd:F0}yd away - navigation stopped.";
_host.Log(msg);
_host.WriteToChat(msg, 1);

View file

@ -1603,8 +1603,12 @@ public sealed partial class RynthAiPlugin
if (inUse) ReloadLootProfileInUse(d.TargetPath);
}
/// <summary>What a loot rule can be built from: the item's name, class, stack and key properties, from the object cache.</summary>
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like)
/// <summary>
/// What a loot rule can be built from: the item's name, class, stack, key properties and
/// T11 reading, from the object cache. <paramref name="like"/> adds its spells;
/// <paramref name="t11"/> asks for an ID when a T11 item's text hasn't arrived.
/// </summary>
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like, bool t11)
{
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
if (wo == null) return null;
@ -1634,6 +1638,10 @@ public sealed partial class RynthAiPlugin
// Material, workmanship and spells need an ID: ask for one, so the next preview has them.
if (Host.HasRequestId && Host.HasHasAppraisalData && !Host.HasAppraisalData(itemId)) Host.RequestId(itemId);
}
// Always read (a cached parse), so the popup knows whether the T11 option applies.
f.T11 = Loot.T11ItemSupport.Get(wo);
// T11 tier, grade and modifiers are appraisal text: ask for it, so the next preview has them.
if (t11 && f.T11.IsT11 && !f.T11.HasText && Host.HasRequestId) Host.RequestId(itemId);
return f;
}
@ -1656,17 +1664,18 @@ public sealed partial class RynthAiPlugin
}
/// <summary>
/// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview]: a rule for
/// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview]: a rule for
/// the selected item, straight into the loot profile in use (the defaults: exact
/// name and class; Read for scrolls, Keep # one full stack for stacks, else Keep).
/// t11 also requires the item's T11 attributes.
/// </summary>
private void HandleLootCommand(string[] parts)
{
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
if (sub != "add")
{
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item to the loot profile in use");
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. preview = show it, add nothing.");
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use");
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing.");
ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor.");
return;
}
@ -1686,6 +1695,7 @@ public sealed partial class RynthAiPlugin
case "name": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Name; break;
case "like": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Like; break;
case "exact": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.NameAndClass; break;
case "t11": req.IncludeT11 = true; break;
case "preview":
case "?": preview = true; break;
default:
@ -1695,7 +1705,7 @@ public sealed partial class RynthAiPlugin
req.KeepCount = n;
break;
}
ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like or preview.");
ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like, t11 or preview.");
return;
}
}
@ -2879,6 +2889,11 @@ public sealed partial class RynthAiPlugin
return;
}
settings.IsMacroRunning = true;
// The patrol picked its own start (the first waypoint in sight). Starting the macro
// here must not also trigger the macro-start "nearest waypoint" pick on the next
// tick: on a loop that is often a waypoint near the END (it comes back to the start),
// so the bot walked there, back to waypoint 0, and only then on (2026-10-08).
_macroWasRunning = true;
}
settings.CurrentNavPath = string.Empty;
settings.CurrentRoute = route;

View file

@ -0,0 +1,323 @@
using System;
using System.Text.RegularExpressions;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Out of the acid at once. A hotspot (an acid or lava pool, ACE's Hotspot) hurts every couple of
/// seconds while you stand in it and says so: "You suffer 32 damage from acid!". On 2026-10-07
/// Drakkon died twice that way in an hour: the patrol (once after a reload, once after a fight)
/// left him in a pool the hazard list didn't know, and topping up with healing kits held him there
/// - every kit stopped him, the acid matched each kit, and the kits ran his stamina out.
///
/// Now the first hotspot hit, while the macro runs, stops everything (combat, buffs, healing,
/// looting, the route, the meta: OnTick returns here, like the death hold) and walks the character
/// back out along its own footsteps (the positions it just came through, so a path it could walk)
/// to where it stood just before the hit. It hands back once it got there and no hit came
/// for HazardQuietMs. A dungeon cell it was hurt in is a hazard from then on (persisted), so the
/// patrol reroutes around it now and on later visits.
/// </summary>
public sealed partial class RynthAiPlugin
{
/// <summary>The escape clock (ms); host tests replace it.</summary>
internal static Func<long> HazardClock = static () => Environment.TickCount64;
/// <summary>No hit for this long = out of it (hotspots hit about every 2.5-3.5 s).</summary>
internal const long HazardQuietMs = 4000;
/// <summary>An escape that hasn't got out by then gives the tick back (and says so).</summary>
internal const long HazardEscapeMaxMs = 20000;
private const long HazardTrailSampleMs = 250;
private const int HazardTrailSize = 80; // 20 s of positions
private const double HazardArriveMeters = 0.6;
/// <summary>A footstep on the way counts as passed this close (the target needs HazardArriveMeters).</summary>
private const double HazardStepMeters = 1.0;
private const double HazardMinBackMeters = 2.5;
/// <summary>A trail point this long before the first hit is taken as outside the pool.</summary>
private const long HazardBeforeHitMs = 750;
private static readonly Regex HotspotDamageRx = new(
@"^You suffer (\d+) (?:points of )?damage from (?:the )?([A-Za-z][A-Za-z ]*?)[.!]*$",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private readonly (long At, uint Cell, float X, float Y)[] _hazardTrail = new (long, uint, float, float)[HazardTrailSize];
private int _hazardTrailHead;
private int _hazardTrailCount;
private long _hazardTrailLastAt;
private long _hazardLastHitAt;
private long _hazardFirstHitAt;
private long _hazardEscapeSince; // 0 = not escaping
private long _hazardArrivedAt; // 0 = still running to the target
private bool _hazardHasTarget;
private uint _hazardTargetCell;
private float _hazardTargetX, _hazardTargetY;
private long _hazardTargetAt; // the trail time of the target (older = further back)
/// <summary>The footsteps back to the target, newest first; the last one is the target.</summary>
private readonly System.Collections.Generic.List<(uint Cell, float X, float Y)> _hazardPath = new();
private int _hazardPathIdx;
private bool _hazardRunning;
private long _hazardRunBeatAt;
private string _hazardSource = "";
/// <summary>True while the escape owns the character.</summary>
internal bool HazardEscaping => _hazardEscapeSince != 0;
/// <summary>"You suffer 32 damage from acid!" -> 32, "acid". Broadcast text only.</summary>
internal static bool TryParseHotspotDamage(string? text, out int amount, out string source)
{
amount = 0;
source = "";
if (string.IsNullOrEmpty(text)) return false;
Match m = HotspotDamageRx.Match(text.Trim());
if (!m.Success || !int.TryParse(m.Groups[1].Value, out amount)) return false;
source = m.Groups[2].Value.Trim().ToLowerInvariant();
return true;
}
/// <summary>Chat hook: a hotspot hit starts (or pushes on) the escape.</summary>
internal void NoteHotspotChat(string? text, int chatType)
{
if (chatType != 0 || !TryParseHotspotDamage(text, out int amount, out string source)) return;
// Off (Escape Acid and Lava): neither the escape nor the learning - a character that walks
// through acid on purpose doesn't want the patrol rerouted around it either.
if (_dashboard?.Settings is { EscapeHazards: false }) return;
long now = HazardClock();
bool fresh = _hazardLastHitAt == 0 || now - _hazardLastHitAt > HazardQuietMs;
if (fresh) _hazardFirstHitAt = now;
_hazardLastHitAt = now;
_hazardSource = source;
if (Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _))
_objectCache?.RegisterDamageHazardCell(cell, source);
if (_dashboard?.Settings is not { IsMacroRunning: true }) return;
if (!HazardEscaping)
{
StartHazardEscape(now, amount);
return;
}
// Got to the target and still hurt: the pool reaches further back. Go further.
if (_hazardArrivedAt != 0 || !_hazardHasTarget)
{
_hazardArrivedAt = 0;
if (!PickHazardTarget(now, olderThan: _hazardHasTarget ? _hazardTargetAt : _hazardFirstHitAt - HazardBeforeHitMs + 1))
Log("[RynthAi] Hazard: still taking damage and no older spot to run back to; running on.");
}
}
/// <summary>Every tick: where the character stood (not while escaping, nor dead).</summary>
internal void RecordHazardTrail()
{
if (HazardEscaping) return;
long now = HazardClock();
if (now - _hazardTrailLastAt < HazardTrailSampleMs) return;
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out _, out _, out _, out _, out _) || cell == 0)
return;
_hazardTrailLastAt = now;
_hazardTrail[_hazardTrailHead] = (now, cell, x, y);
_hazardTrailHead = (_hazardTrailHead + 1) % HazardTrailSize;
if (_hazardTrailCount < HazardTrailSize) _hazardTrailCount++;
}
private void StartHazardEscape(long now, int amount)
{
_hazardEscapeSince = now;
_hazardArrivedAt = 0;
_hazardRunning = false;
PickHazardTarget(now, olderThan: _hazardFirstHitAt - HazardBeforeHitMs + 1);
Log($"[RynthAi] Hazard: took {amount} {_hazardSource} damage - stopping everything and moving out"
+ (_hazardHasTarget ? $" (back to ({_hazardTargetX:0.0}, {_hazardTargetY:0.0}))." : " (no earlier spot known: running back the way it faces)."));
try { Host.WriteToChat($"[RynthAi] Standing in {_hazardSource} - stopping everything to move out.", 1); } catch { }
try { if (Host.HasCancelAttack) Host.CancelAttack(); } catch { }
_combatManager?.ReleaseHeldTurn();
_navigationEngine?.Stop();
try { StopCorpseMovement(); } catch { }
}
/// <summary>
/// The newest trail point older than <paramref name="olderThan"/>, in this landblock, at least
/// HazardMinBackMeters away, preferring one outside a known hazard cell. False = none; then
/// the escape runs straight back from where it faces.
/// </summary>
private bool PickHazardTarget(long now, long olderThan)
{
_hazardHasTarget = false;
if (!Host.TryGetPlayerPose(out uint cell, out float px, out float py, out _, out float qw, out _, out _, out float qz))
return false;
int fallback = -1;
for (int k = 1; k <= _hazardTrailCount; k++)
{
int i = (_hazardTrailHead - k + HazardTrailSize) % HazardTrailSize;
var p = _hazardTrail[i];
if (p.At >= olderThan || (p.Cell >> 16) != (cell >> 16)) continue;
double d = Math.Sqrt((p.X - px) * (p.X - px) + (p.Y - py) * (p.Y - py));
if (d < HazardMinBackMeters) continue;
if (_objectCache?.IsHazardCell(p.Cell) == true)
{
if (fallback < 0) fallback = i;
continue;
}
SetHazardTarget(p);
return true;
}
if (fallback >= 0)
{
SetHazardTarget(_hazardTrail[fallback]);
return true;
}
// No trail (fresh login, or it all lies in the pool): 4 m straight back from the facing.
double yawDeg = ((-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI)) % 360.0 + 720.0) % 360.0;
double back = (yawDeg + 180.0) * Math.PI / 180.0;
SetHazardTarget((olderThan - 1, cell, (float)(px + 4.0 * Math.Sin(back)), (float)(py + 4.0 * Math.Cos(back))));
return false;
}
private void SetHazardTarget((long At, uint Cell, float X, float Y) p)
{
_hazardHasTarget = true;
_hazardTargetAt = p.At;
_hazardTargetCell = p.Cell;
_hazardTargetX = p.X;
_hazardTargetY = p.Y;
// The footsteps from now back to the target, newest first, thinned to about 1 m apart:
// the way it came in is a way it can walk out (no straight line through a wall).
_hazardPath.Clear();
_hazardPathIdx = 0;
float lx = float.NaN, ly = float.NaN;
for (int k = 1; k <= _hazardTrailCount; k++)
{
var t = _hazardTrail[(_hazardTrailHead - k + HazardTrailSize) % HazardTrailSize];
if (t.At <= p.At) break;
if ((t.Cell >> 16) != (p.Cell >> 16)) continue;
if (!float.IsNaN(lx) && (t.X - lx) * (t.X - lx) + (t.Y - ly) * (t.Y - ly) < 1.0f) continue;
_hazardPath.Add((t.Cell, t.X, t.Y));
lx = t.X; ly = t.Y;
}
_hazardPath.Add((p.Cell, p.X, p.Y));
}
/// <summary>
/// Called in OnTick right after the death hold. True = the escape owns this tick: nothing else
/// runs (no buffs, healing kits, combat, looting, route or meta).
/// </summary>
internal bool HoldForHazardEscape()
{
if (!HazardEscaping) return false;
long now = HazardClock();
if (_dashboard?.Settings is { EscapeHazards: false })
{
EndHazardEscape("Escape Acid and Lava was turned off");
return false;
}
if (_dashboard?.Settings is not { IsMacroRunning: true })
{
EndHazardEscape("the macro was stopped");
return false;
}
// Died, recalled or portalled meanwhile: the target is somewhere else now.
if (_hazardHasTarget && Host.TryGetPlayerPose(out uint cellNow, out _, out _, out _, out _, out _, out _, out _)
&& (cellNow >> 16) != (_hazardTargetCell >> 16))
{
EndHazardEscape("left the area");
return false;
}
bool quiet = now - _hazardLastHitAt >= HazardQuietMs;
if (now - _hazardEscapeSince > HazardEscapeMaxMs && quiet)
{
EndHazardEscape("no hit for a while");
return false;
}
if (now - _hazardEscapeSince > HazardEscapeMaxMs * 2)
{
EndHazardEscape($"still hurt after {HazardEscapeMaxMs * 2 / 1000} s - giving the tick back");
return false;
}
if (_hazardArrivedAt == 0 && _hazardHasTarget)
RunToHazardTarget(now);
if (_hazardArrivedAt != 0 && quiet)
{
EndHazardEscape("out of it");
return false;
}
return true;
}
private void RunToHazardTarget(long now)
{
if (!Host.TryGetPlayerPose(out _, out float px, out float py, out _, out _, out _, out _, out _))
return;
// Skip to just past the furthest footstep already reached (it may have been carried
// along, or started near the end); the last one is the target.
for (int j = _hazardPath.Count - 1; j >= _hazardPathIdx; j--)
{
var r = _hazardPath[j];
double rd = Math.Sqrt((r.X - px) * (r.X - px) + (r.Y - py) * (r.Y - py));
if (rd <= (j == _hazardPath.Count - 1 ? HazardArriveMeters : HazardStepMeters))
{
_hazardPathIdx = j + 1;
break;
}
}
double dx = 0, dy = 0;
if (_hazardPathIdx < _hazardPath.Count)
{
var w = _hazardPath[_hazardPathIdx];
dx = w.X - px; dy = w.Y - py;
}
if (_hazardPathIdx >= _hazardPath.Count)
{
_hazardArrivedAt = now;
StopHazardRun();
return;
}
double desired = Math.Atan2(dx, dy) * (180.0 / Math.PI);
if (desired < 0) desired += 360.0;
bool aligned = _navigationEngine?.ServoToward(desired) ?? TurnDirect(desired);
if (!aligned)
{
if (_hazardRunning) StopHazardRun();
return;
}
if (!_hazardRunning || now - _hazardRunBeatAt >= 500)
{
Host.SetAutoRunBy("Hazard", true);
_hazardRunning = true;
_hazardRunBeatAt = now;
}
}
private bool TurnDirect(double desired)
{
if (Host.HasTurnToHeading) Host.TurnToHeadingBy("Hazard", (float)desired);
return true;
}
private void StopHazardRun()
{
if (!_hazardRunning) return;
_hazardRunning = false;
Host.SetAutoRunBy("Hazard", false);
if (Host.HasStopCompletely) Host.StopCompletelyBy("Hazard");
}
private void EndHazardEscape(string why)
{
StopHazardRun();
Log($"[RynthAi] Hazard: {why} after {(HazardClock() - _hazardEscapeSince) / 1000.0:0.0} s - resuming.");
_hazardEscapeSince = 0;
_hazardArrivedAt = 0;
_hazardHasTarget = false;
_hazardPath.Clear();
_hazardTrailCount = 0; // the old trail runs through the pool
_navigationEngine?.ResumeFromNearestWaypoint();
}
}

View file

@ -131,6 +131,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Give queue — drained one item per tick with a cooldown (interval comes from settings)
private readonly Queue<(uint itemId, uint targetId, int stackSize)> _pendingGives = new();
private DateTime _lastGiveAt = DateTime.MinValue;
// The give the server hasn't answered yet (0 = none): the next one waits for it.
private uint _giveInFlightId, _giveInFlightTarget;
private int _giveInFlightAmount, _giveInFlightStack, _giveInFlightTries;
private long _giveInFlightAt;
private const long GiveConfirmMs = 3000;
private const int GiveMaxTries = 2;
private RynthCore.Loot.LootProfile? _nativeLootProfile;
private string _nativeLootProfilePath = string.Empty;
private DateTime _nativeLootProfileTime = DateTime.MinValue;
@ -677,6 +683,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
_inventoryManager = new InventoryManager(Host, _dashboard.Settings, _objectCache);
_manaStoneManager = new ManaStoneManager(Host, _dashboard.Settings, _objectCache);
LegacyUi.NavPoint.SpellNameLookup = id => SpellTableStub.GetById(id)?.Name; // recall steps by name
_manaStoneManager.IsLootKept = IsKeptByLootProfile;
_petManager = new PetManager(Host, _dashboard.Settings, _objectCache, _combatManager, _charSkills);
_combatManager.SummonOut = () => _petManager?.CurrentSummon();
@ -877,7 +884,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100),
["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2),
["PetMinMonsters"] = (1, 20),
["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (250, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100),
["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100),
["MinSkillLevelTier1"] = (1, 500), ["MinSkillLevelTier2"] = (1, 500), ["MinSkillLevelTier3"] = (1, 500), ["MinSkillLevelTier4"] = (1, 500),
["MinSkillLevelTier5"] = (1, 500), ["MinSkillLevelTier6"] = (1, 500), ["MinSkillLevelTier7"] = (1, 500), ["MinSkillLevelTier8"] = (1, 500),
["MonsterRange"] = (1, 200), ["MonsterDisengageRange"] = (0, 200), ["RingRange"] = (1, 50), ["ApproachRange"] = (1, 50),
@ -1476,6 +1483,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// finally below still submits the nav markers.
if (HoldForDeath())
return;
// Standing in acid or lava: nothing but getting out (RynthAiPlugin.HazardEscape.cs).
RecordHazardTrail();
if (HoldForHazardEscape())
return;
if (diag) Host.Log("[RynthAi] OnTick: before CheckBusyTimeout");
CheckBusyTimeout();
@ -2035,6 +2046,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
try { mmEat = MetaScheduleChat(text); } catch { }
if (mmEat) eat = 1;
else _dashboard?.PushChatLine(text, chatType);
try { NoteHotspotChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Hazard chat check failed: {ex.Message}"); }
_buffManager?.OnChatWindowText(text, chatType);
_manaStoneManager?.OnChatWindowText(text);
_petManager?.OnChatWindowText(text);
@ -3007,13 +3019,48 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
int count = _pendingGives.Count;
_pendingGives.Clear();
_giveInFlightId = 0;
ChatLine(count > 0
? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)."
: "[RynthAi] Give queue is already empty.");
}
/// <summary>
/// One give at a time, each after the server has taken the last: the item has left the
/// inventory (or its stack shrank, for part of a stack). The queue used to send a give
/// every 150 ms; the server takes one give at a time and answers the rest "too busy",
/// so /ub give handed over one item and dropped the rest (2026-10-08). A give with no
/// answer in GiveConfirmMs is sent once more, then skipped.
/// </summary>
private void DrainGiveQueue()
{
long now = Environment.TickCount64;
if (_giveInFlightId != 0)
{
if (GiveLanded())
{
_giveInFlightId = 0;
_lastGiveAt = DateTime.UtcNow;
if (_pendingGives.Count == 0)
ChatLine("[RynthAi] Give queue complete.");
}
else if (now - _giveInFlightAt < GiveConfirmMs)
return;
else if (_giveInFlightTries < GiveMaxTries)
{
GiveItem(_giveInFlightId, _giveInFlightTarget, _giveInFlightAmount, _giveInFlightStack);
_giveInFlightTries++;
_giveInFlightAt = now;
return;
}
else
{
ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it.");
_giveInFlightId = 0;
if (_pendingGives.Count == 0) return;
}
}
if (_pendingGives.Count == 0) return;
int intervalMs = _dashboard?.Settings.GiveQueueIntervalMs ?? 150;
if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return;
@ -3024,9 +3071,21 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize;
GiveItem(itemId, targetId, stackSize, whole);
_lastGiveAt = DateTime.UtcNow;
_giveInFlightId = itemId;
_giveInFlightTarget = targetId;
_giveInFlightAmount = stackSize;
_giveInFlightStack = whole;
_giveInFlightTries = 1;
_giveInFlightAt = now;
}
if (_pendingGives.Count == 0)
ChatLine("[RynthAi] Give queue complete.");
/// <summary>The in-flight give went through: the item left the inventory, or part of its stack did.</summary>
private bool GiveLanded()
{
if (_objectCache?[unchecked((int)_giveInFlightId)] is not WorldObject wo) return true;
if (!InPlayerInventory(wo.Container)) return true;
return _giveInFlightAmount < _giveInFlightStack
&& Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < _giveInFlightStack;
}
/// <summary>

View file

@ -76,6 +76,7 @@ internal sealed class AutoVendorManager
private long _nextPollAt;
private int _failures;
private readonly HashSet<uint> _sessionSkip = new(); // items the engine refused to sell
private readonly HashSet<string> _sellSkipLogged = new(StringComparer.OrdinalIgnoreCase); // names logged as held back this session
private readonly List<uint> _idQueue = new();
private readonly Dictionary<uint, (int Attempts, long LastAt)> _idState = new();
@ -457,6 +458,7 @@ internal sealed class AutoVendorManager
_profilePath = path;
_failures = 0;
_sessionSkip.Clear();
_sellSkipLogged.Clear();
_bailAt = Now();
_nextActionAt = 0;
_host.Log($"[RynthAi] AutoVendor: {_vendorName} [0x{merchantId:X8}] profile '{path}' ({_profile.Rules.Count} rules)");
@ -853,14 +855,36 @@ internal sealed class AutoVendorManager
SafetyFacts safety = ReadSafety(wo, player);
string? unsafeWhy = AutoVendorPlanner.UnsafeReason(safety, _settings.AutoVendorOnlyFromMainPack);
if (unsafeWhy != null && heldBack == null)
{
if (!_sellSkipLogged.Contains(wo.Name))
{
ProfileVerdict uv = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx));
// "Not identified" is usually just not yet (the IDs are on their way): only a
// certain Sell match is worth a line.
if (uv.Rule?.Action == VTankLootAction.Sell && uv.Certain && _sellSkipLogged.Add(wo.Name))
_host.Log($"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{uv.RuleName}'): {unsafeWhy}.");
}
continue;
}
uint type = ItemType(wo);
int stack = StackOf(wo);
bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
int unitValue = stack > 1 ? safety.Value / stack : safety.Value;
if (unsafeWhy == null && !AutoVendorPlanner.VendorWillBuy(v, type, isNote, unitValue))
{
// A Sell rule wanted it and the vendor won't take it: say why, once per name a
// session (peas not sold at Aun Amanaualuan, 2026-10-07, with nothing logged).
if (heldBack == null && !_sellSkipLogged.Contains(wo.Name))
{
ProfileVerdict sv = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx));
if (sv.Rule?.Action == VTankLootAction.Sell && sv.Certain && _sellSkipLogged.Add(wo.Name))
_host.Log(!v.Buys(type)
? $"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{sv.RuleName}'): this vendor doesn't buy {AutoVendorPlanner.CategoryName(type)} (item type 0x{type:X}, vendor buys 0x{v.ItemTypes:X})."
: $"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{sv.RuleName}'): worth {unitValue:n0} each, this vendor pays for items up to {v.MaxValue:n0}.");
}
continue;
}
ItemFacts f = InventoryFacts(wo, safety.Appraised);
ProfileVerdict verdict = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), f, ctx));
@ -876,6 +900,8 @@ internal sealed class AutoVendorManager
{
if (heldBack != null && verdict.Rule?.Action == VTankLootAction.Sell)
heldBack.Add($"{wo.Name} - {sd.Reason}");
else if (heldBack == null && verdict.Rule?.Action == VTankLootAction.Sell && _sellSkipLogged.Add(wo.Name))
_host.Log($"[RynthAi] AutoVendor: not selling '{wo.Name}': {sd.Reason}.");
continue;
}

View file

@ -254,7 +254,9 @@ internal static class AutoVendorPlanner
if (f.IsRare) return "rare";
if (onlyFromMainPack && !f.InMainPack) return "not in main pack";
if (f.Attuned != 0) return "attuned";
if (f.Bonded != 0) return "bonded";
// Not Bonded: on ACE it only decides what a death keeps (PropertyInt.Bonded, Player_Death);
// it never stops a sale. Peas, trade notes and salvage bags are bonded so a death keeps
// them, and AutoVendor held them all back (2026-10-07). Quest items are not sellable anyway.
if (f.Retained) return "retained";
if (f.TimesTinkered > 0) return "tinkered";
if (f.Imbued != 0) return "imbued";

View file

@ -22,7 +22,7 @@ internal sealed class AtlasLocation
// A portal's destination.
public bool HasDest, DestOnMap;
public double DestNs, DestEw;
public string DestName = "", DestPlace = "";
public string DestName = "", DestPlace = "", DestCell = "";
public int MinLevel, MaxLevel;
public bool Quest, Closed;
}
@ -92,6 +92,7 @@ internal sealed class Atlas
l.DestOnMap = TryNum(d, "ns", out l.DestNs) & TryNum(d, "ew", out l.DestEw);
l.DestName = Str(d, "name");
l.DestPlace = Str(d, "place");
l.DestCell = Str(d, "cell");
}
locs.Add(l);
}
@ -110,6 +111,36 @@ internal sealed class Atlas
public AtlasLocation? ById(int id) => _byId.TryGetValue(id, out var l) ? l : null;
/// <summary>
/// Landblocks that are dungeons: places (and portal destinations) the Atlas has in "dungeon"
/// cells, less any landblock with places on the map. A dungeon's nav_XXXX.tile holds only that
/// landblock's surface (a flat sheet; RynthNav.Baker leaves dungeon cells out), so it isn't
/// a navmesh for walking inside the dungeon.
/// </summary>
public HashSet<uint> DungeonLandblocks()
{
var dungeon = new HashSet<uint>();
var map = new HashSet<uint>();
foreach (AtlasLocation l in Locations)
{
if (TryLandblock(l.Cell, out uint lb))
{
if (l.OnMap) map.Add(lb);
else if (l.Place.Equals("dungeon", StringComparison.Ordinal)) dungeon.Add(lb);
}
if (l.HasDest && !l.DestOnMap && l.DestPlace.Equals("dungeon", StringComparison.Ordinal) && TryLandblock(l.DestCell, out uint dlb))
dungeon.Add(dlb);
}
dungeon.ExceptWith(map);
return dungeon;
}
private static bool TryLandblock(string cell, out uint lb)
{
lb = 0;
return cell.Length == 8 && uint.TryParse(cell.AsSpan(0, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb);
}
// ── Search ───────────────────────────────────────────────────────────────
/// <summary>How well <paramref name="name"/> matches <paramref name="q"/> (lower case): 0 = not at all.</summary>

View file

@ -8,7 +8,11 @@ namespace RynthCore.Plugin.RynthNav;
// Where a character's personal recalls land. The client is never told (the server keeps
// a character's lifestone, ties, last portal and house), so RynthNav learns them from what
// it sees: the server's messages ("You have attuned your spirit to this Lifestone.", "X is
// recalling home.") and the teleport that follows. Saved per character in
// recalling home.") and the teleport that follows, and a teleport right after your own spell
// words (a recall cast by hand: RecallPlanner.GuessHandCast). ACE sends a character neither
// its tie positions (PlayerDescription carries only LastOutsideDeath) nor the tied portals'
// data ids (LinkedPortalOne/Two aren't SendOnLogin and change silently), so a tie made
// before RynthNav was there is learned on the first cast of its recall. Saved per character in
// NavData\recalls.txt. No host calls: the offline tests compile this file.
// (GoArrow kept the same kind of per-character recall list; Digero 2006, Virindi 2011, MIT.)
@ -61,6 +65,9 @@ internal enum RecallEvent
RecallingHometown,
/// <summary>"Name is recalling to the marketplace." (lands in a dungeon: never used for routes).</summary>
RecallingMarketplace,
/// <summary>"You say, "Zojak Ququ"" on the spellcasting channel: you started casting a spell
/// (a recall cast by hand teleports a few seconds later).</summary>
OwnSpellWords,
}
internal sealed class RecallMemory
@ -108,15 +115,21 @@ internal sealed class RecallMemory
}
}
/// <summary>ChatMessageType.Spellcasting: the words a caster speaks (yours: "You say, "...").</summary>
public const int ChatTypeSpellcasting = 17;
/// <summary>
/// Reads a chat line (the server's own wording, ACE's Player_Location / Lifestone /
/// WorldObject_Magic). <paramref name="playerName"/> picks out your own "is recalling"
/// lines from other players' nearby.
/// lines from other players' nearby. <paramref name="chatType"/> tells your spell words
/// (Spellcasting, 17) from something you typed in local chat (Speech, 2).
/// </summary>
public static RecallEvent Classify(string? text, string? playerName)
public static RecallEvent Classify(string? text, string? playerName, int chatType = -1)
{
if (string.IsNullOrEmpty(text)) return RecallEvent.None;
string t = text.Trim();
if (chatType == ChatTypeSpellcasting && t.StartsWith("You say, \"", StringComparison.Ordinal))
return RecallEvent.OwnSpellWords;
if (t.StartsWith("You have attuned your spirit to this Lifestone", StringComparison.OrdinalIgnoreCase))
return RecallEvent.AttunedLifestone;
if (t.StartsWith("You have successfully linked with the life stone", StringComparison.OrdinalIgnoreCase))

View file

@ -71,13 +71,13 @@ internal static class RecallPlanner
if (known != null)
{
AddLearnedSpell(list, notes, known, memory, charKey, LifestoneRecall, "Lifestone Recall", RecallSlot.Lifestone,
"cast Lifestone Tie on a lifestone");
"cast Lifestone Tie on a lifestone, cast Lifestone Recall once, or /rnav tie lifestone at the tied lifestone");
AddLearnedSpell(list, notes, known, memory, charKey, PortalRecall, "Portal Recall", RecallSlot.LastPortal,
"walk through a portal");
AddLearnedSpell(list, notes, known, memory, charKey, PrimaryPortalTieRecall, "Primary Portal Tie Recall", RecallSlot.Tie1,
"cast Primary Portal Tie on a portal");
"cast Primary Portal Tie on a portal, cast Primary Portal Tie Recall once, or /rnav tie 1 at the tied portal");
AddLearnedSpell(list, notes, known, memory, charKey, SecondaryPortalTieRecall, "Secondary Portal Tie Recall", RecallSlot.Tie2,
"cast Secondary Portal Tie on a portal");
"cast Secondary Portal Tie on a portal, cast Secondary Portal Tie Recall once, or /rnav tie 2 at the tied portal");
}
// Command recalls (no spell): @lifestone always; house, mansion and hometown
@ -123,6 +123,115 @@ internal static class RecallPlanner
private static string Where(RecallSpot s) => s.Label.Length > 0 ? "in " + s.Label : "in a dungeon";
// ── Learning from a recall cast by hand ──────────────────────────────────
/// <summary>Recall the Sanctuary (Lifestone Sending): lands where @lifestone does.</summary>
public const int RecallTheSanctuary = 2023;
/// <summary>WeenieError YouMustLinkToLifestoneToRecall / YouMustLinkToPortalToRecall.</summary>
public const uint ErrorMustLinkLifestone = 0x049E, ErrorMustLinkPortal = 0x04A3;
/// <summary>What a teleport right after your own spell words teaches.</summary>
public enum HandCast
{
/// <summary>Nothing new (already known, a fixed recall, or can't tell); <c>why</c> says which.</summary>
Nothing,
/// <summary>The landing of <c>slot</c>.</summary>
Learn,
/// <summary>A portal tie recall, but not which: ask (/rnav tie 1|2).</summary>
AskTie,
}
/// <summary>
/// You spoke spell words, stood still and were teleported: a recall cast by hand. Which
/// one, from where it landed: on a lifestone, Lifestone Recall; anywhere else, a portal tie
/// recall (Portal Recall's landing is the last portal's, already known). A landing that
/// matches a recall already known teaches nothing. When the spellbook leaves more than one
/// tie recall (or Portal Recall with no last portal known), ask. No host calls.
/// </summary>
/// <param name="atLifestone">The landing is on a lifestone (the Atlas's).</param>
/// <param name="nearUnits">Two landings this close are the same place.</param>
public static HandCast GuessHandCast(RecallSpot landing, bool atLifestone, ISet<int>? known, RecallMemory memory,
string charKey, double nearUnits, out RecallSlot slot, out string why)
{
slot = RecallSlot.Lifestone;
if (known == null) { why = "the spellbook isn't read yet"; return HandCast.Nothing; }
if (atLifestone)
{
if (!known.Contains(LifestoneRecall)) { why = "on a lifestone, but Lifestone Recall isn't in the spellbook"; return HandCast.Nothing; }
if (Same(memory.Get(charKey, RecallSlot.Lifestone), landing, nearUnits)) { why = "Lifestone Recall, already known"; return HandCast.Nothing; }
if (known.Contains(RecallTheSanctuary) && Same(memory.Get(charKey, RecallSlot.Sanctuary), landing, nearUnits))
{ why = "on your @lifestone lifestone: Lifestone Recall or Recall the Sanctuary, can't tell"; return HandCast.Nothing; }
why = "on a lifestone: Lifestone Recall";
return HandCast.Learn;
}
if (Same(memory.Get(charKey, RecallSlot.LastPortal), landing, nearUnits)) { why = "where the last portal went: Portal Recall"; return HandCast.Nothing; }
var ties = new List<RecallSlot>(2);
if (known.Contains(PrimaryPortalTieRecall)) ties.Add(RecallSlot.Tie1);
if (known.Contains(SecondaryPortalTieRecall)) ties.Add(RecallSlot.Tie2);
foreach (RecallSlot t in ties)
if (Same(memory.Get(charKey, t), landing, nearUnits)) { slot = t; why = RecallMemory.SlotName(t) + ", already known"; return HandCast.Nothing; }
if (ties.Count == 0) { why = "no portal tie recall in the spellbook (a spell's teleport RynthNav doesn't know)"; return HandCast.Nothing; }
bool maybePortalRecall = known.Contains(PortalRecall) && memory.Get(charKey, RecallSlot.LastPortal) == null;
if (ties.Count == 1 && !maybePortalRecall)
{
slot = ties[0];
why = "the only portal tie recall in the spellbook";
return HandCast.Learn;
}
slot = ties[0];
why = maybePortalRecall ? "a portal tie recall or Portal Recall (no last portal known yet)" : "a portal tie recall, primary or secondary";
return HandCast.AskTie;
}
/// <summary>Two landings are the same place: on the map within <paramref name="nearUnits"/>; off it, the same label.</summary>
public static bool Same(RecallSpot? a, RecallSpot b, double nearUnits)
{
if (a == null || a.OnMap != b.OnMap) return false;
if (a.OnMap) return NavCoords.Distance(a.Ns, a.Ew, b.Ns, b.Ew) < nearUnits;
return a.Label.Equals(b.Label, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// The recall the server says isn't linked: "You must link to a lifestone to recall it" is
/// always Lifestone Recall; "...to a portal..." is whichever portal recall was just cast
/// (<paramref name="castSpell"/>, 0 = not known: nothing).
/// </summary>
public static RecallSlot? SlotUnlinked(uint error, int castSpell) => error switch
{
ErrorMustLinkLifestone => RecallSlot.Lifestone,
ErrorMustLinkPortal => castSpell switch
{
PrimaryPortalTieRecall => RecallSlot.Tie1,
SecondaryPortalTieRecall => RecallSlot.Tie2,
PortalRecall => RecallSlot.LastPortal,
_ => null,
},
_ => null,
};
/// <summary>The recall spell whose landing a slot holds (0 for the command recalls).</summary>
public static int SpellFor(RecallSlot slot) => slot switch
{
RecallSlot.Lifestone => LifestoneRecall,
RecallSlot.LastPortal => PortalRecall,
RecallSlot.Tie1 => PrimaryPortalTieRecall,
RecallSlot.Tie2 => SecondaryPortalTieRecall,
_ => 0,
};
/// <summary>A slot's name for players ("Primary Portal Tie Recall", "@lifestone").</summary>
public static string Title(RecallSlot slot) => slot switch
{
RecallSlot.Sanctuary => "@lifestone",
RecallSlot.Lifestone => "Lifestone Recall",
RecallSlot.LastPortal => "Portal Recall",
RecallSlot.Tie1 => "Primary Portal Tie Recall",
RecallSlot.Tie2 => "Secondary Portal Tie Recall",
RecallSlot.House => "House recall",
RecallSlot.Mansion => "Allegiance mansion recall",
_ => "Allegiance hometown recall",
};
public static List<RecallLink> Links(List<RecallOption> options)
{
var links = new List<RecallLink>(options.Count);

View file

@ -0,0 +1,109 @@
using System;
using DotRecast.Core.Numerics;
using DotRecast.Detour;
namespace RynthCore.Plugin.RynthNav;
// Running into a wall: the walk is running but the character isn't moving. The navmesh is baked
// with a 2 m agent radius (RynthNav.Baker), which seals gaps under ~4 m and leaves some ground in
// little islands (Shoushi's plaza, where the Town Network drops you, 10-08); where the plan runs
// out the walk heads straight for its goal for a moment (BlindPushTicks), and that, or a wall the
// mesh doesn't show, used to mean running into it until the 30 s progress watchdog. Now: blocked
// for StuckWindowMs = turn away at an angle (alternating sides), plan again, and after
// StuckMaxTries on one leg without progress stop and say where.
public sealed partial class RynthNavPlugin
{
private const long StuckWindowMs = 1200; // running this long...
private const double StuckMoveUnits = 0.6; // ...and moved less than this = blocked (a run covers 4+ u/s)
private const long UnstickMs = 1600; // then turn away from it and run this long (~0.5 s of it turning)
private const double UnstickAngleDeg = 120.0; // away from where it was heading, off to one side
private const int StuckMaxTries = 4; // blocked this often on a leg without progress = stop
private bool _ranLastTick; // the walk asked to run last tick (not standing, not turning in place)
private double _lastDriveDeg;
private long _stuckWinMs, _unstickUntilMs;
private double _stuckWx, _stuckWy, _unstickDeg;
private int _stuckTries, _stuckSide = 1;
/// <summary>DriveTo for the walk's own steering: remembers that it ran and which way.</summary>
private void WalkDrive(double deg)
{
DriveTo(deg);
_lastDriveDeg = deg;
_ranLastTick = !_turnInPlace;
}
/// <summary>
/// Nothing between here and (<paramref name="tx"/>, <paramref name="ty"/>) as far as the navmesh
/// shows: every metre of the line, bar 2 m at each end (we and a portal stand off the eroded
/// mesh), is within 1.5 m of walkable ground. A wall leaves a gap of twice the agent radius plus
/// its thickness, over 4 m, so its middle fails. No query (no tiles): true, as before.
/// </summary>
private bool StraightOnMesh(double tx, double ty)
{
if (_query == null) return true;
var filter = new DtQueryDefaultFilter();
double dx = tx - _wx, dy = ty - _wy, len = Math.Sqrt(dx * dx + dy * dy);
for (double s = 2.0; s < len - 2.0; s += 1.0)
{
var pt = new RcVec3f((float)(_wx + dx * s / len), (float)_wz, (float)(_wy + dy * s / len));
_query.FindNearestPoly(pt, new RcVec3f(1.5f, 4, 1.5f), filter, out long r, out _, out _);
if (r == 0) return false;
}
return true;
}
/// <summary>A new leg (or goto): nothing blocked yet.</summary>
private void ResetBlocked()
{
_ranLastTick = false;
_stuckWinMs = 0; _unstickUntilMs = 0; _stuckTries = 0;
}
/// <summary>
/// Once per walking tick, before steering. True when it drove this tick (stepping round
/// something) or finished the goto; the caller returns.
/// </summary>
private bool StepBlocked()
{
long now = NowMs;
bool ran = _ranLastTick;
_ranLastTick = false;
if (_unstickUntilMs > now)
{
DriveTo(_unstickDeg);
lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})";
return true;
}
if (_unstickUntilMs != 0)
{
// Stepped aside: plan again from here (and allow one more push where the plan ends).
_unstickUntilMs = 0;
lock (_gotoGate) _gotoPath = null;
_blindTicks = 0; _replanTick = 0;
_stuckWinMs = 0;
return false;
}
if (!ran || _stuckWinMs == 0) { _stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy; return false; }
if (now - _stuckWinMs < StuckWindowMs) return false;
double moved = Math.Sqrt((_wx - _stuckWx) * (_wx - _stuckWx) + (_wy - _stuckWy) * (_wy - _stuckWy));
_stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy;
if (moved >= StuckMoveUnits) return false;
string at = NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx));
if (++_stuckTries > StuckMaxTries)
{
string why; lock (_gate) why = _status;
FinishGoto($"stopped: blocked at {at} ({StuckMaxTries} tries to get round it; something in the way the map doesn't show) ({why})");
return true;
}
_stuckSide = -_stuckSide;
_unstickDeg = ((_lastDriveDeg + 180.0 - _stuckSide * (180.0 - UnstickAngleDeg)) % 360.0 + 360.0) % 360.0;
_unstickUntilMs = now + UnstickMs;
Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {StuckWindowMs / 1000.0:F1} s); "
+ $"turning to {_unstickDeg:F0} and planning again ({_stuckTries}/{StuckMaxTries})");
DriveTo(_unstickDeg);
lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})";
return true;
}
}

View file

@ -114,13 +114,14 @@ public sealed partial class RynthNavPlugin
long now = NowMs;
if (landblockChanged && _hasPose)
{
try { _tileHere = File.Exists(Path.Combine(NavDataDir, $"nav_{CurrentLandblock:X4}.tile")) ? 1 : 0; } catch { _tileHere = -1; }
// A dungeon's tile is its landblock's surface: no navmesh here (RynthNavPlugin.InDungeon).
try { _tileHere = !InDungeon(_cellId) && File.Exists(Path.Combine(NavDataDir, $"nav_{CurrentLandblock:X4}.tile")) ? 1 : 0; } catch { _tileHere = -1; }
}
if (now < _nextInfoMs || now - Interlocked.Read(ref _lastStatusPollMs) > PanelPollWindowMs) return;
_nextInfoMs = now + InfoRefreshMs;
if (Interlocked.Exchange(ref _infoBusy, 1) != 0) return;
uint lb = CurrentLandblock;
bool hasPose = _hasPose;
bool hasPose = _hasPose, dungeon = InDungeon(_cellId);
Task.Run(() =>
{
try
@ -129,7 +130,7 @@ public sealed partial class RynthNavPlugin
if (Directory.Exists(NavDataDir))
foreach (string _ in Directory.EnumerateFiles(NavDataDir, "nav_*.tile")) n++;
_tilesOnDisk = n;
if (hasPose) _tileHere = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile")) ? 1 : 0;
if (hasPose) _tileHere = !dungeon && File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile")) ? 1 : 0;
}
catch { }
finally { Interlocked.Exchange(ref _infoBusy, 0); }

View file

@ -29,6 +29,10 @@ public sealed partial class RynthNavPlugin
private const long RecallCastWindowMs = 40000; // our own recall cast -> the teleport within this
private const long RecallStepTimeoutMs = 45000; // a route's recall step gives up after this
private const long RecallRecastMs = 4500; // re-cast a recall spell this often while waiting
private const long HandCastWindowMs = 12000; // your spell words -> portal space within this = a recall cast by hand
private const double HandCastStillUnits = 2.0; // ...standing still meanwhile (walking into a portal moves you)
private const double LifestoneLandUnits = 10.0; // a landing this close to a lifestone = on it (Lifestone Recall)
private const double PortalBesideUnits = 4.0; // a live portal this close as portal space begins: maybe that portal, not a recall
private const long StanceRetryMs = 1500;
private const long WandAfterMs = 6000; // no magic stance by then: try wielding a wand
private const int CombatModeNonCombat = 1, CombatModeMagic = 8;
@ -37,6 +41,7 @@ public sealed partial class RynthNavPlugin
private volatile Atlas _atlas = Atlas.Empty;
private volatile string _atlasStatus = "loading…";
private HashSet<uint> _mapLandblocks = new(); // landblocks with Atlas places on the map (tick thread)
private volatile HashSet<uint> _dungeonLandblocks = new(); // dungeon landblocks the Atlas knows (Atlas.DungeonLandblocks; read-only once built)
private AtlasStore _store = new();
private RecallMemory _memory = new();
private bool _storesLoaded;
@ -67,12 +72,18 @@ public sealed partial class RynthNavPlugin
private int _castRecallSpell;
private long _castRecallMs;
private RecallSpot? _pendingTie;
// Your own spell words (a recall cast by hand teleports a few seconds later): when and where.
private long _selfCastMs;
private double _selfCastWx, _selfCastWy;
private bool _selfCastDied;
private int _weenieSeq = -1; // the last server refusal looked at (-1 = none yet)
// Teleport tracking (tick thread).
private bool _trkPortaling, _trkHaveLast, _trkHavePre;
private uint _trkLastCell, _trkPreCell;
private double _trkLastWx, _trkLastWy, _trkPreWx, _trkPreWy;
private long _trkLastTeleportMs;
private long _trkLastTeleportMs, _trkPortalStartMs;
private bool _trkPortalBeside; // a live portal stood right beside you as portal space began
// Route planning with recalls: the recalls the current route can use (by RouteStep.RecallIndex).
private List<RecallOption> _routeRecalls = new();
@ -146,7 +157,7 @@ public sealed partial class RynthNavPlugin
private void OnLoginTravel()
{
_charKey = ""; _playerName = ""; _known = null; _nextKnownMs = 0;
_pendingRecallSlot = null; _castRecallSpell = 0; _pendingTie = null;
_pendingRecallSlot = null; _castRecallSpell = 0; _pendingTie = null; _selfCastMs = 0;
_trkHaveLast = false; _trkPortaling = false;
}
@ -175,6 +186,7 @@ public sealed partial class RynthNavPlugin
foreach (var l in atlas.Locations)
if (l.OnMap && l.Cell.Length == 8 && uint.TryParse(l.Cell.AsSpan(0, 4), NumberStyles.HexNumber, null, out uint lb)) lbs.Add(lb);
_mapLandblocks = lbs;
_dungeonLandblocks = atlas.DungeonLandblocks();
_indexedAtlas = atlas;
if (_known != null && atlas.Recalls.Count > 0) LogKnownRecalls(_known);
}
@ -183,6 +195,10 @@ public sealed partial class RynthNavPlugin
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd, fromPanel: false);
while (_recallEvents.TryDequeue(out var ev)) OnRecallEvent(ev.Event, ev.Ms);
PollRecallRefusal();
if (_selfCastMs != 0 && !_selfCastDied && now - _selfCastMs < HandCastWindowMs + 30000
&& Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _) && maxHp > 0 && hp == 0)
_selfCastDied = true; // died mid-cast: the trip to the lifestone that follows isn't a recall
bool teleported = TrackTeleport(now);
UpdateArrow(teleported);
@ -250,6 +266,12 @@ public sealed partial class RynthNavPlugin
/// <summary>Outdoors, or in a building of a landblock that has Atlas places on the map.</summary>
private bool IsOnMap(uint cell) => (cell & 0xFFFF) < 0x100 || _mapLandblocks.Contains(cell >> 16);
/// <summary>
/// In a dungeon the Atlas knows. Its landblock's tile is the surface's (dungeon cells aren't
/// baked), so there is no navmesh to walk here even though nav_XXXX.tile exists.
/// </summary>
private bool InDungeon(uint cell) => (cell & 0xFFFF) >= 0x100 && _dungeonLandblocks.Contains(cell >> 16);
// ── Teleports: the arrow's portal/recall steps and learning recall landings ──
private bool TrackTeleport(long now)
@ -260,6 +282,9 @@ public sealed partial class RynthNavPlugin
if (!_trkPortaling)
{
_trkPortaling = true;
_trkPortalStartMs = now;
// Only worth the look after your own spell words (a hand-cast recall, or a portal used standing at it?).
_trkPortalBeside = _selfCastMs != 0 && now - _selfCastMs < HandCastWindowMs && _trkHaveLast && LivePortalWithin(_trkLastWx, _trkLastWy, PortalBesideUnits);
_trkHavePre = _trkHaveLast;
_trkPreCell = _trkLastCell; _trkPreWx = _trkLastWx; _trkPreWy = _trkLastWy;
}
@ -273,23 +298,32 @@ public sealed partial class RynthNavPlugin
bool havePre = _trkPortaling ? _trkHavePre : _trkHaveLast;
uint preCell = _trkPortaling ? _trkPreCell : _trkLastCell;
double preWx = _trkPortaling ? _trkPreWx : _trkLastWx, preWy = _trkPortaling ? _trkPreWy : _trkLastWy;
long startMs = _trkPortaling ? _trkPortalStartMs : now;
bool portalBeside = _trkPortaling && _trkPortalBeside;
_trkPortaling = false;
if (now - _trkLastTeleportMs > 2000)
{
teleported = true;
_trkLastTeleportMs = now;
OnTeleported(havePre, preCell, preWx, preWy);
OnTeleported(havePre, preCell, preWx, preWy, startMs, portalBeside);
}
}
_trkHaveLast = true; _trkLastCell = _cellId; _trkLastWx = _wx; _trkLastWy = _wy;
return teleported;
}
private void OnTeleported(bool havePre, uint preCell, double preWx, double preWy)
private void OnTeleported(bool havePre, uint preCell, double preWx, double preWy, long startMs, bool portalBeside)
{
long now = NowMs;
RecallSpot landing = SpotHere();
string who = _charKey;
// Your spell words shortly before portal space, standing still since, not dead, no portal
// right beside you: a recall cast by hand (walking into a portal moves you; using one you
// stand at doesn't, hence the portal check; dying is a trip, not a recall).
bool handCast = _selfCastMs != 0 && startMs - _selfCastMs >= 0 && startMs - _selfCastMs < HandCastWindowMs
&& !_selfCastDied && havePre && !portalBeside
&& Math.Sqrt((preWx - _selfCastWx) * (preWx - _selfCastWx) + (preWy - _selfCastWy) * (preWy - _selfCastWy)) < HandCastStillUnits;
_selfCastMs = 0; _selfCastDied = false;
if (who.Length == 0) return;
if (_pendingRecallSlot is RecallSlot slot && now - _pendingRecallMs < RecallAnnounceWindowMs)
@ -312,7 +346,17 @@ public sealed partial class RynthNavPlugin
RecallPlanner.SecondaryPortalTieRecall => RecallSlot.Tie2,
_ => null,
};
if (learned is RecallSlot ls) _memory.Set(who, ls, landing);
if (learned is RecallSlot ls)
{
_memory.Set(who, ls, landing);
Host.Log($"[RynthNav] learned {RecallMemory.SlotName(ls)} lands at {Describe(landing)}");
}
return;
}
// A recall cast by hand (or by another plugin): never the last portal's landing.
if (handCast && !CameThroughAtlasPortal(havePre, preCell, preWx, preWy, landing))
{
LearnHandCast(landing);
return;
}
// Not a recall we know of: a portal, most likely. Portal Recall goes back to where
@ -341,6 +385,101 @@ public sealed partial class RynthNavPlugin
return false;
}
/// <summary>A live portal object within <paramref name="units"/> of a world point (this landblock's objects).</summary>
private bool LivePortalWithin(double wx, double wy, double units)
{
if (!Host.HasGetLiveObjectIds) return false;
foreach (uint id in Host.GetLiveObjectIds())
{
if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue;
if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out _) || cell == 0) continue;
double ox = ((cell >> 24) & 0xFF) * 192.0 + x, oy = ((cell >> 16) & 0xFF) * 192.0 + y;
if ((ox - wx) * (ox - wx) + (oy - wy) * (oy - wy) < units * units) return true;
}
return false;
}
/// <summary>
/// A known portal stood where you were, and goes where you landed: the teleport was that
/// portal (used standing at it), not the spell you'd just cast.
/// </summary>
private bool CameThroughAtlasPortal(bool havePre, uint preCell, double preWx, double preWy, RecallSpot landing)
{
if (!havePre || !IsOnMap(preCell) || !landing.OnMap) return false;
double pns = NavCoords.NsFromWorld(preWy), pew = NavCoords.EwFromWorld(preWx);
foreach (AtlasLocation l in _atlas.Locations)
{
if (!l.OnMap || !l.HasDest || !l.DestOnMap || !l.Type.Equals("Portal", StringComparison.Ordinal)) continue;
if (NavCoords.Distance(pns, pew, l.Ns, l.Ew) < PortalNearUnits
&& NavCoords.Distance(landing.Ns, landing.Ew, l.DestNs, l.DestEw) < RecallNearUnits) return true;
}
return false;
}
/// <summary>
/// A recall cast by hand (RynthNav didn't cast it): learn which one from where it landed
/// (RecallPlanner.GuessHandCast), so ties made before RynthNav was there, or cast from the
/// spell bar, are planned from now on.
/// </summary>
private void LearnHandCast(RecallSpot landing)
{
if (landing.OnMap)
foreach (AtlasRecall r in _atlas.Recalls)
if (r.OnMap && NavCoords.Distance(landing.Ns, landing.Ew, r.Ns, r.Ew) < RecallNearUnits)
{
Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {r.Name}'s landing, nothing to learn");
return;
}
AtlasLocation? ls = landing.OnMap ? _atlas.Nearest("Lifestone", landing.Ns, landing.Ew, LifestoneLandUnits) : null;
RecallPlanner.HandCast kind = RecallPlanner.GuessHandCast(landing, ls != null, _known, _memory, _charKey, RecallNearUnits,
out RecallSlot slot, out string why);
switch (kind)
{
case RecallPlanner.HandCast.Learn:
if (ls != null) landing.Label = ls.Name + (landing.Label.Length > 0 ? " (" + landing.Label + ")" : "");
_memory.Set(_charKey, slot, landing);
Host.Log($"[RynthNav] learned {RecallMemory.SlotName(slot)} lands at {Describe(landing)} (a recall cast by hand: {why})");
Say($"{RecallPlanner.Title(slot)} takes you to {Describe(landing)}: routes can use it now.");
break;
case RecallPlanner.HandCast.AskTie:
_pendingTie = landing;
Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {why}; asking which tie");
Say($"Recalled to {Describe(landing)}. If that was a portal tie recall: /rnav tie 1 (primary) or /rnav tie 2 (secondary).");
break;
default:
Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {why}");
break;
}
}
/// <summary>
/// The server's "You must link to a lifestone / portal to recall it": that recall has no
/// tie (any more), so forget its landing; a route waiting on it plans again without it.
/// </summary>
private void PollRecallRefusal()
{
if (!Host.HasGetLastWeenieError || !Host.TryGetLastWeenieError(out int seq, out uint error, out _, out _)) return;
if (_weenieSeq < 0 || seq == _weenieSeq) { _weenieSeq = seq; return; } // the first look only notes where the count stands
_weenieSeq = seq;
int cast = _castRecallSpell != 0 && NowMs - _castRecallMs < RecallCastWindowMs ? _castRecallSpell : 0;
if (RecallPlanner.SlotUnlinked(error, cast) is not RecallSlot slot || _charKey.Length == 0) return;
bool had = _memory.Get(_charKey, slot) != null;
_memory.Clear(_charKey, slot);
if (slot == RecallSlot.Tie1 || slot == RecallSlot.Tie2) _pendingTie = null;
string name = RecallPlanner.Title(slot);
Host.Log($"[RynthNav] {name}: the server says it isn't linked (0x{error:X4}){(had ? "; its landing is forgotten" : "")}");
RecallOption? o = _recallWait ? CurrentRecallOption() : null;
if (o != null && o.SpellId == RecallPlanner.SpellFor(slot) && _gotoActive)
{
string goal = _gotoName, type = _gotoType, enter = _enterName, enterType = _enterType;
double gns = NavCoords.NsFromWorld(_finalTns), gew = NavCoords.EwFromWorld(_finalTew);
Say($"goto: {name} isn't tied to anything; planning again without it");
EndRecall();
StartWalk(goal.Length > 0 ? goal : NavCoords.Fmt(gns, gew), type, gns, gew, enter, enterType);
}
else if (had) Say($"{name} isn't tied to anything: routes won't use it until you tie it again.");
}
/// <summary>Where you stand now, as a recall landing: on the map or not, and a label.</summary>
private RecallSpot SpotHere()
{
@ -362,7 +501,7 @@ public sealed partial class RynthNavPlugin
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
RecallEvent e = RecallMemory.Classify(text, _playerName);
RecallEvent e = RecallMemory.Classify(text, _playerName, chatType);
if (e != RecallEvent.None) _recallEvents.Enqueue((e, NowMs));
}
@ -396,6 +535,11 @@ public sealed partial class RynthNavPlugin
case RecallEvent.RecallingMarketplace:
_pendingRecallSlot = null;
break;
case RecallEvent.OwnSpellWords:
// Any spell: only a teleport soon after, standing here, makes it a recall (OnTeleported).
if (!_hasPose) break;
_selfCastMs = ms; _selfCastWx = _wx; _selfCastWy = _wy; _selfCastDied = false;
break;
default:
if (RecallMemory.SlotFor(e, out RecallSlot slot))
{
@ -428,23 +572,42 @@ public sealed partial class RynthNavPlugin
return l == null ? null : new RecallSpot { OnMap = true, Ns = l.Ns, Ew = l.Ew, Label = l.Name };
}
private void OnPortalTied()
/// <summary>
/// The tied portal: the selected portal, looked up in the Atlas by its weenie class (ACE
/// ties the portal's class), else the nearest portal in the Atlas within <paramref name="nearUnits"/>.
/// </summary>
private AtlasLocation? TiePortal(double nearUnits)
{
// The tied portal's destination: the selected portal, looked up in the Atlas by its
// weenie class (ACE ties the portal's class), else the nearest portal in the Atlas.
AtlasLocation? portal = null;
uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
PlayerMapPos(out double pns, out double pew);
if (sel != 0 && Host.TryGetObjectWcid(sel, out uint wcid)) portal = _atlas.PortalByWcid(wcid, pns, pew);
portal ??= _hasPose ? _atlas.Nearest("Portal", pns, pew, 60) : null;
portal ??= _hasPose ? _atlas.Nearest("Portal", pns, pew, nearUnits) : null;
return portal;
}
private static RecallSpot TieLanding(AtlasLocation portal) => portal.DestOnMap
? new RecallSpot { OnMap = true, Ns = portal.DestNs, Ew = portal.DestEw, Label = portal.Name }
: new RecallSpot { OnMap = false, Label = portal.DestName.Length > 0 ? portal.DestName : portal.Name };
/// <summary>/rnav tie 1|2 with no tie waiting: where the portal you've selected or stand at goes.</summary>
private RecallSpot? TiedPortalSpot(out string why)
{
AtlasLocation? portal = TiePortal(PortalNearUnits);
why = portal == null ? "select the tied portal, or stand at it, first"
: !portal.HasDest ? $"{portal.Name} isn't in the Atlas with a destination" : "";
return portal != null && portal.HasDest ? TieLanding(portal) : null;
}
private void OnPortalTied()
{
AtlasLocation? portal = TiePortal(60);
if (portal == null || !portal.HasDest)
{
Say("Portal tie noted, but the portal isn't in the Atlas: its recall won't be used for routes.");
return;
}
var spot = portal.DestOnMap
? new RecallSpot { OnMap = true, Ns = portal.DestNs, Ew = portal.DestEw, Label = portal.Name }
: new RecallSpot { OnMap = false, Label = portal.DestName.Length > 0 ? portal.DestName : portal.Name };
RecallSpot spot = TieLanding(portal);
bool k1 = _known?.Contains(RecallPlanner.PrimaryPortalTie) ?? false, k2 = _known?.Contains(RecallPlanner.SecondaryPortalTie) ?? false;
if (k1 && !k2) { _memory.Set(_charKey, RecallSlot.Tie1, spot); Say($"Primary portal tie: {portal.Name}."); return; }
if (k2 && !k1) { _memory.Set(_charKey, RecallSlot.Tie2, spot); Say($"Secondary portal tie: {portal.Name}."); return; }
@ -819,7 +982,7 @@ public sealed partial class RynthNavPlugin
"/rnav arrow <place|coords> | arrow off | arrow route <place> — the arrow\n" +
"/rnav go <place|coords> — walk there (route with portals/recalls when /rnav portals on)\n" +
"/rnav route <place|coords> — plan a route (portals and recalls), no walking\n" +
"/rnav atlas <search> — find places | fav [place] — favorite | recalls [on|off] | tie 1|2\n" +
"/rnav atlas <search> — find places | fav [place] — favorite | recalls [on|off] | tie 1|2|lifestone\n" +
"/rnav goto <coords> | preview <coords> | portals on|off | stop | here | load | test | navdata\n" +
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>\n" +
"/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" +
@ -1026,14 +1189,46 @@ public sealed partial class RynthNavPlugin
foreach (string n in notes) Say(" " + n);
}
/// <summary>
/// /rnav tie 1|2: which portal tie the last one (or the last tie recall cast by hand) was;
/// with none waiting, the portal you have selected or stand at is that tie (a tie made
/// before RynthNav was there). /rnav tie lifestone: the lifestone you have selected or
/// stand at is the one Lifestone Recall is tied to. /rnav tie clear 1|2|lifestone forgets one.
/// </summary>
private void CmdTie(string rest)
{
if (_pendingTie == null || _charKey.Length == 0) { Note("no portal tie waiting — cast a Portal Tie on a portal first"); return; }
RecallSlot slot = rest.Trim() == "2" ? RecallSlot.Tie2 : rest.Trim() == "1" ? RecallSlot.Tie1 : (RecallSlot)(-1);
if ((int)slot < 0) { Say("/rnav tie 1 (primary) or /rnav tie 2 (secondary)"); return; }
_memory.Set(_charKey, slot, _pendingTie);
Note($"{(slot == RecallSlot.Tie1 ? "Primary" : "Secondary")} portal tie: {Describe(_pendingTie)}");
_pendingTie = null;
if (_charKey.Length == 0) { Note("not logged in yet"); return; }
string arg = rest.Trim().ToLowerInvariant();
bool clear = arg.StartsWith("clear", StringComparison.Ordinal);
if (clear) arg = arg.Substring(5).Trim();
RecallSlot slot = arg switch
{
"1" => RecallSlot.Tie1,
"2" => RecallSlot.Tie2,
"lifestone" or "ls" => RecallSlot.Lifestone,
_ => (RecallSlot)(-1),
};
if ((int)slot < 0) { Say("/rnav tie 1 (primary) | 2 (secondary) | lifestone, or /rnav tie clear 1|2|lifestone"); return; }
string name = RecallPlanner.Title(slot);
if (clear)
{
_memory.Clear(_charKey, slot);
Note($"{name}: landing forgotten (routes won't use it until it's learned again)");
return;
}
RecallSpot? spot;
if (slot == RecallSlot.Lifestone)
{
// The Atlas lifestone at the selected object (anything else selected doesn't count), else the nearest one.
RecallSpot? sel = SelectedObjectSpot(out _);
AtlasLocation? ls = sel != null && sel.OnMap ? _atlas.Nearest("Lifestone", sel.Ns, sel.Ew, LifestoneLandUnits) : null;
spot = ls != null ? new RecallSpot { OnMap = true, Ns = ls.Ns, Ew = ls.Ew, Label = ls.Name } : NearestAtlasSpot("Lifestone", 40);
if (spot == null) { Note("tie lifestone: select your tied lifestone, or stand at it, first"); return; }
}
else if (_pendingTie != null) { spot = _pendingTie; _pendingTie = null; }
else if ((spot = TiedPortalSpot(out string why)) == null) { Note($"tie {arg}: {why}"); return; }
_memory.Set(_charKey, slot, spot);
Note($"{name}: {Describe(spot)}");
}
/// <summary>Plans a route (portals and, unless off, recalls) and shows it in the panel. Tick thread.</summary>

View file

@ -496,6 +496,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
// needs no navmesh here.
bool recallFirst = _route != null && _route.Count > 0 && (_route[0].UseRecall || _route[0].IsHub);
uint hereLb = CurrentLandblock;
// A dungeon's landblock has a tile too, but it's the surface's (dungeon cells aren't
// baked): walking on it inside the dungeon runs into walls. Say so instead.
if (!recallFirst && InDungeon(_cellId))
{
_route = null;
lock (_gate) { _status = $"in a dungeon (0x{hereLb:X4}): no navmesh"; _lastPath = ""; }
Note($"goto: no navmesh inside dungeons yet (landblock 0x{hereLb:X4}); walk out through its portal, or turn on recalls so the route can start with one");
return;
}
if (!recallFirst && !File.Exists(Path.Combine(NavDataDir, $"nav_{hereLb:X4}.tile")))
{
_route = null;
@ -638,6 +647,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
// ArrivalUnits from the typed point. Standing on that spot is arriving.
bool atMeshGoal = !isPortalLeg && _goalOnMesh &&
Math.Sqrt((_goalMeshEw - _wx) * (_goalMeshEw - _wx) + (_goalMeshNs - _wy) * (_goalMeshNs - _wy)) < ArrivalUnits;
// A portal is run into straight from PortalArriveUnits: only with nothing between, as far as
// the navmesh shows. A portal round a corner (a wall within 14 u of it) is reached along
// the path first; it used to be run at through the wall, 12 s a try, five tries.
if (isPortalLeg && toGoal < arrive && toGoal > PortalContactUnits && !atMeshGoal)
{
bool pathLeft;
lock (_gotoGate) pathLeft = _gotoPath != null && _gotoIdx < _gotoPath.Count;
if (pathLeft && !StraightOnMesh(_gotoTew, _gotoTns)) arrive = PortalContactUnits;
}
if (toGoal < arrive || atMeshGoal)
{
OnSubGoalReached();
@ -650,7 +668,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
// Following a route over land, progress is what's left of the route (it can lead away
// from the target for a while); otherwise the straight distance.
double left = _coarse != null ? _coarse.Remaining(_wx, _wy) : toGoal;
if (left < _bestDist - ProgressUnits) { _bestDist = left; _bestTick = _legTicks; }
if (left < _bestDist - ProgressUnits) { _bestDist = left; _bestTick = _legTicks; _stuckTries = 0; }
else if (_coarse != null && left > _bestDist + RouteLostUnits)
{
// Following a route but getting ever farther from it: stop rather than wander.
@ -664,6 +682,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
FinishGoto($"stopped: no progress for 30 s, {toGoal:F0}u short ({why})");
return;
}
// Running into something (RynthNavPlugin.Blocked.cs): turn away, plan again, or stop and say where.
if (StepBlocked()) return;
// Plan at once, re-plan every 20 ticks, and every 5 while there is no plan.
bool due = _gotoPath == null ? (_replanTick++ % 5) == 0 : (++_replanTick % 20) == 0;
@ -709,7 +729,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
// Straight at the goal, or along the route at its next crossing.
double bh = (_coarse != null ? Math.Atan2(_aimEw - _wx, _aimNs - _wy) : Math.Atan2(fdew, fdns)) * 180.0 / Math.PI;
bh = SteerRoundPortals(bh < 0 ? bh + 360.0 : bh, 10.0);
DriveTo(bh);
WalkDrive(bh);
if (_blindTicks % 10 == 0) lock (_gotoGate) _gotoPath = null; // re-plan soon
}
else if (_blindTicks++ == BlindPushTicks)
@ -728,7 +748,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
// hub portals' circles, a wall beside), it held 234 deg into the wall while the path wanted
// 301 and re-planned every 0.6 s (10-01 20:07, "just spazzing"). Steering is for the
// blind push and the last steps onto a portal, where there is no path.
DriveTo(desired);
WalkDrive(desired);
}
// ── Portal routing ───────────────────────────────────────────────────────────
@ -776,6 +796,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
else { _gotoTew = _finalTew; _gotoTns = _finalTns; }
// New leg: fresh progress watchdog, and the old leg's walkable end no longer counts.
ResetHub();
ResetBlocked();
_coarseHoldTicks = _graph != null ? CoarseHoldMaxTicks : 0;
_nextAvoidMs = 0;
_walkHaveLast = false; // a new leg starts where the last step's teleport put us
@ -790,6 +811,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
_gotoActive = false; _route = null; _portalWait = false;
ResetHub();
_avoid.Clear(); _coarseHoldTicks = 0;
ResetBlocked();
Host.SetAutoRun(false); Host.StopCompletely();
lock (_gate) _status = status;
Host.Log($"[RynthNav] goto: {status}");
@ -942,7 +964,11 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
var filter = new DtQueryDefaultFilter();
var startP = new RcVec3f((float)_wx, (float)_wz, (float)_wy);
_query.FindNearestPoly(startP, new RcVec3f(8, 64, 8), filter, out long sRef, out RcVec3f sPt, out _);
// The ground we stand on first: the mesh keeps the agent radius (2 m) from walls, so close
// up it's within that, at our height. Only then the wide search, which can pick ground on
// the far side of a thin wall or a roof overhead, and the walk then runs into that wall.
_query.FindNearestPoly(startP, new RcVec3f(2.5f, 4, 2.5f), filter, out long sRef, out RcVec3f sPt, out _);
if (sRef == 0) _query.FindNearestPoly(startP, new RcVec3f(8, 64, 8), filter, out sRef, out sPt, out _);
// A failed plan drops the old one: StepGoto must not keep following a stale path.
if (sRef == 0) { lock (_gate) _status = "off navmesh"; lock (_gotoGate) _gotoPath = null; return; }
@ -1025,8 +1051,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy);
if (ol < 0.05) continue; // straight on: no corner to clear
double nx = px + ox / ol * _wallClearance, ny = py + oy / ol * _wallClearance;
q2.FindNearestPoly(new RcVec3f((float)nx, (float)_wz, (float)ny), new RcVec3f(0.3f, 24, 0.3f), filter, out long rr, out _, out _);
if (rr != 0) wps[i] = (nx, ny);
// Only onto walkable ground itself (inside a polygon), not merely near it: near it,
// the moved corner could sit closer to the wall than the body is wide.
q2.FindNearestPoly(new RcVec3f((float)nx, (float)_wz, (float)ny), new RcVec3f(0.3f, 24, 0.3f), filter, out long rr, out RcVec3f rp, out _);
if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) wps[i] = (nx, ny);
}
}
lock (_gotoGate) { _gotoPath = wps; _gotoIdx = 0; }
@ -1161,9 +1189,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
bool exists = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile"));
int onDisk = 0;
try { if (Directory.Exists(NavDataDir)) onDisk = Directory.GetFiles(NavDataDir, "nav_*.tile").Length; } catch { }
bool indoors = (_cellId & 0xFFFF) >= 0x0100;
bool indoors = (_cellId & 0xFFFF) >= 0x0100, dungeon = InDungeon(_cellId);
string status; lock (_gate) status = _status;
return $"landblock 0x{lb:X4}{(indoors ? " (indoors)" : "")} — tile {(exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, "
return $"landblock 0x{lb:X4}{(dungeon ? " (a dungeon)" : indoors ? " (indoors)" : "")} — tile "
+ $"{(dungeon ? (exists ? "surface only, no dungeon navmesh" : "MISSING") : exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, "
+ $"{onDisk} tile(s) in {NavDataDir}; route graph: {_graphStatus}; Town Network: {_townNetStatus}; goto {(_gotoActive ? "ACTIVE" : "off")}"
+ $"{(_coarse != null ? $" (route {_coarse.Crossed}/{_coarse.Count})" : "")}, portals {(_portalsEnabled ? "on" : "off")}; status: {status}";
}

View file

@ -133,6 +133,11 @@ public sealed class LootEditItemRequest
public string RuleName { get; set; } = string.Empty;
/// <summary>True: the profile open in the Loot Editor; false: the one RynthAi loots with.</summary>
public bool ToOpenProfile { get; set; }
/// <summary>
/// Also require the item's T11 attributes (LootItemRuleOptions.IncludeT11). Added
/// 2026-10-07; an older engine never sends it, so it reads false.
/// </summary>
public bool IncludeT11 { get; set; }
/// <summary>Echoed in the draft so the popup knows the answer is to its latest ask.</summary>
public int Seq { get; set; }
}
@ -156,6 +161,10 @@ public sealed class LootEditItemDraft
public string Format { get; set; } = string.Empty;
/// <summary>What was built (the defaults filled in).</summary>
public int Match { get; set; }
/// <summary>The rule was asked to include the item's T11 attributes (added 2026-10-07).</summary>
public bool IncludeT11 { get; set; }
/// <summary>The item is T11 gear, so "Include T11 attributes" has something to add (added 2026-10-07).</summary>
public bool IsT11 { get; set; }
public int Action { get; set; }
public int KeepCount { get; set; }
public string RuleName { get; set; } = string.Empty;

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot.T11;
using RynthCore.Loot.VTank;
namespace RynthCore.Loot.Editing;
@ -26,6 +27,11 @@ public sealed class LootItemFacts
public Dictionary<int, double> Doubles { get; set; } = new();
/// <summary>The item's spell names (empty when none or not identified).</summary>
public List<string> Spells { get; set; } = new();
/// <summary>
/// The item's T11 reading (ACECustom tier 11+ text), or null when it wasn't asked for.
/// <see cref="T11ItemInfo.None"/> for an item that isn't T11 gear.
/// </summary>
public T11ItemInfo? T11 { get; set; }
public bool Stackable => MaxStackSize > 1 || StackSize > 1;
@ -53,6 +59,11 @@ public sealed class LootItemRuleOptions
public int? KeepCount { get; set; }
/// <summary>Null or blank: "Keep Copper Pea" and the like.</summary>
public string? RuleName { get; set; }
/// <summary>
/// Also require the item's T11 attributes (tier, grade, damage %, each modifier, slot
/// special, Cast on Strike), each at least as good as this item's. Works with any match.
/// </summary>
public bool IncludeT11 { get; set; }
}
/// <summary>A built rule, ready to preview and insert.</summary>
@ -155,6 +166,7 @@ public static class LootItemRules
};
bool hasClass = f.ObjectClass != (int)AcObjectClass.Unknown;
LootItemMatch match = o.Match;
bool likeBare = false;
if (match == LootItemMatch.NameAndClass && !hasClass)
{
match = LootItemMatch.Name;
@ -177,13 +189,15 @@ public static class LootItemRules
return null;
}
rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass)));
int extra = AddLikeConditions(rule, f, notes);
if (extra == 0)
notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}."
+ (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty));
likeBare = AddLikeConditions(rule, f, notes) == 0;
break;
}
int t11Added = o.IncludeT11 ? AddT11Conditions(rule, f, notes) : 0;
if (likeBare && t11Added == 0)
notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}."
+ (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty));
string defaultName = DefaultRuleName(name.Length > 0 ? name : ClassName(f.ObjectClass), action, keep, match);
string ruleName = OneLine(o.RuleName).Trim();
rule.Name = ruleName.Length > 0 ? ruleName : defaultName;
@ -248,6 +262,59 @@ public static class LootItemRules
return rule.Conditions.Count - n;
}
/// <summary>
/// The T11 conditions, on RynthAi's virtual T11 keys: Is T11, then tier, grade, damage %,
/// every catalogued modifier, slot special and Cast on Strike count, each at least this
/// item's. Left out on purpose: Can Wield (the character, not the item), Zone Locked
/// (where it was appraised), the wield gates (they follow from the tier) and the modifier
/// count / rating total / roll % (they follow from the per-modifier values).
/// How many it added.
/// </summary>
private static int AddT11Conditions(VTankLootRule rule, LootItemFacts f, List<string> notes)
{
T11ItemInfo? t = f.T11;
if (t == null || !t.IsT11)
{
notes.Add("Not a T11 item, so there are no T11 attributes to add.");
return 0;
}
int n = rule.Conditions.Count;
void Equal(int key, int v) => rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyE, Num(v), Num(key)));
void AtLeast(int key, int v) { if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyGE, Num(v), Num(key))); }
Equal(T11Keys.IsT11, 1);
if (!t.HasText)
{
notes.Add("The item hasn't been identified, so only \"Is T11\" could be added. Assess it and preview again for its tier, grade and modifiers.");
return rule.Conditions.Count - n;
}
AtLeast(T11Keys.EstimatedTier, t.EstimatedTier);
AtLeast(T11Keys.WeaponGrade, t.GradeRank);
AtLeast(T11Keys.DamagePercent, t.DamagePercent);
bool valuelessSpecial = false;
var unknown = new List<string>();
foreach (T11Modifier m in t.Modifiers)
{
if (T11Catalog.ModifierByKey(m.Key) == null)
{
unknown.Add(m.Name);
continue;
}
// A modifier's key reads 0 when it is absent, so a value-less one can't be required by value.
if (m.Value > 0) AtLeast(T11Keys.ForModifier(m.Key), m.Value);
else if (m.IsSlotSpecial) valuelessSpecial = true;
}
if (valuelessSpecial) Equal(T11Keys.HasSlotSpecial, 1);
AtLeast(T11Keys.CastOnStrikeCount, t.Procs.Count);
if (unknown.Count > 0)
notes.Add("Left out (RynthAi has no loot key for these modifiers yet): " + string.Join(", ", unknown) + ".");
return rule.Conditions.Count - n;
}
private static VTankLootCondition Cond(int type, params string[] lines) => new(type, "0", lines);
private static string Num(int v) => v.ToString(CultureInfo.InvariantCulture);

View file

@ -480,7 +480,6 @@ internal static class Program
(new SafetyFacts { Appraised = true, Value = 100, CanBeSold = false }, "not sellable"),
(new SafetyFacts { Appraised = true, Value = 100, IsRare = true }, "rare"),
(new SafetyFacts { Appraised = true, Value = 100, Attuned = 1 }, "attuned"),
(new SafetyFacts { Appraised = true, Value = 100, Bonded = 1 }, "bonded"),
(new SafetyFacts { Appraised = true, Value = 100, Retained = true }, "retained"),
(new SafetyFacts { Appraised = true, Value = 100, TimesTinkered = 1 }, "tinkered"),
(new SafetyFacts { Appraised = true, Value = 100, Imbued = 1 }, "imbued"),
@ -495,6 +494,8 @@ internal static class Program
var side = new SafetyFacts { Appraised = true, Class = AcObjectClass.Salvage, Value = 100, InMainPack = false };
Eq(AutoVendorPlanner.UnsafeReason(side, false), null, "side pack ok by default");
// Bonded only decides what a death keeps on ACE: peas, trade notes and salvage are bonded and sell (2026-10-07).
Eq(AutoVendorPlanner.UnsafeReason(new SafetyFacts { Appraised = true, Value = 12500, Bonded = 1 }, false), null, "bonded (kept on death) still sells");
Eq(AutoVendorPlanner.UnsafeReason(side, true), "not in main pack", "OnlyFromMainPack");
}

View file

@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Loot.Editing;
using RynthCore.Loot.T11;
using RynthCore.Loot.VTank;
namespace RynthCore.LootSdkTests;
// "Add to loot profile" with "Include T11 attributes" (2026-10-07): the T11 conditions a
// clicked item adds, on the server-format weapon and armor text LootT11Tests parses.
internal static partial class Program
{
private static void RunLootAddT11Tests()
{
Console.WriteLine("\n-- LootAdd: include T11 attributes --");
TestAddT11Weapon();
TestAddT11Armor();
TestAddT11EdgeCases();
}
/// <summary>A condition as "type:line,line" for order-sensitive comparisons.</summary>
private static string CondText(VTankLootCondition c) => c.NodeType + ":" + string.Join(",", c.DataLines);
private static string GE(int key, int v) => $"{VTankNodeTypes.LongValKeyGE}:{v},{key}";
private static string EQ(int key, int v) => $"{VTankNodeTypes.LongValKeyE}:{v},{key}";
private static List<string> T11Conds(VTankLootRule r) =>
r.Conditions.Where(c => c.DataLines.Count == 2 && int.TryParse(c.DataLines[1], out int k) && T11Keys.IsVirtual(k))
.Select(CondText).ToList();
private static LootItemFacts T11Facts(string name, AcObjectClass cls, string? longDesc, string? use) => new()
{
Id = 0x7000_0001,
Name = name,
ObjectClass = (int)cls,
T11 = T11ItemInfo.Parse(name, longDesc, use),
};
private static void TestAddT11Weapon()
{
LootItemFacts f = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, T11WeaponLongDesc, null);
LootItemRuleDraft? off = LootItemRules.Build(f, new LootItemRuleOptions(), out _);
Eq(off == null ? -1 : T11Conds(off.Rule).Count, 0, "add t11: unchecked adds no T11 conditions");
LootItemRuleDraft? d = LootItemRules.Build(f, new LootItemRuleOptions { IncludeT11 = true }, out string err);
Check(d != null, "add t11: weapon builds (" + err + ")");
if (d == null) return;
Eq(CondText(d.Rule.Conditions[0]), $"{VTankNodeTypes.ObjectClass}:{(int)AcObjectClass.MeleeWeapon}", "add t11: name + class first");
Eq(string.Join(" | ", T11Conds(d.Rule)), string.Join(" | ", new[]
{
EQ(T11Keys.IsT11, 1),
GE(T11Keys.EstimatedTier, 13),
GE(T11Keys.WeaponGrade, 12),
GE(T11Keys.DamagePercent, 86),
GE(T11Keys.ForModifier(28), 41), // Damage Rating
GE(T11Keys.ForModifier(29), 10), // Crit Damage Rating
GE(T11Keys.ForModifier(44), 2), // Pct HP Damage: a slot special with a value
GE(T11Keys.CastOnStrikeCount, 1),
}), "add t11: weapon conditions, at least this item's");
Check(d.Rule.Conditions.All(c => CondText(c) != EQ(T11Keys.HasSlotSpecial, 1)), "add t11: valued special needs no Has Slot Special");
Check(d.Rule.Conditions.All(c => CondText(c) != EQ(T11Keys.ZoneLocked, 1)), "add t11: zone lock left out");
Eq(d.Notes.Count, 0, "add t11: weapon has no notes");
Check(LootItemRules.PreviewLines(d.Rule).Any(l => l.Contains("T11 Mod: Damage Rating")), "add t11: preview names the modifier key");
var dropped = new List<string>();
LootRule? native = LootItemRules.ToNative(d.Rule, dropped);
Eq(dropped.Count, 0, "add t11: native format keeps every T11 condition");
Eq(native?.Conditions.Count ?? -1, d.Rule.Conditions.Count, "add t11: native condition count");
}
private static void TestAddT11Armor()
{
LootItemFacts f = T11Facts("T11 - Celdon Breastplate", AcObjectClass.Armor, T11ArmorLongDesc, T11ArmorUse);
LootItemRuleDraft? d = LootItemRules.Build(f, new LootItemRuleOptions { IncludeT11 = true }, out _);
Check(d != null, "add t11: armor builds");
if (d == null) return;
List<string> t = T11Conds(d.Rule);
Check(t.Contains(GE(T11Keys.EstimatedTier, 16)), "add t11: armor tier from the Triune Weave gate");
Check(!t.Any(c => c.EndsWith("," + T11Keys.WeaponGrade)), "add t11: no grade on armor");
Check(t.Contains(GE(T11Keys.ForModifier(50), 8)), "add t11: Damage Resist");
Check(t.Contains(GE(T11Keys.ForModifier(19), 120)), "add t11: Max Health");
Check(t.Contains(GE(T11Keys.ForModifier(47), 2)), "add t11: Max Health Pct");
Check(!t.Any(c => c.EndsWith("," + T11Keys.ForModifier(60))), "add t11: unknown modifier has no condition");
Check(d.Notes.Any(n => n.Contains("Modifier 60")), "add t11: unknown modifier named in a note");
}
private static void TestAddT11EdgeCases()
{
// Not T11 gear: a note, no conditions.
var plain = new LootItemFacts { Id = 2, Name = "Iron Mace", ObjectClass = (int)AcObjectClass.MeleeWeapon, T11 = T11ItemInfo.None };
LootItemRuleDraft? p = LootItemRules.Build(plain, new LootItemRuleOptions { IncludeT11 = true }, out _);
Eq(p == null ? -1 : T11Conds(p.Rule).Count, 0, "add t11: non-T11 item adds nothing");
Check(p != null && p.Notes.Any(n => n.StartsWith("Not a T11 item")), "add t11: non-T11 note");
// T11 by name but not identified yet: Is T11 only, and a note to assess it.
LootItemFacts unid = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, null, null);
LootItemRuleDraft? u = LootItemRules.Build(unid, new LootItemRuleOptions { IncludeT11 = true }, out _);
Eq(u == null ? "" : string.Join(" | ", T11Conds(u.Rule)), EQ(T11Keys.IsT11, 1), "add t11: unidentified gives Is T11 only");
Check(u != null && u.Notes.Any(n => n.Contains("hasn't been identified")), "add t11: unidentified note");
// A value-less slot special is required through Has Slot Special.
LootItemFacts ring = T11Facts("T11 - Ring", AcObjectClass.Jewelry, null, "Modifiers:\n- Fortify Vitals\n");
LootItemRuleDraft? r = LootItemRules.Build(ring, new LootItemRuleOptions { IncludeT11 = true }, out _);
Check(r != null && T11Conds(r.Rule).Contains(EQ(T11Keys.HasSlotSpecial, 1)), "add t11: value-less special -> Has Slot Special");
// "Items like this": T11 conditions count, so the "matches every X" warning goes away.
LootItemFacts like = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, T11WeaponLongDesc, null);
LootItemRuleDraft? l = LootItemRules.Build(like, new LootItemRuleOptions { Match = LootItemMatch.Like, IncludeT11 = true }, out _);
Check(l != null && !l.Notes.Any(n => n.StartsWith("Nothing but the class")), "add t11: like + T11 is not class-only");
Check(l != null && l.Rule.Conditions.All(c => c.NodeType != VTankNodeTypes.StringValueMatch), "add t11: like still has no name");
LootItemRuleDraft? bare = LootItemRules.Build(plain, new LootItemRuleOptions { Match = LootItemMatch.Like, IncludeT11 = true }, out _);
Check(bare != null && bare.Notes.Any(n => n.StartsWith("Nothing but the class")), "add t11: like + non-T11 still warns class-only");
}
}

View file

@ -45,6 +45,7 @@ internal static partial class Program
RunLootEditTests(args);
RunLootAddTests(args);
RunT11Tests();
RunLootAddT11Tests();
Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed.");

View file

@ -124,6 +124,14 @@
</DataTemplate></DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Wl" Width="26" CanUserResize="False" CanUserSort="False">
<DataGridTemplateColumn.CellTemplate><DataTemplate>
<ToggleButton Classes="light" Content="Wl"
IsChecked="{Binding UseWall, Mode=TwoWay}"
ToolTip.Tip="Wall — War wall spells (a row of projectiles straight ahead; turns to face the target first). Needs Wall Range in the settings."/>
</DataTemplate></DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!-- Name -->
<DataGridTemplateColumn Header="Name" Width="*" MinWidth="100">
<DataGridTemplateColumn.CellTemplate><DataTemplate>

View file

@ -18,7 +18,7 @@ public class MonsterRule : INotifyPropertyChanged
private string _damageType = "Auto";
private int _weaponId;
private bool _fester, _broadside, _gravityWell, _imperil, _yield, _vuln;
private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast;
private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast, _useWall;
private string _exVuln = "None";
private int _offhandId;
private string _petDamage = "PAuto";
@ -46,6 +46,7 @@ public class MonsterRule : INotifyPropertyChanged
public bool UseRing { get => _useRing; set { _useRing = value; OnPropertyChanged(); } }
public bool UseStreak { get => _useStreak; set { _useStreak = value; OnPropertyChanged(); } }
public bool UseBlast { get => _useBlast; set { _useBlast = value; OnPropertyChanged(); } }
public bool UseWall { get => _useWall; set { _useWall = value; OnPropertyChanged(); } }
public string ExVuln { get => _exVuln; set { _exVuln = value; OnPropertyChanged(); } }
public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } }
public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } }

View file

@ -91,6 +91,9 @@ internal static unsafe class FakeHost
public static bool GiveCalls;
/// <summary>Every GiveObjectTo (item, target, amount; 0 = the whole object), in order.</summary>
public static readonly List<(uint Item, uint Target, int Amount)> Gives = new();
/// <summary>When true (the default) a give lands at once, as the server does when it isn't busy:
/// the item goes to the target. False = the server hasn't taken it (still carried).</summary>
public static bool GiveLands = true;
/// <summary>Opt-in: wires StopCompletely (off by default so no other test sees it).</summary>
public static bool StopCalls;
/// <summary>StopCompletely calls (opt-in with <see cref="StopCalls"/>).</summary>
@ -196,7 +199,7 @@ internal static unsafe class FakeHost
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear();
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear();
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); GiveLands = true;
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
@ -631,7 +634,12 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetBusyState() => BusyStateValue;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); return 1; }
private static int GiveObjectTo(uint item, uint target, int amount)
{
Gives.Add((item, target, amount));
if (GiveLands && amount == 0) Containers[item] = target;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCurrentCombatMode() => CombatModeValue;

View file

@ -69,6 +69,7 @@ internal static class Program
HealLatencyTests.Register(runner);
BlastTests.Register(runner);
ArcWhenClearTests.Register(runner);
WallTests.Register(runner);
UseAtLoginTests.Register(runner);
LearnSpellsTests.Register(runner);
AttackLatencyTests.Register(runner);
@ -82,6 +83,9 @@ internal static class Program
ItemInfoTests.Register(runner);
NavOverlayTests.Register(runner);
ActionPacingTests.Register(runner);
HazardEscapeTests.Register(runner);
ManaStoneChoiceTests.Register(runner);
CustomDebuffTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -87,7 +87,9 @@ internal static class AttackLatencyTests
Check.Eq(CombatManager.AttackIntervalMs(Missile, 1500, true, true), 1000.0, "missile: 1000 ms");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, true, false), 1500.0, "magic, same target: the setting");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 2500, true, false), 2500.0, "magic, same target: a slower setting is kept");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, true, false), 1500.0, "magic, setting 0 (old file): 1500");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, true, false), 0.0, "magic, setting 0: no delay of its own (the server gates hold the cast)");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, false, false), CombatManager.NoGatesAttackFloorMs, "setting 0 without the server gates: the 250 ms floor");
Check.Eq(CombatManager.AttackIntervalMs(Magic, -1, true, false), 1500.0, "unset: 1500");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, true, true), CombatManager.NewTargetCastFloorMs,
"magic, new target, server gates: the short floor (UseDone + gesture hold the cast)");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, false, true), 1500.0,

View file

@ -21,7 +21,7 @@ namespace RynthCore.RynthAiHostTests.Tests;
internal static class BuffTests
{
private const uint Player = 0x50000B01;
private const uint STypeCreature = 31, STypeItem = 32;
private const uint STypeCreature = 31, STypeItem = 32, STypeLife = 33;
/// <summary>Buff/tier pairs the name tables used to miss (fixed by 940cb21); NameGapsResolve checks them by name.</summary>
private static readonly HashSet<(string Buff, int Tier)> NameGaps = new()
@ -54,6 +54,9 @@ internal static class BuffTests
r.Add("rebuff: our own lower tier under an expiring higher one counts as on", RebuffUnderExpiringHigherTier);
r.Add("rebuff: cast over item-granted buffs (CastBuffsOverItemBuffs on)", RebuffOverItemBuffs);
r.Add("rebuff: CastBuffsOverItemBuffs defaults on, loads, saves, bridges", OverItemBuffsSetting);
r.Add("buff toggles: by default every prot and bane is cast", TogglesDefaultAllOn);
r.Add("buff toggles: an unticked prot or bane is never cast and never holds NeedsAnyBuff", UntickedSkipped);
r.Add("buff toggles: an old profile loads all on; the list saves, copies and bridges", TogglesSetting);
r.Add("buff choice: spell names the tables miss (Bludgeon Bane, Nuhmudira's, T'ing, Celdiseth's)", NameGapsResolve); // was a known failure; fixed by 940cb21
r.Add("buff choice: a mastery whose name has several spell ids", MultiIdMastery); // was a known failure; fixed by 0aedcee
@ -596,6 +599,129 @@ internal static class BuffTests
Check.True(s.CastBuffsOverItemBuffs, "a save with it on turns it on");
}
// ── Prot and bane toggles (Buffing settings, DisabledBuffs) ───────────────
private static readonly MethodInfo CastSelfBuffs =
typeof(BuffManager).GetMethod("CheckAndCastSelfBuffs", BindingFlags.NonPublic | BindingFlags.Instance)!;
/// <summary>Tier 6 Life and Item Magic, in Magic stance, knowing two prots and two banes.</summary>
private static BuffRig ProtBaneRig()
{
FakeHost.Reset();
Know("Fire Protection Self VI", "Cold Protection Self VI", "Flame Bane VI", "Frost Bane VI");
FakeHost.Skills[(Player, STypeLife)] = (300, 2);
FakeHost.Skills[(Player, STypeItem)] = (300, 2);
FakeHost.WeaponCalls = true; // GetCurrentCombatMode answers CombatModeValue
FakeHost.CombatModeValue = CombatMode.Magic;
return new BuffRig();
}
/// <summary>Runs the buff cast loop until it casts nothing, confirming each cast by chat as the
/// server would. Returns the spells cast in order; <paramref name="done"/> = the loop's last
/// answer was "nothing to do" (what ends a batch in the heartbeat).</summary>
private static List<string> CastAll(BuffRig rig, out bool done)
{
var cast = new List<string>();
done = false;
for (int i = 0; i < 20; i++)
{
int before = FakeHost.Casts.Count;
bool acted = (bool)CastSelfBuffs.Invoke(rig.B, null)!;
if (FakeHost.Casts.Count == before) { done = !acted; break; }
string name = NameOf(FakeHost.Casts.Last().SpellId);
cast.Add(name);
rig.B.OnChatWindowText($"You cast {name} on {(name.Contains("Bane") ? "Rune Robe" : "yourself")}", 7);
}
return cast;
}
private static void TogglesDefaultAllOn()
{
var rig = ProtBaneRig();
Check.Eq(rig.S.DisabledBuffs.Count, 0, "a new profile unticks nothing");
foreach (var (buff, _) in BuffManager.ToggleProtections.Concat(BuffManager.ToggleBanes))
Check.True(rig.B.BuildDynamicBuffList().Contains(buff), $"every toggle names a buff in the list: {buff}");
rig.Live(("Strength Self I", 3000)); // a registry read, with none of ours on
Check.True(rig.B.NeedsAnyBuff(), "nothing on: needs buffs");
var cast = CastAll(rig, out bool done);
Check.Eq(string.Join(", ", cast), "Fire Protection Self VI, Cold Protection Self VI, Flame Bane VI, Frost Bane VI", $"all four are cast (last skip: {rig.B.LastBuffSkipReason})");
Check.True(done, "then the loop has nothing left");
}
private static void UntickedSkipped()
{
var rig = ProtBaneRig();
rig.S.SetBuffEnabled("Fire Protection Self", false);
rig.S.SetBuffEnabled("flame bane", false); // names match case-insensitively
Check.False(rig.B.BuildDynamicBuffList().Contains("Fire Protection Self"), "an unticked prot leaves the list");
Check.False(rig.B.BuildDynamicBuffList().Contains("Flame Bane"), "an unticked bane leaves the list");
rig.Live(("Strength Self I", 3000));
var cast = CastAll(rig, out bool done);
Check.Eq(string.Join(", ", cast), "Cold Protection Self VI, Frost Bane VI", "only the ticked ones are cast");
Check.True(done, "the loop ends with the unticked ones still off: the batch can finish");
// A fresh look, the ticked ones on and the unticked ones never cast: nothing is due.
var idle = ProtBaneRig();
idle.S.SetBuffEnabled("Fire Protection Self", false);
idle.S.SetBuffEnabled("Flame Bane", false);
idle.Live(("Cold Protection Self VI", 3000));
idle.B.OnChatWindowText("You cast Frost Bane VI on Rune Robe", 7);
Check.False(idle.B.NeedsAnyBuff(), "unticked and off doesn't hold Buffing");
idle.S.SetBuffEnabled("Fire Protection Self", true);
Check.True(idle.B.NeedsAnyBuff(), "ticked again: Fire Protection is due");
Check.False(idle.S.IsBuffDisabled("Fire Protection Self"), "and leaves the list");
// Force Rebuff recasts everything, still not the unticked ones.
var fr = ProtBaneRig();
fr.S.SetBuffEnabled("Cold Protection Self", false);
fr.S.SetBuffEnabled("Frost Bane", false);
fr.Live(("Strength Self I", 3000));
fr.B.ForceFullRebuff();
cast = CastAll(fr, out done);
Check.Eq(string.Join(", ", cast), "Fire Protection Self VI, Flame Bane VI", "Force Rebuff skips the unticked ones too");
Check.True(done, "and finishes");
Check.False(FakeHost.Casts.Any(c => NameOf(c.SpellId) is "Cold Protection Self VI" or "Frost Bane VI"), "never cast");
}
private static void TogglesSetting()
{
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(old != null && old.DisabledBuffs.Count == 0, "a profile saved before the setting: all on");
var nul = JsonSerializer.Deserialize("{\"DisabledBuffs\":null}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(nul != null && nul.DisabledBuffs.Count == 0, "a null list: all on");
var some = new LegacyUiSettings();
some.SetBuffEnabled("Acid Bane", false);
some.SetBuffEnabled("Blade Protection Self", false);
var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(some, RynthAiJsonContext.Default.LegacyUiSettings),
RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(back != null && back.IsBuffDisabled("Acid Bane") && back.IsBuffDisabled("Blade Protection Self") && back.DisabledBuffs.Count == 2,
"unticked ones are saved and loaded");
// Profile switch/load copies it (CopySettings is the hand-written field list).
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { some, dst });
Check.True(dst.IsBuffDisabled("Acid Bane") && dst.DisabledBuffs.Count == 2, "a profile with unticked ones loads them");
copy.Invoke(null, new object[] { old!, dst });
Check.Eq(dst.DisabledBuffs.Count, 0, "an old profile loads all on");
// Engine Settings face: the payload carries the list; an engine without the field leaves it alone.
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(payload != null && payload.DisabledBuffs == null, "an older engine's payload has no list");
var s = new LegacyUiSettings();
s.SetBuffEnabled("Frost Bane", false);
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(sent?.DisabledBuffs != null && sent.DisabledBuffs.SequenceEqual(new[] { "Frost Bane" }), "sent to the engine face");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.IsBuffDisabled("Frost Bane"), "a save without the list leaves it alone");
dash.ApplySettingsJson("{\"DisabledBuffs\":[]}");
Check.Eq(s.DisabledBuffs.Count, 0, "a save with an empty list ticks everything");
}
private static BuffRig ArmorRig()
{
FakeHost.Reset();

View file

@ -0,0 +1,55 @@
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-08: with Corruption V and VII known, the custom debuff "Corruption" cast V. A typed-in
// debuff was capped by Creature and Life alone; Corruption is Void, so the search started at VI.
internal static class CustomDebuffTests
{
private const uint Player = 0x50000180;
private const uint STypeCreature = 31, STypeLife = 33, STypeVoid = 43;
public static void Register(Runner r)
{
r.Add("custom debuff: a base name casts the highest known level, capped by Void too (Corruption VII, not V)", VoidCap);
}
private static void VoidCap()
{
FakeHost.Reset();
foreach (string n in new[] { "Corruption V", "Corruption VII" })
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeCreature)] = (250, 2); // tier 5 by the thresholds below
FakeHost.Skills[(Player, STypeLife)] = (250, 2);
FakeHost.Skills[(Player, STypeVoid)] = (400, 3); // tier 7
var s = new LegacyUiSettings
{
MinSkillLevelTier1 = 0, MinSkillLevelTier2 = 50, MinSkillLevelTier3 = 100, MinSkillLevelTier4 = 150,
MinSkillLevelTier5 = 200, MinSkillLevelTier6 = 300, MinSkillLevelTier7 = 350, MinSkillLevelTier8 = 10000,
};
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, System.Array.Empty<uint>());
var c = new CombatManager(host, s, cache);
c.SetPlayerId(Player);
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
sm.RefreshKnownSpells();
c.SetSpellManager(sm);
MethodInfo find = typeof(CombatManager).GetMethod("FindBestCustomDebuffWithTier", BindingFlags.NonPublic | BindingFlags.Instance)!;
object[] args = { "Corruption", 0 };
int id = (int)find.Invoke(c, args)!;
Check.Eq(SpellTableStub.GetById(id)?.Name, "Corruption VII", "the highest known level");
Check.Eq((int)args[1], 7, "tier 7");
object[] args5 = { "Corruption V", 0 };
Check.Eq(SpellTableStub.GetById((int)find.Invoke(c, args5)!)?.Name, "Corruption V", "a full name still casts as is");
}
}

View file

@ -27,6 +27,7 @@ internal static class GiveTests
r.Add("give: /ub give with a count hands over that many", UbGiveCount);
r.Add("give: /mt give hands over only the first match", MtGivesFirst);
r.Add("give: /ub givep matches part of the name", UbGivePartial);
r.Add("give: the next give waits until the server took the last (it answers extra gives 'too busy')", WaitsForServer);
}
private sealed class World
@ -118,4 +119,20 @@ internal static class GiveTests
Check.Eq(FakeHost.Gives.Count, 4, "partial: the three Mana Motes and the Lesser Mana Mote");
Check.False(w.GivenItems.Contains(WornMote), "still not the worn one");
}
// 2026-10-08: the queue sent a give every 150 ms; the server takes one at a time and the
// rest came back "too busy", so /ub give handed over one item.
private static void WaitsForServer()
{
var w = new World();
FakeHost.GiveLands = false; // the server hasn't taken the first yet
w.Run("/ub give Mana Mote to Town Crier");
Check.Eq(FakeHost.Gives.Count, 1, "one give, then it waits for the server");
FakeHost.Containers[FakeHost.Gives[0].Item] = Npc; // the server took it
FakeHost.GiveLands = true;
for (int i = 0; i < 20; i++) w.Call("DrainGiveQueue");
Check.Eq(FakeHost.Gives.Count, 3, "then the other two, each after the last landed");
Check.Eq(FakeHost.Gives.Select(g => g.Item).Distinct().Count(), 3, "no item sent twice");
}
}

View file

@ -0,0 +1,161 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-07, Drakkon: two deaths in an acid pool in an hour. The patrol left him in a pool the
// hazard list didn't know, and topping up with healing kits held him there. Now the first
// "You suffer N damage from acid!" stops everything and walks him back out along his footsteps.
internal static class HazardEscapeTests
{
private const uint Player = 0x50000180;
private const uint CellA = 0x63470160, CellB = 0x6347016C; // dungeon cells, one landblock
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("hazard: the hotspot damage line is read (amount, source); other lines are not", Parse);
r.Add("hazard: a hit stops everything and walks back along the footsteps, then hands back", EscapeAlongFootsteps);
r.Add("hazard: hurt again where it stopped - it goes further back", FurtherBack);
r.Add("hazard: macro off - the cell is still learned, nothing moves", MacroOff);
r.Add("hazard: Escape Acid and Lava off - no escape and nothing learned (some walk through acid)", SettingOff);
}
private static void Parse()
{
Check.True(RynthAiPlugin.TryParseHotspotDamage("You suffer 32 damage from acid!", out int a, out string s) && a == 32 && s == "acid", "acid");
Check.True(RynthAiPlugin.TryParseHotspotDamage("You suffer 11 damage from the lava.", out a, out s) && a == 11 && s == "lava", "lava, with 'the'");
Check.False(RynthAiPlugin.TryParseHotspotDamage("You say, \"Malar Zhapaj\"", out _, out _), "speech");
Check.False(RynthAiPlugin.TryParseHotspotDamage("Olthoi Swarm Worker bites you for 20 points of damage!", out _, out _), "a monster's hit");
}
private sealed class Clock { public long Now = 1_000_000; }
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new() { IsMacroRunning = true };
public readonly WorldObjectCache Cache;
public readonly Clock C = new();
public Bot()
{
FakeHost.Reset();
FakeHost.StopCalls = true;
var host = FakeHost.Create(Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(P, dash);
Cache = new WorldObjectCache(host);
typeof(RynthAiPlugin).GetField("_objectCache", Any)!.SetValue(P, Cache);
var clock = C;
RynthAiPlugin.HazardClock = () => clock.Now;
}
/// <summary>Stands at (x, y), lets time pass and records the footstep.</summary>
public void At(uint cell, float x, float y, long ms = 300)
{
FakeHost.PlayerPose = (cell, x, y, -24f);
C.Now += ms;
P.RecordHazardTrail();
}
public bool Hold() => P.HoldForHazardEscape();
public void Hit() => P.NoteHotspotChat("You suffer 32 damage from acid!", 0);
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
}
private static (float X, float Y) Target(Bot b) => (b.Get<float>("_hazardTargetX"), b.Get<float>("_hazardTargetY"));
private static void EscapeAlongFootsteps()
{
var b = new Bot();
// An L: north up x=60 from y=-185 to y=-175, then east to x=66 - into the acid.
for (int i = 0; i <= 10; i++) b.At(CellA, 60f, -185f + i);
for (int i = 1; i <= 6; i++) b.At(CellB, 60f + i, -175f);
b.Hit();
Check.True(b.P.HazardEscaping, "the hit starts the escape");
Check.True(b.Cache.IsHazardCell(CellB), "the cell it was hurt in is a hazard now");
Check.True(b.Hold(), "the escape owns the tick (nothing else runs)");
Check.True(FakeHost.AutoRun, "running");
var path = b.Get<System.Collections.Generic.List<(uint Cell, float X, float Y)>>("_hazardPath");
Check.True(path.Count >= 3, $"a path of footsteps, not one straight line ({path.Count} points)");
Check.True(path.Take(path.Count - 1).Any(p => p.Y == -175f && p.X > 60f), "it first walks back east-west along the way it came");
var t = Target(b);
Check.True(t.X == 60f && t.Y <= -175f, $"and ends back on the north-south leg, outside the hurt cell ({t.X}, {t.Y})");
// Walk the footsteps: each tick at the next one.
foreach (var p in path)
{
FakeHost.PlayerPose = (p.Cell, p.X, p.Y, -24f);
b.C.Now += 300;
Check.True(b.Hold(), "still holding while it walks out");
}
Check.False(FakeHost.AutoRun, "stopped at the target");
b.C.Now += RynthAiPlugin.HazardQuietMs;
Check.False(b.Hold(), "no hit for a while at the target: the tick is handed back");
Check.False(b.P.HazardEscaping, "escape over");
Check.True(FakeHost.Logs.Any(l => l.Contains("Hazard: out of it")), "and it says so");
}
private static void FurtherBack()
{
var b = new Bot();
for (int i = 0; i <= 12; i++) b.At(CellA, 60f, -190f + i);
b.Hit();
var first = Target(b);
FakeHost.PlayerPose = (CellA, first.X, first.Y, -24f);
b.C.Now += 300;
foreach (var _ in Enumerable.Range(0, 20)) { b.Hold(); FakeHost.PlayerPose = (CellA, first.X, first.Y, -24f); }
Check.False(FakeHost.AutoRun, "arrived at the first spot");
b.C.Now += 2500;
b.Hit(); // the pool reaches further back
var second = Target(b);
Check.True(second.Y < first.Y - 1f, $"it goes further back ({first.Y} -> {second.Y})");
Check.True(b.Hold(), "and keeps the tick");
Check.True(FakeHost.AutoRun, "running again");
}
private static void MacroOff()
{
var b = new Bot();
b.S.IsMacroRunning = false;
for (int i = 0; i <= 6; i++) b.At(CellA, 60f, -185f + i);
b.Hit();
Check.True(b.Cache.IsHazardCell(CellA), "the cell is learned");
Check.False(b.P.HazardEscaping, "but nothing moves the character while you play it");
Check.False(b.Hold(), "and the tick is not held");
}
private static void SettingOff()
{
var b = new Bot();
b.S.EscapeHazards = false;
for (int i = 0; i <= 6; i++) b.At(CellA, 60f, -185f + i);
b.Hit();
Check.False(b.P.HazardEscaping, "no escape");
Check.False(b.Cache.IsHazardCell(CellA), "and the cell is not learned (the patrol keeps its way through)");
Check.False(b.Hold(), "the tick is not held");
// Turned off mid-escape: it lets go at once.
b.S.EscapeHazards = true;
b.Hit();
Check.True(b.P.HazardEscaping, "on again: the next hit escapes");
b.S.EscapeHazards = false;
Check.False(b.Hold(), "turned off mid-escape: the tick is handed back");
Check.False(b.P.HazardEscaping, "escape over");
Check.False(new LegacyUiSettings().EscapeHazards == false, "on by default");
}
}

View file

@ -51,6 +51,7 @@ internal static class LootCorpseTests
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse);
r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation);
r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory);
}
// ── World set-up ──────────────────────────────────────────────────────────
@ -486,6 +487,26 @@ internal static class LootCorpseTests
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry");
}
// 2026-10-07: the client takes an item off the corpse list as soon as the move is sent; the
// corpse was closed then, and the character picked the item up after the corpse closed.
private static void CloseWaitsForInventory()
{
var bot = OpenCorpseAndSendPickup(closeSupported: true);
FakeHost.Containers[Gem] = 0x7FFFFFF0; // off the corpse, not in a pack yet
TickFor(bot, 1500);
Check.Eq(FakeHost.Closes.Count, 0, "not closed while the item is on its way");
Check.False(Completed(bot), "not completed either");
FakeHost.Containers[Gem] = Player; // in the main pack
for (int i = 0; i < 200 && FakeHost.Closes.Count == 0; i++)
{
bot.Tick(BotActivity.Looting);
Thread.Sleep(10);
}
Check.Eq(FakeHost.Closes.Count, 1, "closed once the item is in the inventory");
Check.True(FakeHost.Logs.Any(l => l.Contains("pickup confirmed")), "and the pickup confirmed");
}
private static void TickFor(Bot bot, int ms)
{
long end = Environment.TickCount64 + ms;

View file

@ -0,0 +1,56 @@
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-08: RynthAi used an Aligned Mana Stone on a wand. Only the ordinary tapping stones
// (and mana charges) are stones to RynthAi unless a ManaStone consumable rule names one.
internal static class ManaStoneChoiceTests
{
public static void Register(Runner r)
{
r.Add("mana stones: only ordinary stones and charges are used; special stones only when a rule names them", OrdinaryOnly);
r.Add("mana stones: with tapping off, charged stones and Mana Charges still refill worn gear", RefillWithoutTapping);
}
private static void OrdinaryOnly()
{
FakeHost.Reset();
var host = FakeHost.Create();
var cache = new WorldObjectCache(host);
var s = new LegacyUiSettings { EnableManaTapping = true };
var m = new ManaStoneManager(host, s, cache);
WorldObject W(string name) => new(0x60001000, name, AcObjectClass.ManaStone);
foreach (string n in new[] { "Minor Mana Stone", "Lesser Mana Stone", "Moderate Mana Stone", "Mana Stone", "Greater Mana Stone", "Major Mana Stone", "Titan Mana Charge" })
Check.True(m.IsManaStone(W(n)), $"'{n}' is a stone");
foreach (string n in new[] { "Aligned Mana Stone", "Aetheria Mana Stone", "Unstable Mana Stone", "Enchanted Mana Stone", "Adjanite Mana Stone" })
Check.False(m.IsManaStone(W(n)), $"'{n}' is left alone");
s.ConsumableRules.Add(new ConsumableRule { Name = "Aligned Mana Stone", Type = "ManaStone" });
Check.True(m.IsManaStone(W("Aligned Mana Stone")), "a rule naming it opts it in");
Check.False(m.IsManaStone(W("Mana Stone")), "with rules, only the named stones");
}
private static void RefillWithoutTapping()
{
FakeHost.Reset();
var host = FakeHost.Create();
var cache = new WorldObjectCache(host);
var s = new LegacyUiSettings { EnableManaTapping = false };
var m = new ManaStoneManager(host, s, cache);
WorldObject W(string name) => new(0x60001000, name, AcObjectClass.ManaStone);
Check.False(m.IsManaStone(W("Major Mana Stone")), "tapping off: not a stone to loot or drain into");
Check.True(m.IsRefillStone(W("Major Mana Stone")), "but a charged one still refills gear");
Check.True(m.IsRefillStone(W("Titan Mana Charge")), "a bought Mana Charge too");
Check.False(m.IsRefillStone(W("Aligned Mana Stone")), "never a special stone");
s.ConsumableRules.Add(new ConsumableRule { Name = "Aligned Mana Stone", Type = "ManaStone" });
Check.True(m.IsRefillStone(W("Aligned Mana Stone")), "unless a rule names it");
Check.False(m.IsRefillStone(W("Major Mana Stone")), "with rules, only the named stones");
}
}

View file

@ -43,7 +43,7 @@ internal static class MonsterEditorTests
Name = "Olthoi", Category = "Olthoi nest", MatchExpression = "getcharintprop[25]>=200",
Priority = 3, DamageType = "Acid", WeaponId = 0x50001234, Fester = true, Broadside = true,
GravityWell = true, Imperil = true, Yield = true, Vuln = true, UseArc = true, UseRing = true,
UseStreak = true, UseBolt = false, UseBlast = true, ExVuln = "Fire", OffhandId = 2,
UseStreak = true, UseBolt = false, UseBlast = true, UseWall = true, ExVuln = "Fire", OffhandId = 2,
PetDamage = "Cold", CustomDebuffs = "Corrosion Vulnerability Other, Fire Vulnerability Other VII",
},
new PluginRule { Name = "", Category = "Expression only", MatchExpression = "wobjectfindnearestbytemplatetype[1]" },

View file

@ -28,6 +28,7 @@ internal static class VitalsTests
r.Add("vitals: Heal Self known only above the tier Life Magic allows (vitae) is still cast", HealAboveAllowedTier);
r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter);
r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals);
r.Add("vitals: no components for the top level - the next lower level is cast, not the same one again", NoComponentsFallsBack);
// Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md).
r.Add("vitals: a hot reload's login refresh trusts its first read; a real login waits for two equal reads", HotReloadRefresh);
r.Add("vitals: RynthAi tells the engine a reload is unsafe while engaged, under a heal line or casting", ReloadBlockerReport);
@ -69,6 +70,42 @@ internal static class VitalsTests
Check.Eq(FakeHost.Stops, 1, "only once per streak");
}
// 2026-10-08: with no components for the highest Stamina to Mana / Revitalize / Heal the
// character knew, RynthAi kept retrying that one level; it parked the whole family, then
// tried the same level again. Now that level is passed over and the next lower one is cast.
private static void NoComponentsFallsBack()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
var host = FakeHost.Create();
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false };
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 };
var b = new BuffManager(host, s, sm, vitals);
b.SetCharacterSkills(skills);
Check.True(b.CheckVitals(), "10% mana: Stamina to Mana is cast");
int top = FakeHost.Casts[^1].SpellId;
b.OnChatWindowText("You don't have all the components for this spell.", 0);
for (int i = 0; i < 50 && FakeHost.Casts.Count < 2; i++)
{
b.CheckVitals();
System.Threading.Thread.Sleep(20);
}
Check.Eq(FakeHost.Casts.Count, 2, "a second cast goes out");
int next = FakeHost.Casts[^1].SpellId;
Check.True(next != top, $"a different level ({SpellTableStub.GetById(top)?.Name} -> {SpellTableStub.GetById(next)?.Name})");
Check.True(SpellTableStub.GetById(next)?.Family == SpellTableStub.GetById(top)?.Family, "the same spell, one level down");
}
// 2026-10-04, "nav and looting have priority over healing, almost dying in packs": the
// arbiter only saw a heal on ticks where CheckVitals ran (never while looting kept the client
// busy). Health under a line now says "wants vitals" by itself.

View file

@ -0,0 +1,327 @@
using System;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Wall spells (2026-10-08): a monster rule with Wall on casts its element's wall (picked by spell
// category, 229-235) when Wall Range is on and enough monsters are in the wall's path toward the
// target. Priority: Ring, then Wall, then Blast, then the base shape; a wall-only rule casts Bolt
// between walls. A wall is untargeted (ACE flies it along the caster's facing and never turns the
// caster for it), so the bot snaps its heading to the target first and holds the cast until the
// new heading has reached the server; already facing, it casts at once without turning. Walls are
// area casts for the damage bookkeeping. Old profiles and engine payloads load with walls off.
internal static class WallTests
{
private const uint Player = 0x50000D01;
private const int Target = 0x7000A001;
public static void Register(Runner r)
{
r.Add("walls: Ring, then Wall, then Blast, then the base shape; wall-only casts Bolt between walls", ShapePriority);
r.Add("walls: each element's wall by category, the tier limit, none for Nether", WallPerElement);
r.Add("walls: Wall Range off, too few in the path, or no wall known: the rule's other shape", WallOverride);
r.Add("walls: the path is a corridor toward the target, ahead of the caster", WallPathGeometry);
r.Add("walls: far off the target, it turns first and casts after the settle; facing it, no turn", WallFacing);
r.Add("walls: the cast itself waits for the turn, then goes as an area cast", WallCastThroughAttack);
r.Add("walls: UseWall, Wall Range and Min Wall Targets load off / 0 / 3 from old files", OldSettings);
}
private static int Id(string name) => SpellTable.Named(name).Select(r => r.Id).First();
private static string NameOf(int id) => id == 0 ? "(none)" : SpellTable.ById(id)?.Name ?? $"#{id}";
private sealed class Rig
{
public readonly LegacyUiSettings S = new();
public readonly CombatManager C;
public int InPath = 5;
public DateTime Now = new(2026, 10, 8, 12, 0, 0);
public Rig(int tier, params string[] known)
{
FakeHost.Reset();
foreach (string n in known)
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
int T(int k) => k <= tier ? 0 : 10000; // the no-skills stub reads 250 buffed
S.MinSkillLevelTier1 = 0; S.MinSkillLevelTier2 = T(2); S.MinSkillLevelTier3 = T(3); S.MinSkillLevelTier4 = T(4);
S.MinSkillLevelTier5 = T(5); S.MinSkillLevelTier6 = T(6); S.MinSkillLevelTier7 = T(7); S.MinSkillLevelTier8 = T(8);
S.RingRange = 0;
S.WallRange = 20;
S.MinWallTargets = 3;
// The player at the origin, the target 10 yd north; the player faces north.
FakeHost.PlayerPose = (0x0101001Bu, 0f, 0f, 0f);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 10f, 0f);
FakeHost.Names[(uint)Target] = "Drudge Skulker";
FakeHost.HeadingDeg = 0;
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, new[] { (uint)Target });
C = new CombatManager(host, S, cache);
C.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.RefreshKnownSpells();
C.SetSpellManager(sm);
C.WallPathCountOverride = () => InPath;
C.WallClock = () => Now;
}
public (string Spell, string Shape) Cast(string element, MonsterRule rule)
{
int id = C.FindBestShapedSpell(element, rule, out _, out int shape, arcTargetId: Target);
return (NameOf(id), CombatManager.ShapeName(shape));
}
}
private static MonsterRule Wall(bool bolt = true) => new() { Name = "Drudge", UseBolt = bolt, UseWall = true };
private static void ShapePriority()
{
MonsterRule R(bool ring = false, bool bolt = false, bool blast = false, bool wall = false, bool arc = false)
=> new() { UseArc = arc, UseRing = ring, UseBolt = bolt, UseBlast = blast, UseWall = wall };
string N(int s) => CombatManager.ShapeName(s);
int C(MonsterRule r, bool ringDue, bool wallDue, bool blastConditional = false, bool blastFanMet = false)
=> CombatManager.ChooseCastShape(r, blastConditional, blastFanMet, ringDue, wallDue, () => true, out _);
var all = R(ring: true, bolt: true, blast: true, wall: true);
Check.Eq(N(C(all, ringDue: true, wallDue: true, true, true)), "Ring", "all due: Ring");
Check.Eq(N(C(all, ringDue: false, wallDue: true, true, true)), "Wall", "wall and blast due: Wall");
Check.Eq(N(C(all, ringDue: false, wallDue: false, true, true)), "Blast", "only the blast due: Blast");
Check.Eq(N(C(all, ringDue: false, wallDue: false, true, false)), "Bolt", "none due: the base shape (Bolt)");
Check.Eq(N(C(R(wall: true), false, true)), "Wall", "wall-only, due: Wall");
Check.Eq(N(C(R(wall: true), false, false)), "Bolt", "wall-only, not due: Bolt between walls (like ring-only)");
Check.Eq(N(CombatManager.PickBaseShape(R(wall: true))), "Bolt", "wall-only base: Bolt");
Check.Eq(N(CombatManager.PickBaseShape(R(wall: true, ring: true))), "Bolt", "ring + wall only: Bolt");
Check.Eq(CombatManager.PickBaseShape(R()), -1, "nothing on: still no cast");
int asked = 0;
int s = CombatManager.ChooseCastShape(R(arc: true, wall: true), false, false, false, wallDue: true, () => { asked++; return true; }, out bool g);
Check.Eq(N(s), "Wall", "Arc + Wall, wall due: Wall");
Check.True(asked == 0 && !g, "a due wall skips the arc test");
Check.Eq(N(CombatManager.ChooseCastShape(R(arc: true, wall: true), false, false, false, null, out _)), "Arc",
"the old overload (no wall) is unchanged");
}
private static void WallPerElement()
{
var cases = new (string Element, string Wall)[]
{
("Acid", "Blistering Creeper"), ("Bludgeon", "Hammering Crawler"), ("Cold", "Foon-Ki's Glacial Floe"),
("Lightning", "Os' Wall"), ("Fire", "Slithering Flames"), ("Pierce", "Spike Strafe"),
("Blade", "Bed of Blades"), ("Slash", "Bed of Blades"),
};
string[] retail = cases.Select(c => c.Wall).Distinct().ToArray();
foreach (var (element, wall) in cases)
{
var rig = new Rig(7, retail);
Check.Eq(NameOf(rig.C.FindBestWallSpell(element)), wall, $"{element}: {wall} (of all seven known)");
Check.Eq(rig.Cast(element, Wall()), (wall, "Wall"), $"{element}: cast as the Wall shape");
}
var any = new Rig(7, retail);
Check.Eq(any.C.FindBestWallSpell("Nether"), 0, "Nether: no walls");
Check.Eq(any.Cast("Nether", Wall()).Shape, "?", "Nether, nothing else known: no wall cast");
// Retail walls are power 200: level 5 by ACE's server formula, castable from tier 5.
Check.Eq(SpellDatabase.LevelFromPower(SpellTable.ById(Id("Slithering Flames"))!.Power), 5, "Slithering Flames: level 5 (power 200)");
Check.Eq(NameOf(new Rig(5, "Slithering Flames").C.FindBestWallSpell("Fire")), "Slithering Flames", "tier 5: the retail wall");
Check.Eq(new Rig(4, "Slithering Flames").C.FindBestWallSpell("Fire"), 0, "tier 4: too hard (the same limit as Flame Bolt V)");
// Several known in the category: the highest level the tier allows, then the power.
var fire = new Rig(8, "Slithering Flames", "Burning Earth", "Flame Whip");
Check.Eq(NameOf(fire.C.FindBestWallSpell("Fire")), "Burning Earth", "tier 8: Burning Earth (power 400, level 8)");
var fire7 = new Rig(7, "Slithering Flames", "Burning Earth");
Check.Eq(NameOf(fire7.C.FindBestWallSpell("Fire")), "Slithering Flames", "tier 7: not the level-8 one");
Check.Eq(new Rig(7, "Flame Bolt VI").C.FindBestWallSpell("Fire"), 0, "no wall known: none");
// The cold snapshot: never guess.
FakeHost.Reset();
var host = FakeHost.Create(Player);
var c = new CombatManager(host, new LegacyUiSettings(), FakeHost.MakeCache(host, Player, Array.Empty<uint>()));
var sm = new SpellManager(host, new LegacyUiSettings());
sm.InitializeNatively();
c.SetSpellManager(sm);
Check.Eq(c.FindBestWallSpell("Fire"), 0, "spellbook snapshot cold: no wall");
}
private static void WallOverride()
{
string[] book = { "Foon-Ki's Glacial Floe", "Frost Bolt VI", "Frost Blast VI", "Frost Arc VI" };
var rig = new Rig(7, book);
Check.Eq(rig.Cast("Cold", Wall()), ("Foon-Ki's Glacial Floe", "Wall"), "5 in the path (3 needed): the wall");
rig.InPath = 2;
Check.Eq(rig.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "2 in the path: Bolt");
rig.InPath = 5;
rig.S.WallRange = 0;
Check.Eq(rig.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "Wall Range 0: no walls");
rig.S.WallRange = 20;
Check.Eq(rig.Cast("Cold", new MonsterRule { UseArc = true, UseWall = true }).Shape, "Wall", "Arc + Wall, due: Wall");
Check.Eq(rig.Cast("Cold", new MonsterRule { UseBlast = true, UseWall = true, UseBolt = false }).Shape, "Wall", "Blast + Wall, both due: Wall");
rig.InPath = 1;
Check.Eq(rig.Cast("Cold", new MonsterRule { UseBlast = true, UseWall = true, UseBolt = false }), ("Frost Blast VI", "Blast"),
"Blast + Wall, wall not due: Blast");
rig.InPath = 5;
Check.Eq(rig.Cast("Cold", new MonsterRule { UseBolt = true }), ("Frost Bolt VI", "Bolt"), "Wall off in the rule: unchanged");
Check.Eq(rig.C.FindBestShapedSpell("Cold", Wall(), out _, out int probeShape), Id("Frost Bolt VI"),
"an element probe (no target) never picks a wall");
Check.Eq(CombatManager.ShapeName(probeShape), "Bolt", "probe shape Bolt");
var noWall = new Rig(7, "Frost Bolt VI");
Check.Eq(noWall.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "no cold wall known: Bolt (the wall isn't due)");
Check.Eq(CombatManager.ChooseCastShape(new MonsterRule { UseRing = true, UseWall = true }, false, false, true, true, null, out _),
CombatManager.ShapeRing, "ring and wall due: Ring");
}
private static void WallPathGeometry()
{
Check.True(CombatManager.InWallPath(10, 0), "the target itself");
Check.True(CombatManager.InWallPath(15, 10), "15 yd, 10 deg off: 2.6 yd aside");
Check.False(CombatManager.InWallPath(15, 25), "15 yd, 25 deg off: 6.3 yd aside, outside");
Check.True(CombatManager.InWallPath(3, 60), "close, 60 deg off: 2.6 yd aside");
Check.False(CombatManager.InWallPath(5, 120), "behind the caster: no");
Check.True(CombatManager.InWallPath(5, -30), "the other side too");
Check.Near(CombatManager.WallHalfWidth, 4.0, 1e-9, "half width 4 yd (5 projectiles across)");
}
private static void WallFacing()
{
var rig = new Rig(7, "Slithering Flames");
// Facing the target (within 1 degree): cast at once, no turn.
FakeHost.HeadingDeg = 0.5f;
Check.False(rig.C.HoldForWallFacing(Target), "0.5 deg off: cast now");
Check.Eq(FakeHost.Turns, 0, "no turn");
// 90 degrees off: snap to the target, then hold for the settle.
FakeHost.HeadingDeg = 90;
Check.True(rig.C.HoldForWallFacing(Target), "90 deg off: hold");
Check.Eq(FakeHost.Turns, 1, "one heading snap");
Check.Near(FakeHost.HeadingDeg, 0, 0.5, "snapped to the target (north)");
rig.Now = rig.Now.AddMilliseconds(500);
Check.True(rig.C.HoldForWallFacing(Target), "500 ms later: still settling");
rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs);
Check.False(rig.C.HoldForWallFacing(Target), "after the settle: cast");
Check.Eq(FakeHost.Turns, 1, "no second turn");
// Turned, but the target walked far off during the settle: turn again.
FakeHost.HeadingDeg = 180;
Check.True(rig.C.HoldForWallFacing(Target), "180 deg off: hold");
FakeHost.Positions[(uint)Target] = (0x0101001Bu, 10f, 0f, 0f); // now due east
rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1);
Check.True(rig.C.HoldForWallFacing(Target), "settled but 90 deg off now: turn again");
Check.Eq(FakeHost.Turns, 3, "the second snap");
Check.Near(FakeHost.HeadingDeg, 90, 0.5, "to the east");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatCast] wall: facing")), "the turn is logged");
// The drift allowed after the settle shrinks with distance (1.8 m to the side).
Check.Near(CombatManager.WallDriftAllowedDeg(64.0), 1.6, 0.1, "70 yd: about 1.6 degrees");
Check.Near(CombatManager.WallDriftAllowedDeg(9.0), 5.0, 0.01, "10 yd: capped at 5 degrees");
// Always turn: 6 degrees off is a snap too (a wall flies straight).
var small = new Rig(7, "Slithering Flames");
FakeHost.HeadingDeg = 6;
Check.True(small.C.HoldForWallFacing(Target), "6 deg off: turn first");
Check.Eq(FakeHost.Turns, 1, "one snap");
// A target that keeps moving: at most WallFaceMaxSnaps turns, then the wall goes anyway.
var chase = new Rig(7, "Slithering Flames");
FakeHost.HeadingDeg = 180;
Check.True(chase.C.HoldForWallFacing(Target), "first snap");
float east = 10f;
for (int i = 1; i < CombatManager.WallFaceMaxSnaps; i++)
{
FakeHost.HeadingDeg = 180; // keeps facing away (the target ran round behind)
chase.Now = chase.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1);
Check.True(chase.C.HoldForWallFacing(Target), $"snap {i + 1}");
}
FakeHost.HeadingDeg = 180;
chase.Now = chase.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1);
Check.False(chase.C.HoldForWallFacing(Target), "after the last snap: cast anyway");
_ = east;
}
private static void WallCastThroughAttack()
{
var rig = new Rig(7, "Slithering Flames", "Flame Bolt VI");
rig.S.MonsterRules.Clear();
rig.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true });
rig.C.activeTargetId = Target;
var target = new WorldObject(Target, "Drudge Skulker");
MethodInfo attack = typeof(CombatManager).GetMethod("AttackWithMagic", BindingFlags.NonPublic | BindingFlags.Instance)!;
FieldInfo held = typeof(CombatManager).GetField("_wallFaceHeld", BindingFlags.NonPublic | BindingFlags.Instance)!;
FieldInfo tier = typeof(CombatManager).GetField("_lastCastTier", BindingFlags.NonPublic | BindingFlags.Instance)!;
FieldInfo area = typeof(CombatManager).GetField("_lastCastWasRing", BindingFlags.NonPublic | BindingFlags.Instance)!;
FieldInfo resolving = typeof(CombatManager).GetField("_awaitingCastResolution", BindingFlags.NonPublic | BindingFlags.Instance)!;
FakeHost.HeadingDeg = 270; // facing west, the target is north
attack.Invoke(rig.C, new object[] { target });
Check.Eq(FakeHost.Casts.Count, 0, "far off: no cast yet");
Check.True((bool)held.GetValue(rig.C)!, "the wall is held for its turn");
Check.Eq(FakeHost.Turns, 1, "turned first");
rig.Now = rig.Now.AddMilliseconds(300);
attack.Invoke(rig.C, new object[] { target });
Check.Eq(FakeHost.Casts.Count, 0, "300 ms later: still no cast (the server catching up)");
rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs);
attack.Invoke(rig.C, new object[] { target });
Check.Eq(FakeHost.Casts.Count, 1, "after the settle: cast");
Check.Eq(NameOf(FakeHost.Casts[0].SpellId), "Slithering Flames", "the wall");
Check.False((bool)held.GetValue(rig.C)!, "not held");
Check.Eq(FakeHost.Turns, 1, "no turn with the cast");
Check.True((bool)area.GetValue(rig.C)!, "an area cast for the bookkeeping (like a ring)");
Check.Eq((int)tier.GetValue(rig.C)!, -5, "filed with the area tiers: level 5, negative");
// Already facing: straight to the cast, no turn. (A fresh rig: no cast resolving.)
var facing = new Rig(7, "Slithering Flames", "Flame Bolt VI");
facing.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true });
facing.C.activeTargetId = Target;
FakeHost.HeadingDeg = 0;
attack.Invoke(facing.C, new object[] { target });
Check.Eq(FakeHost.Casts.Count, 1, "facing: cast at once");
Check.Eq(NameOf(FakeHost.Casts[0].SpellId), "Slithering Flames", "the wall");
Check.Eq(FakeHost.Turns, 0, "no turn");
Check.True((bool)resolving.GetValue(facing.C)!, "the cast arms the cadence guard (no turn until it resolves)");
// A bolt (wall not due) is single-target as before.
var bolt = new Rig(7, "Slithering Flames", "Flame Bolt VI");
bolt.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true });
bolt.C.activeTargetId = Target;
bolt.InPath = 1;
FakeHost.HeadingDeg = 270;
attack.Invoke(bolt.C, new object[] { target });
Check.Eq(NameOf(FakeHost.Casts.Single().SpellId), "Flame Bolt VI", "wall not due: the bolt, no turn needed");
Check.Eq(FakeHost.Turns, 0, "targeted casts don't turn (the server does)");
Check.False((bool)area.GetValue(bolt.C)!, "single-target");
Check.Eq((int)tier.GetValue(bolt.C)!, 6, "positive tier");
}
private static void OldSettings()
{
var old = JsonSerializer.Deserialize("{\"MinRingTargets\":4,\"BlastRange\":10}", RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.Eq(old.WallRange, 0, "old profile: Wall Range off");
Check.Eq(old.MinWallTargets, 3, "old profile: Min Wall Targets 3");
var fresh = new LegacyUiSettings();
Check.True(fresh.WallRange == 0 && fresh.MinWallTargets == 3, "new settings: off / 3");
var bridge = JsonSerializer.Deserialize("{\"MinRingTargets\":4}", RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(bridge.WallRange == null && bridge.MinWallTargets == null, "older engine's settings: no wall values (left alone)");
var newer = JsonSerializer.Deserialize("{\"WallRange\":15,\"MinWallTargets\":4}", RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(newer.WallRange == 15 && newer.MinWallTargets == 4, "an engine with walls: carried");
const string oldRules = "[{\"Name\":\"Default\",\"Priority\":1,\"UseBolt\":true},{\"Name\":\"Drudge\",\"UseRing\":true,\"UseBlast\":true}]";
var rules = JsonSerializer.Deserialize(oldRules, RynthAiJsonContext.Default.MonsterRuleList)!;
Check.False(rules[0].UseWall || rules[1].UseWall, "old monster file: Wall off");
rules[1].UseWall = true;
string json = JsonSerializer.Serialize(rules, RynthAiJsonContext.Default.MonsterRuleList);
Check.True(json.Contains("\"UseWall\": true"), "saved with UseWall");
var back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MonsterRuleList)!;
Check.True(back[1].UseWall && !back[0].UseWall, "round trip keeps it");
var payload = JsonSerializer.Deserialize("{\"rules\":[{\"Name\":\"Mite\",\"UseWall\":true}]}", RynthAiJsonContext.Default.MonstersBridgePayload)!;
Check.True(payload.Rules[0].UseWall, "the engine's rules JSON carries UseWall");
}
}

View file

@ -106,6 +106,13 @@ internal static class NavBake
/// </summary>
public static float AgentMaxClimb = 1.0f;
/// <summary>
/// How far a wall outline may be simplified. 1.3 m was fine inside the old 2 m agent margin;
/// with a body-sized radius (0.6 m: gaps under about 4 m no longer close, Shoushi 2026-10-08)
/// a 1.3 m simplification could cut a corner through the margin, so it follows the radius.
/// </summary>
internal static float EdgeMaxError(float radius) => Math.Min(1.3f, radius + 0.15f);
private static RcNavMeshBuildSettings Settings(float radius, bool tiled, float cellSize)
{
float slopeDeg = (float)(Math.Acos(TerrainSampler.FloorZ) * 180.0 / Math.PI);
@ -115,7 +122,7 @@ internal static class NavBake
agentHeight = 2.0f, agentRadius = radius, agentMaxClimb = AgentMaxClimb, agentMaxSlope = slopeDeg,
minRegionSize = 8, mergedRegionSize = 20, partitioning = (int)RcPartition.WATERSHED,
filterLowHangingObstacles = true, filterLedgeSpans = true, filterWalkableLowHeightSpans = true,
edgeMaxLen = 12f, edgeMaxError = 1.3f, vertsPerPoly = VertsPerPoly, detailSampleDist = 6f, detailSampleMaxError = 1f,
edgeMaxLen = 12f, edgeMaxError = EdgeMaxError(radius), vertsPerPoly = VertsPerPoly, detailSampleDist = 6f, detailSampleMaxError = 1f,
// The solo bake reads the intermediate results (the .obj export); the tiled bake only
// needs the finished navmesh, and keeping every tile's heightfields cost 1.5-2.7 GB a chunk.
tiled = tiled, tileSize = tiled ? TiledTileSize : 0, keepInterResults = !tiled, buildAll = true,

View file

@ -39,6 +39,10 @@ internal static partial class Program
Run(nameof(RecallListColdSpellbook), RecallListColdSpellbook);
Run(nameof(RecallMemoryRoundTrip), RecallMemoryRoundTrip);
Run(nameof(RecallMessages), RecallMessages);
Run(nameof(HandCastOnALifestone), HandCastOnALifestone);
Run(nameof(HandCastPortalTie), HandCastPortalTie);
Run(nameof(RecallNotLinked), RecallNotLinked);
Run(nameof(DungeonLandblocksFromTheAtlas), DungeonLandblocksFromTheAtlas);
Run(nameof(AtlasSearchAndBestMatch), AtlasSearchAndBestMatch);
Run(nameof(ArrowSingleTarget), ArrowSingleTarget);
Run(nameof(ArrowAlongRoute), ArrowAlongRoute);
@ -249,6 +253,128 @@ internal static partial class Program
Check(RecallMemory.Classify("", "Tom") == RecallEvent.None, "empty");
Check(RecallMemory.SlotFor(RecallEvent.RecallingHome, out var slot) && slot == RecallSlot.House, "house slot");
Check(!RecallMemory.SlotFor(RecallEvent.RecallingMarketplace, out _), "marketplace has no slot");
// Your spell words (Spellcasting, 17) start a hand cast; the same words typed in local chat don't.
Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom", RecallMemory.ChatTypeSpellcasting) == RecallEvent.OwnSpellWords, "own spell words");
Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom", 2) == RecallEvent.None, "typed in local chat");
Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom") == RecallEvent.None, "chat type unknown");
Check(RecallMemory.Classify("Ann says, \"Zojak Ququ\"", "Tom", RecallMemory.ChatTypeSpellcasting) == RecallEvent.None, "someone else casting");
}
// ── A recall cast by hand: which one, from where it landed ───────────────
private const string Me = "Aelrynth|Tom";
private static RecallSpot At(double ns, double ew, string label = "") => new() { OnMap = true, Ns = ns, Ew = ew, Label = label };
private static void HandCastOnALifestone()
{
var mem = new RecallMemory();
var known = new HashSet<int> { RecallPlanner.LifestoneRecall, RecallPlanner.PrimaryPortalTieRecall };
var k = RecallPlanner.GuessHandCast(At(42.1, 33.6), atLifestone: true, known, mem, Me, 30, out var slot, out _);
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Lifestone, "on a lifestone: Lifestone Recall");
mem.Set(Me, RecallSlot.Lifestone, At(42.1, 33.6));
k = RecallPlanner.GuessHandCast(At(42.11, 33.6), true, known, mem, Me, 30, out _, out _);
Check(k == RecallPlanner.HandCast.Nothing, "the same lifestone again: nothing new");
k = RecallPlanner.GuessHandCast(At(-30.0, 70.0), true, known, mem, Me, 30, out slot, out _);
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Lifestone, "tied somewhere else since: learned again");
k = RecallPlanner.GuessHandCast(At(42.1, 33.6), true, new HashSet<int> { RecallPlanner.PrimaryPortalTieRecall }, new RecallMemory(), Me, 30, out _, out _);
Check(k == RecallPlanner.HandCast.Nothing, "no Lifestone Recall in the spellbook: not it");
// On the @lifestone lifestone with Recall the Sanctuary known: either spell, can't tell.
var mem2 = new RecallMemory();
mem2.Set(Me, RecallSlot.Sanctuary, At(42.1, 33.6));
var known2 = new HashSet<int> { RecallPlanner.LifestoneRecall, RecallPlanner.RecallTheSanctuary };
k = RecallPlanner.GuessHandCast(At(42.1, 33.6), true, known2, mem2, Me, 30, out _, out _);
Check(k == RecallPlanner.HandCast.Nothing, "Recall the Sanctuary could land there too");
k = RecallPlanner.GuessHandCast(At(10, 10), true, null, mem2, Me, 30, out _, out var why);
Check(k == RecallPlanner.HandCast.Nothing && why.Contains("spellbook"), "a cold spellbook teaches nothing");
}
private static void HandCastPortalTie()
{
var oneTie = new HashSet<int> { RecallPlanner.SecondaryPortalTieRecall };
var k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, oneTie, new RecallMemory(), Me, 30, out var slot, out _);
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie2, "the only tie recall known");
var both = new HashSet<int> { RecallPlanner.PrimaryPortalTieRecall, RecallPlanner.SecondaryPortalTieRecall };
k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, both, new RecallMemory(), Me, 30, out _, out _);
Check(k == RecallPlanner.HandCast.AskTie, "both tie recalls known: ask which");
var mem = new RecallMemory();
mem.Set(Me, RecallSlot.Tie1, At(-33.5, 72.8));
k = RecallPlanner.GuessHandCast(At(-33.51, 72.8), false, both, mem, Me, 30, out slot, out _);
Check(k == RecallPlanner.HandCast.Nothing && slot == RecallSlot.Tie1, "a known tie's landing: nothing new");
// Portal Recall: lands where the last portal went (known: nothing; unknown: ask).
var withPortalRecall = new HashSet<int> { RecallPlanner.PrimaryPortalTieRecall, RecallPlanner.PortalRecall };
var mem2 = new RecallMemory();
mem2.Set(Me, RecallSlot.LastPortal, At(12, 34));
k = RecallPlanner.GuessHandCast(At(12, 34), false, withPortalRecall, mem2, Me, 30, out _, out _);
Check(k == RecallPlanner.HandCast.Nothing, "the last portal's landing: Portal Recall");
k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, withPortalRecall, mem2, Me, 30, out slot, out _);
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie1, "elsewhere, last portal known: the one tie");
k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, withPortalRecall, new RecallMemory(), Me, 30, out _, out _);
Check(k == RecallPlanner.HandCast.AskTie, "last portal unknown: could be Portal Recall, ask");
k = RecallPlanner.GuessHandCast(At(1, 1), false, new HashSet<int> { RecallPlanner.LifestoneRecall }, new RecallMemory(), Me, 30, out _, out _);
Check(k == RecallPlanner.HandCast.Nothing, "off a lifestone with no tie recall: not one RynthNav knows");
// A dungeon landing (off the map) is learned too, and matched by its label.
var dungeon = new RecallSpot { OnMap = false, Label = "a dungeon (landblock 6145)" };
k = RecallPlanner.GuessHandCast(dungeon, false, oneTie, new RecallMemory(), Me, 30, out slot, out _);
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie2, "a tie into a dungeon");
var mem3 = new RecallMemory();
mem3.Set(Me, RecallSlot.Tie2, new RecallSpot { OnMap = false, Label = "a dungeon (landblock 6145)" });
k = RecallPlanner.GuessHandCast(dungeon, false, oneTie, mem3, Me, 30, out _, out _);
Check(k == RecallPlanner.HandCast.Nothing, "the same dungeon again: nothing new");
// Once learned, the planner uses it.
var plannerMem = new RecallMemory();
plannerMem.Set(Me, RecallSlot.Tie2, At(-33.5, 72.8, "Shoushi"));
var list = RecallPlanner.Build(Atlas.Empty, oneTie, plannerMem, Me, new List<string>());
Check(list.Exists(o => o.SpellId == RecallPlanner.SecondaryPortalTieRecall && Math.Abs(o.Ns + 33.5) < 1e-9), "the learned tie is planned");
}
private static void DungeonLandblocksFromTheAtlas()
{
// A dungeon landblock's tile is its surface (dungeon cells aren't baked): the walk must
// know it's in one. Dungeon places and dungeon portal destinations count; a landblock
// with places on the map (a town, its cellars) never does.
Atlas atlas = Atlas.Parse(@"{""locations"":[
{""name"":""Surface"",""type"":""Portal"",""cell"":""000102C8"",""place"":""dungeon"",""dest"":{""cell"":""26E5001D"",""place"":""outdoor"",""ns"":81.68,""ew"":-71.16}},
{""name"":""Holtburg Dungeon Portal"",""type"":""Portal"",""cell"":""A9B40021"",""place"":""outdoor"",""ns"":42.0,""ew"":33.0,""dest"":{""cell"":""01F60230"",""place"":""dungeon""}},
{""name"":""Shoushi"",""type"":""Town"",""cell"":""DA55001D"",""place"":""outdoor"",""ns"":-33.5,""ew"":72.8},
{""name"":""Cellar Vendor"",""type"":""Vendor"",""cell"":""DA550105"",""place"":""dungeon""},
{""name"":""Odd"",""type"":""Landmark"",""cell"":""zz"",""place"":""dungeon""}
]}");
HashSet<uint> d = atlas.DungeonLandblocks();
Check(d.Contains(0x0001), "a dungeon place's landblock");
Check(d.Contains(0x01F6), "a portal's dungeon destination");
Check(!d.Contains(0x26E5) && !d.Contains(0xA9B4), "outdoor landblocks aren't dungeons");
Check(!d.Contains(0xDA55), "a town landblock with a dungeon cell isn't one");
Check(d.Count == 2, "nothing else (a bad cell is skipped)");
}
private static void RecallNotLinked()
{
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkLifestone, 0) == RecallSlot.Lifestone, "no lifestone tie: Lifestone Recall");
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.PrimaryPortalTieRecall) == RecallSlot.Tie1, "no primary tie");
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.SecondaryPortalTieRecall) == RecallSlot.Tie2, "no secondary tie");
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.PortalRecall) == RecallSlot.LastPortal, "no last portal");
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, 0) == null, "a portal recall cast by hand: can't tell which");
Check(RecallPlanner.SlotUnlinked(0x0402, RecallPlanner.LifestoneRecall) == null, "a fizzle isn't a missing tie");
Check(RecallPlanner.SpellFor(RecallSlot.Tie2) == RecallPlanner.SecondaryPortalTieRecall && RecallPlanner.SpellFor(RecallSlot.House) == 0, "slot spells");
var mem = new RecallMemory();
mem.Set(Me, RecallSlot.Lifestone, At(42.1, 33.6));
int v = mem.Version;
mem.Clear(Me, RecallSlot.Lifestone);
Check(mem.Get(Me, RecallSlot.Lifestone) == null && mem.Version > v, "forgotten (and saved)");
var notes = new List<string>();
RecallPlanner.Build(Atlas.Empty, new HashSet<int> { RecallPlanner.LifestoneRecall }, mem, Me, notes);
Check(notes.Exists(n => n.Contains("Lifestone Recall") && n.Contains("cast Lifestone Recall once")), "the note says how to teach it");
}
// ── Atlas ────────────────────────────────────────────────────────────────