RynthSuite as of 2026-10-05 evening (internal a078b8e): release 2026.10.5.20 - healing delay fixes, stuck-cast safeguards, buffs over items, slayers recognised and chosen first, recover my corpse, /ub give and /mt give, Mana Tap skips wands, dungeon floor-plan bake, heal latency log

This commit is contained in:
Tom Bohar 2026-10-05 14:59:43 -04:00
commit 6847868401
60 changed files with 6361 additions and 769 deletions

View file

@ -11,4 +11,14 @@
<ItemGroup>
<IlcArg Include="--runtimeopt:GCSegmentSize=800000" />
</ItemGroup>
<!--
Plugin manifest fields shared by every RynthSuite plugin (Directory.Build.targets embeds the
manifest; each csproj sets its own RynthPluginMinEngineApi and description).
-->
<PropertyGroup>
<RynthPluginAuthor>RynthSuite</RynthPluginAuthor>
<RynthPluginHomepage>https://aelrynth.com/rynth.html</RynthPluginHomepage>
<RynthPluginLicense>MIT</RynthPluginLicense>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,12 @@
<Project>
<!--
Plugin manifests (RynthCore SDK): each plugin's csproj sets RynthPluginMinEngineApi (and any
RynthPluginDependency items); the SDK's targets write the manifest JSON from the csproj, compile
in RynthPluginInfo, and embed the JSON in the DLL. The plugins reference the SDK by
ProjectReference, so its build\ targets are imported here rather than by NuGet.
-->
<PropertyGroup>
<_RynthCoreSdkTargets>$(MSBuildThisFileDirectory)..\..\RynthCore\src\RynthCore.PluginSdk\build\RynthCore.PluginSdk.targets</_RynthCoreSdkTargets>
</PropertyGroup>
<Import Project="$(_RynthCoreSdkTargets)" Condition="Exists('$(_RynthCoreSdkTargets)')" />
</Project>

View file

@ -149,6 +149,22 @@ internal sealed class ActivityArbiter
_ => "Default",
};
/// <summary>
/// What a display shows for the bot's activity (the RynthAi dashboard and the phone, through
/// the snapshot's "botAction"; RynthNet's status "action"). The same as the BotAction control
/// string except for "Buffing", which is one slot for every vitals and buff job: there it is
/// <paramref name="buffingLabel"/> (Healing, Restoring mana, Restoring stamina or Buffing).
/// Healing showed as "Buffing" on both (2026-10-05). The control string itself never changes:
/// CombatManager's canRun and CorpseOpenController compare against "Buffing".
/// </summary>
public static string DisplayLabel(string? botAction, string? buffingLabel)
{
string action = string.IsNullOrEmpty(botAction) ? "Default" : botAction;
if (string.Equals(action, "Buffing", OIC) && !string.IsNullOrEmpty(buffingLabel))
return buffingLabel;
return action;
}
/// <summary>
/// STEP 1 shadow mode. Compute the would-be decision and log it whenever
/// it (or the legacy BotAction it's being compared against) changes.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,255 @@
using System;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Bookkeeping for the casts BuffManager sends (buffs and vitals): when each one went out,
/// when its incantation ("You say, ...") arrived, and whether the server has finished it.
///
/// Why (Drakkon on DreamWeave, 2026-10-05, ops\overnight\2026-10-05-stuck-cast.md):
/// * The give-up timers ran from the SEND. A healthy DreamWeave vital takes 2.2-2.5 s from
/// its incantation to its result, and the incantation lags the send by up to 1.2 s, so a
/// cast the server was still finishing was given up at 2.5 s and the next one drew
/// "You're too busy!". Now the give-up runs from the incantation when one arrives
/// (<see cref="GiveUpAt"/>), capped, and from the send when none does.
/// * "Has the server finished?" cleared on ANY UseDone, including the 0x1D refusal of the
/// next cast. Now only a completion that belongs to the outstanding cast counts: its own
/// result line, or a UseDone with no error after its incantation (<see cref="AwaitingServer"/>).
/// A refusal is a refusal, not "done".
/// * A cast the server held open (incantation, no result) was only released when someone
/// moved the character. <see cref="Refusal"/> says when to send one movement nudge.
/// * Each cast's time from incantation to result is logged ([CastTime]), so a slow or held
/// cast shows in the log.
///
/// Pure bookkeeping: it never calls the game. The clock is injectable for the tests.
/// </summary>
internal sealed class CastTracker
{
internal sealed class Cast
{
public int SpellId;
public string Name = "";
public DateTime SentAt;
public DateTime IncantAt = DateTime.MinValue;
public int SeqAtSend;
public int SeqAtIncant;
public int SeqAtRefusal;
public bool Refused; // AC answered this cast with "You're too busy!"
public bool Done; // its result line, or UseDone(0) after its incantation
public bool Nudged; // the one movement nudge for this held cast has gone out
public bool StuckLogged;
public bool HasIncantation => IncantAt != DateTime.MinValue;
}
/// <summary>Incantation to result, at most. Healthy DreamWeave vitals: 2.21-2.52 s.</summary>
public const double IncantToResultMs = 3000;
/// <summary>Never wait longer than this after the send, whatever the incantation said.</summary>
public const double GiveUpCapMs = 6000;
/// <summary>An incantation with no result for this long is a held cast.</summary>
public const double HeldAfterIncantMs = 6000;
/// <summary>
/// The same, when the held cast is a heal or health is under a heal line (2026-10-05: Drakkon
/// died 4 s after a Heal Self the server held open). Past the healthy 2.2-2.5 s from
/// incantation to result, so a cast still finishing normally is not nudged.
/// </summary>
public const double UrgentHeldAfterIncantMs = 2800;
/// <summary>An incantation this long after the send isn't credited to it.</summary>
private const double IncantWindowMs = 15000;
private readonly Action<string> _log;
public CastTracker(Action<string> log) => _log = log;
public Func<DateTime> Clock = () => DateTime.Now;
public DateTime Now => Clock();
/// <summary>The last cast sent.</summary>
public Cast? Current { get; private set; }
/// <summary>The cast whose incantation arrived and whose result hasn't (may be older than Current).</summary>
public Cast? Open { get; private set; }
/// <summary>When to stop waiting for <paramref name="c"/>: <paramref name="fallbackMs"/> after
/// the send, or later when its incantation came late (incantation + IncantToResultMs), but
/// never past max(fallbackMs, GiveUpCapMs) after the send.</summary>
public static DateTime GiveUpAt(Cast c, double fallbackMs)
{
DateTime basis = c.SentAt.AddMilliseconds(fallbackMs);
if (!c.HasIncantation) return basis;
DateTime byIncant = c.IncantAt.AddMilliseconds(IncantToResultMs);
DateTime cap = c.SentAt.AddMilliseconds(Math.Max(fallbackMs, GiveUpCapMs));
DateTime d = byIncant > basis ? byIncant : basis;
return d < cap ? d : cap;
}
/// <summary>True when the pending cast <paramref name="spellId"/> is past its give-up time.
/// Null when the tracker doesn't hold that cast (the caller uses its old timer).</summary>
public bool? GiveUpReached(int spellId, double fallbackMs)
{
Cast? c = Current;
if (c == null || c.SpellId != spellId) return null;
return Now >= GiveUpAt(c, fallbackMs);
}
public void Sent(int spellId, string name, int useDoneSeq)
{
DateTime now = Now;
// An earlier cast that is still held open stays Open; one with no incantation is simply replaced.
Current = new Cast { SpellId = spellId, Name = name, SentAt = now, SeqAtSend = useDoneSeq };
}
/// <summary>"You say, ..." arrived. Credited to the last cast sent when it has none yet.
/// A new incantation also means the server let go of any older open cast.</summary>
public Cast? Incantation(int useDoneSeq)
{
DateTime now = Now;
Cast? c = Current;
if (c == null || c.HasIncantation || c.Refused || c.Done || (now - c.SentAt).TotalMilliseconds > IncantWindowMs)
return null;
if (Open != null && Open != c && !Open.Done)
{
_log($"[CastTime] '{Open.Name}': no result {Secs(now - Open.IncantAt)} after its incantation; the server started the next cast ('{c.Name}'), so it is over.");
Open.Done = true;
}
c.IncantAt = now;
c.SeqAtIncant = useDoneSeq;
Open = c;
_log($"[CastTime] '{c.Name}': incantation {Ms(now - c.SentAt)} after the send.");
return c;
}
/// <summary>A result line ("You cast X ...", a fizzle, a hard refusal). <paramref name="castText"/>
/// is what followed "You cast " (null for lines that don't name the spell). <paramref name="atStart"/>:
/// an unnamed refusal the server gives before the cast starts (no components, not enough mana),
/// which belongs to the last cast sent. Returns the cast it belongs to, or null.</summary>
public Cast? Result(string? castText, string kind, bool atStart = false)
{
Cast? c = null;
bool currentLive = Current != null && !Current.Done && !Current.Refused;
bool openLive = Open != null && !Open.Done;
if (!string.IsNullOrEmpty(castText))
{
if (Current != null && !Current.Done && Matches(castText, Current.Name)) c = Current;
else if (openLive && Matches(castText, Open!.Name)) c = Open;
}
else if (atStart)
c = currentLive && !Current!.HasIncantation ? Current : (openLive ? Open : null);
else
// Unnamed, after the windup (a fizzle): the cast the server is running, else the last one sent.
c = openLive ? Open : (currentLive ? Current : null);
if (c == null) return null;
Close(c, kind);
return c;
}
private static bool Matches(string castText, string name) =>
name.Length > 0 && castText.StartsWith(name, StringComparison.OrdinalIgnoreCase);
/// <summary>The cast's own enchantment landed (self-buff confirmed by event or registry).</summary>
public void Confirmed(int spellId, string kind)
{
if (Current != null && !Current.Done && Current.SpellId == spellId) Close(Current, kind);
else if (Open != null && !Open.Done && Open.SpellId == spellId) Close(Open, kind);
}
private void Close(Cast c, string kind)
{
c.Done = true;
DateTime now = Now;
string nudged = c.Nudged ? " (after the movement nudge)" : "";
if (c.HasIncantation)
_log($"[CastTime] '{c.Name}': {kind} {Secs(now - c.IncantAt)} after its incantation (send to incantation {Ms(c.IncantAt - c.SentAt)}){nudged}.");
else
_log($"[CastTime] '{c.Name}': {kind} {Secs(now - c.SentAt)} after the send (no incantation seen){nudged}.");
if (Open == c) Open = null;
}
/// <summary>The last UseDone the engine saw. A UseDone with no error after a cast's incantation
/// is that cast finishing; anything else (0x1D too busy, a UseDone before the incantation) is not.</summary>
public void ObserveUseDone(int lastSeq, uint lastError)
{
if (lastError != 0) return;
foreach (Cast? c in new[] { Open, Current })
{
if (c == null || c.Done || !c.HasIncantation || lastSeq <= c.SeqAtIncant) continue;
Close(c, $"UseDone #{lastSeq} (no error)");
}
}
/// <summary>
/// True while the server hasn't finished the last cast sent. Clears on that cast's result
/// line, on a UseDone(0) after its incantation, after a refusal once a UseDone(0) shows the
/// server free again, or at its give-up time (<paramref name="fallbackMs"/> from the send,
/// later with a late incantation). <paramref name="hasLast"/> false (an engine before v70)
/// keeps the old rule: any new UseDone clears it.
/// </summary>
public bool AwaitingServer(double fallbackMs, int useDoneSeq, bool hasLast, int lastSeq, uint lastError)
{
Cast? c = Current;
if (c == null || c.Done) return false;
if (Now >= GiveUpAt(c, fallbackMs)) return false;
if (!hasLast) return useDoneSeq == c.SeqAtSend;
ObserveUseDone(lastSeq, lastError);
if (c.Done) return false;
if (c.Refused && lastError == 0 && lastSeq > c.SeqAtRefusal) return false;
return true;
}
/// <summary>
/// "You're too busy!" arrived. The last cast sent, if it had no incantation yet, was refused.
/// Returns true exactly once per held cast: an incantation more than HeldAfterIncantMs ago,
/// no result, and AC still refusing casts. The caller sends one movement nudge.
/// </summary>
public bool Refusal(int useDoneSeq, double heldAfterMs = HeldAfterIncantMs)
{
Cast? c = Current;
if (c != null && !c.HasIncantation && !c.Done && !c.Refused)
{
c.Refused = true;
c.SeqAtRefusal = useDoneSeq;
}
return TakeNudge(heldAfterMs);
}
/// <summary>
/// True exactly once per held cast: open (incantation, no result) for more than
/// <paramref name="heldAfterMs"/> and not nudged yet. Marks it nudged. The refusal path uses
/// it with HeldAfterIncantMs; a heal (or health under a heal line) polls it each tick with
/// UrgentHeldAfterIncantMs, without waiting for a refusal.
/// </summary>
public bool TakeNudge(double heldAfterMs)
{
Cast? held = Open;
if (held == null || held.Done || held.Nudged || !held.HasIncantation) return false;
if ((Now - held.IncantAt).TotalMilliseconds <= heldAfterMs) return false;
held.Nudged = true;
return true;
}
/// <summary>The cast the server holds open (incantation, no result), or null.</summary>
public Cast? Held => Open is { Done: false } o && o.HasIncantation ? o : null;
/// <summary>One log line the first time a cast has been open past HeldAfterIncantMs (polled each tick).</summary>
public void Poll()
{
Cast? held = Open;
if (held == null || held.Done || held.StuckLogged) return;
if ((Now - held.IncantAt).TotalMilliseconds <= HeldAfterIncantMs) return;
held.StuckLogged = true;
_log($"[CastTime] '{held.Name}': HELD - incantation {Secs(Now - held.IncantAt)} ago and no result yet (the server is holding the cast open).");
}
/// <summary>Seconds a cast has been held open (incantation, no result), or 0.</summary>
public double HeldSeconds
{
get
{
Cast? held = Open;
return held == null || held.Done ? 0 : (Now - held.IncantAt).TotalSeconds;
}
}
private static string Secs(TimeSpan t) => $"{t.TotalSeconds:0.00} s";
private static string Ms(TimeSpan t) => $"{t.TotalMilliseconds:0} ms";
}

View file

@ -3348,8 +3348,9 @@ public partial class CombatManager : IDisposable
/// <summary>
/// The weapon to fight <paramref name="target"/> with (0 = none), and the element in
/// <paramref name="desired"/>. See WeaponPlanner for the order: the Damage tab's weapon
/// (listed only), the Monsters rule's damage type, the weakness (weakest element a listed
/// <paramref name="desired"/>. See WeaponPlanner for the order: this monster's Damage tab
/// weapon (listed only), a slayer of the monster, the Damage tab DEFAULT row's weapon, the
/// Monsters rule's damage type, the weakness (weakest element a listed
/// weapon of the main kind has), else the weapon in hand, the learned best, the first.
/// Casters are skipped when the character has no War/Void Magic (IsUsableCombatWeapon).
/// </summary>
@ -3414,7 +3415,13 @@ public partial class CombatManager : IDisposable
var weak = WeaknessFor(target);
listed = ApplyAmmo(listed, ruleElement, weak);
// Slayers (PropertyInt 166 = the monster's PropertyInt 2) only when a listed weapon has one.
int ctype = listed.Any(c => c.SlayerType > 0) ? CreatureTypeOf(wcid, target.Name, target.Id) : 0;
int ctype = 0;
if (listed.Any(c => c.SlayerType > 0))
{
ctype = CreatureTypeOf(wcid, target.Name, target.Id);
if (ctype == 0 && _slayerTypeUnknownNoted.TryAdd(wcid != 0 ? wcid.ToString() : target.Name ?? "", 0))
_host.Log($"[EquipDiag] '{target.Name}' (wcid {wcid}): creature type not known yet (not appraised, not in the creature data) - no slayer check until it is");
}
return WeaponPlanner.Choose(listed, ruleElement, weak, e => CanCastElement(e, rule),
fixedId, fixedSource, learnedId, ctype, fixedIsDefault);
}
@ -3424,18 +3431,26 @@ public partial class CombatManager : IDisposable
/// <summary>
/// A weapon's slayer (creature type, damage multiplier); (0, 0) when it has none or isn't
/// identified yet (the weapon tracker identifies listed weapons). ACE needs both properties.
/// identified yet (the weapon tracker identifies listed weapons). The multiplier is 0 when
/// not known: ACE sends SlayerCreatureType (int 166, an assessment property) on appraisal
/// but never SlayerDamageBonus (float 138), so requiring both (as before 2026-10-05) meant no
/// slayer was ever seen on an ACE server. A server that does send float 138 gets it used.
/// </summary>
internal (int Type, double Bonus) SlayerOf(int weaponId)
{
uint uid = unchecked((uint)weaponId);
if (!_host.HasGetObjectIntProperty || !_host.TryGetObjectIntProperty(uid, PropSlayerCreatureType, out int t) || t <= 0)
return (0, 0);
if (!_host.HasGetObjectDoubleProperty || !_host.TryGetObjectDoubleProperty(uid, PropSlayerDamageBonus, out double b) || b <= 0)
return (0, 0);
return (t, b);
double bonus = _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(uid, PropSlayerDamageBonus, out double b) && b > 0 ? b : 0;
if (_slayerNoted.TryAdd((weaponId, t), 0))
_host.Log($"[EquipDiag] weapon 0x{uid:X8} '{WeaponName(weaponId)}' slays {CreatureTypeNames.Name(t)} ({(bonus > 0 ? "x" + bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture) : "bonus not sent")})");
return (t, bonus);
}
// Logged once each: a listed weapon's slayer; a monster whose type isn't known while a slayer is listed.
private readonly System.Collections.Concurrent.ConcurrentDictionary<(int, int), byte> _slayerNoted = new();
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, byte> _slayerTypeUnknownNoted = new();
// Creature type by wcid, once seen: a wcid's type never changes, so the next spawn is instant.
// Concurrent: the Damage tab's JSON export asks for weaknesses off the combat tick.
private readonly System.Collections.Concurrent.ConcurrentDictionary<uint, int> _creatureTypeByWcid = new();
@ -3443,7 +3458,8 @@ public partial class CombatManager : IDisposable
/// <summary>
/// The monster's CreatureType (PropertyInt 2; 0 = unknown): this session's per-wcid cache,
/// else the creature store (appraisals saved by name and wcid), else the live appraisal
/// (the engine identifies every new object). Never guessed from the name.
/// (the engine identifies every new object), else the shipped world-database table
/// (CreatureWeakness: wcid and exact name). Never guessed from name keywords.
/// </summary>
internal int CreatureTypeOf(uint wcid, string? name, int objectId = 0)
{
@ -3464,6 +3480,11 @@ public partial class CombatManager : IDisposable
if (_creatureTypeByWcid.Count > 4096) _creatureTypeByWcid.Clear();
_creatureTypeByWcid[wcid] = ctype;
}
// Not seen yet on this server: the shipped world-database table (wcid and name must both
// match, as for its resists). Not cached, so this monster's own appraisal still wins once
// it lands. 4,506 of the ~4,900 creature profiles are seeded without a type (2026-10-05),
// so before this the first fight with a monster had no slayer step.
if (ctype <= 0) ctype = CreatureWeakness.TableCreatureType(wcid, name);
return ctype > 0 ? ctype : 0;
}
@ -3996,7 +4017,7 @@ public partial class CombatManager : IDisposable
&& (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletely();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Combat");
_combatSwapTeardownDone = true;
_host.Log($"[EquipDiag] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})");
}
@ -4244,7 +4265,7 @@ public partial class CombatManager : IDisposable
&& (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletely();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Combat");
_combatSwapTeardownDone = true;
}
if (!EnsureHandClearForWand(wandId, diagNow: true))
@ -4393,13 +4414,13 @@ public partial class CombatManager : IDisposable
}
else if (error > 0)
{
_host.SetMotion(MotionTurnRight, true);
_host.SetMotion(MotionTurnLeft, false);
_host.SetMotionBy("Combat", MotionTurnRight, true);
_host.SetMotionBy("Combat", MotionTurnLeft, false);
}
else
{
_host.SetMotion(MotionTurnLeft, true);
_host.SetMotion(MotionTurnRight, false);
_host.SetMotionBy("Combat", MotionTurnLeft, true);
_host.SetMotionBy("Combat", MotionTurnRight, false);
}
}
catch { }
@ -4407,8 +4428,8 @@ public partial class CombatManager : IDisposable
private void ClearCombatTurnMotions()
{
_host.SetMotion(MotionTurnRight, false);
_host.SetMotion(MotionTurnLeft, false);
_host.SetMotionBy("Combat", MotionTurnRight, false);
_host.SetMotionBy("Combat", MotionTurnLeft, false);
}
/// <summary>Let go of a turn the facing servo is holding. Called when combat stops

View file

@ -0,0 +1,205 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// [HealLatency]: how long health sat under a heal line before the first heal went out, and what
/// held it meanwhile. One line per episode, and a summary every <see cref="SummaryEvery"/> episodes.
///
/// Why (2026-10-05): a tester playing a mage reported heals that are "sometimes fine, sometimes
/// several seconds late", and nothing in the log said when health crossed a line or what the bot
/// was waiting on. With this a tester's log answers it:
///
/// [HealLatency] 3120 ms: health 41% under Heal At 60% (in combat) -> Heal Self; held by: busy count 2980 ms (leftover), cast gate 140 ms; arbiter Combat 120 ms
///
/// An episode opens on the first tick health is under the active line (Emergency Heal At, Stamina
/// To Health At, Heal At in combat, Top Off HP idle) and ends at the first heal sent for it (kit,
/// Heal Self, Stamina to Health or a health potion). While health stays under a line, the next
/// episode opens once that heal has resolved (no kit or vital cast left in flight), so a slow
/// second heal is measured from when it became possible, not from the first one. An episode that
/// ends with no heal (health rose, or the fight ended and the idle line is lower) is logged only
/// when it lasted <see cref="NoHealLogMs"/> or more.
///
/// Pure bookkeeping: BuffManager feeds it once per heartbeat and when a heal goes out; it never
/// calls the game. The clock comes from the caller (tests move it by hand).
/// </summary>
internal sealed class HealLatencyTracker
{
/// <summary>A summary line after this many healed episodes.</summary>
public const int SummaryEvery = 10;
/// <summary>An episode that ends without a heal is logged only from this long.</summary>
public const double NoHealLogMs = 1000;
private readonly Action<string> _log;
public HealLatencyTracker(Action<string> log) => _log = log;
// ── The open episode ────────────────────────────────────────────────────
private bool _open;
private bool _healed; // a heal went out for the open episode; waiting for it to resolve
private bool _followUp; // opened while health stayed under the line after a heal
private DateTime _start;
private int _startHp;
private string _line = "";
private int _lineValue;
private bool _inCombat;
private DateTime _lastTickAt = DateTime.MinValue;
// Time held per reason, and time the arbiter gave the tick to something other than Buffing.
private readonly Dictionary<string, double> _held = new(StringComparer.Ordinal);
private readonly Dictionary<string, double> _arbiter = new(StringComparer.Ordinal);
private string _lastDetail = "";
// ── Summary since the last summary line ─────────────────────────────────
private int _n;
private double _sumMs, _maxMs;
private string _maxWhat = "";
private int _over1s, _over3s, _noHeal;
/// <summary>Totals for the tests and /ra status.</summary>
public int Episodes { get; private set; }
public double LastDelayMs { get; private set; } = -1;
public string LastLine { get; private set; } = "";
public bool IsOpen => _open && !_healed;
/// <summary>
/// Once per heartbeat, before the tick's work: health and the line it is under (line "" = none).
/// <paramref name="healInFlight"/>: a kit or a heal cast from the last episode hasn't resolved yet.
/// </summary>
public void Observe(DateTime now, int hp, string line, int lineValue, bool inCombat, bool healInFlight)
{
bool under = line.Length > 0;
if (!under)
{
if (_open && !_healed)
{
double ms = (now - _start).TotalMilliseconds;
if (ms >= NoHealLogMs)
{
_noHeal++;
_log($"[HealLatency] no heal in {ms:0} ms: health {_startHp}% under {_line} {_lineValue}%{Where(_inCombat)}{(_followUp ? " (follow-up)" : "")}, " +
$"then {hp}% (over the line now); held by: {Held()}{Arb()}");
}
}
_open = false;
_healed = false;
_followUp = false;
return;
}
if (_open && _healed)
{
// Still under a line after a heal: the next one is measured from when it became possible.
if (healInFlight) { _lastTickAt = now; return; }
Begin(now, hp, line, lineValue, inCombat, followUp: true);
return;
}
if (!_open)
{
Begin(now, hp, line, lineValue, inCombat, followUp: false);
return;
}
// Open and waiting: a lower line (Heal At -> Emergency) is worth saying in the line.
if (line != _line && (line.StartsWith("Emergency", StringComparison.Ordinal) || line.StartsWith("Stamina", StringComparison.Ordinal)))
{
_line = line;
_lineValue = lineValue;
}
}
/// <summary>Once per heartbeat, after the tick's work: why no heal went out this tick.</summary>
public void EndTick(DateTime now, string heldBy, string detail, string arbiterActivity)
{
if (!_open || _healed) { _lastTickAt = now; return; }
double dt = _lastTickAt == DateTime.MinValue ? 0 : (now - _lastTickAt).TotalMilliseconds;
if (dt < 0 || dt > 2000) dt = 0; // a hitch or a paused clock is not "held"
_lastTickAt = now;
if (dt <= 0) return;
string key = heldBy.Length > 0 ? heldBy : "nothing reported";
_held[key] = (_held.TryGetValue(key, out double h) ? h : 0) + dt;
if (detail.Length > 0) _lastDetail = detail;
if (arbiterActivity.Length > 0 && arbiterActivity != "Buffing")
_arbiter[arbiterActivity] = (_arbiter.TryGetValue(arbiterActivity, out double a) ? a : 0) + dt;
}
/// <summary>A heal went out (kit, Heal Self, Stamina to Health, health potion).</summary>
public void HealSent(DateTime now, string action)
{
if (!_open || _healed) return;
_healed = true;
double ms = Math.Max(0, (now - _start).TotalMilliseconds);
Episodes++;
LastDelayMs = ms;
string line = $"[HealLatency] {ms:0} ms: health {_startHp}% under {_line} {_lineValue}%{Where(_inCombat)}{(_followUp ? " (follow-up)" : "")} -> {action}; held by: {Held()}{Arb()}";
LastLine = line;
_log(line);
_n++;
_sumMs += ms;
if (ms >= 1000) _over1s++;
if (ms >= 3000) _over3s++;
if (ms > _maxMs) { _maxMs = ms; _maxWhat = $"{action}, {TopHeld()}"; }
if (_n >= SummaryEvery)
{
_log($"[HealLatency] summary of {_n} heals: avg {_sumMs / _n:0} ms, max {_maxMs:0} ms ({_maxWhat}); " +
$"{_over1s} over 1 s, {_over3s} over 3 s; {_noHeal} episode(s) with no heal");
_n = 0; _sumMs = 0; _maxMs = 0; _maxWhat = ""; _over1s = 0; _over3s = 0; _noHeal = 0;
}
}
private void Begin(DateTime now, int hp, string line, int lineValue, bool inCombat, bool followUp)
{
_open = true;
_healed = false;
_followUp = followUp;
_start = now;
_startHp = hp;
_line = line;
_lineValue = lineValue;
_inCombat = inCombat;
_lastTickAt = now;
_held.Clear();
_arbiter.Clear();
_lastDetail = "";
}
private static string Where(bool inCombat) => inCombat ? " (in combat)" : " (idle)";
private string Held()
{
if (_held.Count == 0) return "nothing (healed on the first tick)";
var parts = new List<KeyValuePair<string, double>>(_held);
parts.Sort((a, b) => b.Value.CompareTo(a.Value));
var sb = new StringBuilder();
for (int i = 0; i < parts.Count && i < 4; i++)
{
if (i > 0) sb.Append(", ");
sb.Append(parts[i].Key).Append(' ').Append(parts[i].Value.ToString("0")).Append(" ms");
}
if (_lastDetail.Length > 0) sb.Append(" [last: ").Append(_lastDetail).Append(']');
return sb.ToString();
}
private string TopHeld()
{
string top = "nothing";
double best = -1;
foreach (var kv in _held)
if (kv.Value > best) { best = kv.Value; top = kv.Key; }
return top;
}
private string Arb()
{
if (_arbiter.Count == 0) return "";
var sb = new StringBuilder("; arbiter gave the tick to ");
bool first = true;
foreach (var kv in _arbiter)
{
if (!first) sb.Append(", ");
first = false;
sb.Append(kv.Key).Append(' ').Append(kv.Value.ToString("0")).Append(" ms");
}
return sb.ToString();
}
}

View file

@ -0,0 +1,32 @@
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// What RynthAi tells the engine before a hot reload (the RynthPluginReloadBlocker export).
///
/// Drakkon died on 2026-10-05 13:43:20 after an engine hot reload at 13:42:55 took every plugin
/// down for about 8 s in the middle of a fight. The engine now asks each plugin before it reloads
/// and waits (up to 2 minutes) while one says a reload would hurt. RynthAi says so while the macro
/// runs and a monster is engaged, health is under a heal line, or a cast is awaiting its result.
///
/// Pure: the plugin computes the text on its own thread each tick; the export only hands the last
/// text to the engine.
/// </summary>
internal static class ReloadSafety
{
/// <summary>Why a reload now would hurt, or "" when it is safe. The engine logs
/// "engine reload waiting: RynthAi " followed by this text.</summary>
public static string Reason(bool macroRunning, bool monsterEngaged, string healLine, int healthPct,
int lineValue, string castInFlight)
{
if (!macroRunning) return "";
var parts = new List<string>(3);
if (monsterEngaged) parts.Add("a monster engaged");
if (healLine.Length > 0) parts.Add($"health {healthPct}% under {healLine} {lineValue}%");
if (castInFlight.Length > 0) parts.Add($"'{castInFlight}' awaiting its result");
if (parts.Count == 0) return "";
bool fight = monsterEngaged || healLine.Length > 0;
return (fight ? "in combat" : "casting") + " (" + string.Join(", ", parts) + ")";
}
}

View file

@ -9,7 +9,9 @@ namespace RynthCore.Plugin.RynthAi;
/// <param name="Element">Normalized element ("" = unknown).</param>
/// <param name="Rending">Element of a rending imbue ("" = none).</param>
/// <param name="SlayerType">The creature type it slays (PropertyInt 166 SlayerCreatureType, 0 = none).</param>
/// <param name="SlayerBonus">Its damage multiplier against that type (PropertyFloat 138 SlayerDamageBonus, 0 = none).</param>
/// <param name="SlayerBonus">Its damage multiplier against that type (PropertyFloat 138 SlayerDamageBonus); 0 = not
/// known. ACE never sends float 138 on appraisal (it isn't an assessment property), so with a SlayerType it is
/// usually 0, and the weapon still slays (every slayer in the ACE world database has a bonus of 1.15 or more).</param>
internal sealed record WeaponCandidate(int Id, string Name, int Kind, string Element, string Rending, bool InHand,
int SlayerType = 0, double SlayerBonus = 0);
@ -19,17 +21,22 @@ internal readonly record struct WeaponPlan(int WeaponId, string Element, string
/// <summary>
/// The element-and-weapon rule, pure (no host). The weakness decides the weapon, never the
/// other way round, except for a slayer:
/// 1. A Damage tab weapon (this monster's, else the DEFAULT row's) is used as set; it must be in the Items list.
/// Its element is the rule's, else its own, else the weakest the character can cast.
/// other way round, except for a slayer (owner's rule, 2026-10-05: a monster is always
/// attacked with a slayer of it before an element choice, even when another weapon's element
/// meets a lower resistance; only a weapon the player set for that monster trumps it):
/// 1. The weapon set on THIS monster's own Damage tab row is used as set, slayer or not; it
/// must be in the Items list. Its element is the rule's, else its own, else the weakest
/// the character can cast.
/// 2. A slayer: a listed weapon of the character's main kind whose SlayerCreatureType is
/// the monster's CreatureType and whose SlayerDamageBonus is above 1 (ACE multiplies the
/// whole hit by it, so it beats any element choice). Several: the biggest bonus, then
/// the element order (the rule's element, else the weakest group), then a matching
/// rending, then the one in hand, then list order. Its element is the wand's own, else a
/// melee/missile weapon's own, else the rule's, else the weakest the character can cast.
/// Creature type unknown (not appraised yet): no slayer step.
/// 3. (The Damage tab DEFAULT row's weapon is a player pick too: it is step 1.)
/// the monster's CreatureType and whose SlayerDamageBonus is above 1 or not known (ACE
/// multiplies the whole hit by it, so it beats any element choice, and never sends the
/// bonus on appraisal). Several: the biggest bonus (an unknown one counts as
/// UnknownSlayerBonus), then the element order (the rule's element, else the weakest
/// group), then a matching rending, then the one in hand, then list order. Its element
/// is the wand's own, else a melee/missile weapon's own, else the rule's, else the
/// weakest the character can cast. Creature type unknown: no slayer step.
/// A slayer of another kind (a melee slayer for a mage) is not a candidate.
/// 3. The Damage tab DEFAULT row's weapon (listed only): above the element steps, below a slayer.
/// 4. A Monsters rule damage type (not Auto) is the element; wield the listed weapon of that
/// element (a matching rending first, then the one in hand, then list order).
/// Whatever is chosen, a wand casts its own element when it has one (owner's rule,
@ -51,6 +58,12 @@ internal static class WeaponPlanner
/// <summary>Two multipliers this close are a tie.</summary>
public const double TieEpsilon = 0.005;
/// <summary>
/// The bonus a slayer whose SlayerDamageBonus isn't known is ranked at: the smallest in the
/// ACE world database (1.15), so a slayer with a known bigger bonus wins over it.
/// </summary>
public const double UnknownSlayerBonus = 1.15;
/// <summary>Fallback element order when nothing is known ("Slash" first).</summary>
public static readonly string[] FallbackOrder = { "Slash", "Fire", "Cold", "Lightning", "Acid", "Pierce", "Bludgeon", "Nether" };
@ -69,12 +82,13 @@ internal static class WeaponPlanner
bool ruleSet = rule.Length > 0;
WeaponCandidate? fixedPick = fixedWeaponId != 0 ? Find(listed, fixedWeaponId) : null;
// 1. A weapon the player picked on the Damage tab: for this monster, or the DEFAULT row's
// (listed only). A player's pick is honoured, slayer or not (owner, 2026-10-04: "if
// it's set to auto slayer wins, if the player picks a weapon we honour that").
// fixedIsDefault only changes the source label.
if (fixedPick != null)
return FixedPlan(fixedPick, fixedSource, rule, weak, canCast);
// 1. The weapon the player set on this monster's own Damage tab row (listed only): honoured,
// slayer or not (owner, 2026-10-05: "the only time a slayer property gets trumped is if
// the player manually inputs a weapon without it"). The DEFAULT row's weapon is not a
// pick for this monster: a slayer of it beats that one (step 3).
if (fixedPick != null && !fixedIsDefault)
return FixedPlan(fixedPick, Slays(fixedPick, creatureType)
? fixedSource + ", " + SlayerSource(creatureType, fixedPick.SlayerBonus) : fixedSource, rule, weak, canCast);
if (listed.Count == 0)
{
@ -101,7 +115,7 @@ internal static class WeaponPlanner
}
}
// 3. The Damage tab default weapon (listed only).
// 3. The Damage tab DEFAULT row's weapon (listed only): no slayer of this monster is listed.
if (fixedPick != null)
return FixedPlan(fixedPick, fixedSource, rule, weak, canCast);
@ -200,16 +214,24 @@ internal static class WeaponPlanner
return null;
}
/// <summary>True when <paramref name="c"/> slays <paramref name="creatureType"/> (ACE: SlayerCreatureType == CreatureType, with a bonus).</summary>
/// <summary>
/// True when <paramref name="c"/> slays <paramref name="creatureType"/> (ACE: SlayerCreatureType ==
/// CreatureType). A bonus that is known must be above 1; an unknown one (0: ACE doesn't send
/// float 138 on appraisal) counts.
/// </summary>
public static bool Slays(WeaponCandidate c, int creatureType) =>
creatureType > 0 && c.SlayerType == creatureType && c.SlayerBonus > 1.0 + TieEpsilon;
creatureType > 0 && c.SlayerType == creatureType && (c.SlayerBonus <= 0 || c.SlayerBonus > 1.0 + TieEpsilon);
/// <summary>The plan's source for a slayer: "slayer (Olthoi x2)".</summary>
public static string SlayerSource(int creatureType, double bonus) =>
$"slayer ({CreatureTypeNames.Name(creatureType)} x{bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)})";
/// <summary>The bonus a slayer is ranked at: its own when known, else <see cref="UnknownSlayerBonus"/>.</summary>
public static double RankBonus(WeaponCandidate c) => c.SlayerBonus > 0 ? c.SlayerBonus : UnknownSlayerBonus;
/// <summary>The plan's source for a slayer: "slayer (Olthoi x2)", or "slayer (Olthoi)" when the bonus isn't known.</summary>
public static string SlayerSource(int creatureType, double bonus) => bonus > 0
? $"slayer ({CreatureTypeNames.Name(creatureType)} x{bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)})"
: $"slayer ({CreatureTypeNames.Name(creatureType)})";
/// <summary>
/// The matching slayer to wield: the biggest bonus (ties within <see cref="TieEpsilon"/>),
/// The matching slayer to wield: the biggest bonus (<see cref="RankBonus"/>; ties within <see cref="TieEpsilon"/>),
/// then the element order (the rule's element, else the weakest group), then a matching
/// rending, then the one in hand, then list order. Null when none matches.
/// </summary>
@ -217,7 +239,7 @@ internal static class WeaponPlanner
CreatureWeakness.Ranking? weak, Func<string, bool> canCast)
{
double top = 0;
foreach (var c in pool) if (Slays(c, creatureType) && c.SlayerBonus > top) top = c.SlayerBonus;
foreach (var c in pool) if (Slays(c, creatureType) && RankBonus(c) > top) top = RankBonus(c);
if (top <= 0) return null;
List<List<string>>? groups = rule.Length == 0 && weak != null && weak.Order.Count > 0 ? TieGroups(weak) : null;
@ -226,7 +248,7 @@ internal static class WeaponPlanner
for (int i = 0; i < pool.Count; i++)
{
var c = pool[i];
if (!Slays(c, creatureType) || c.SlayerBonus < top - TieEpsilon) continue;
if (!Slays(c, creatureType) || RankBonus(c) < top - TieEpsilon) continue;
int elemRank = 0;
if (rule.Length > 0) elemRank = c.Element == rule ? 0 : 1;
else if (groups != null)

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
@ -21,6 +22,8 @@ public sealed partial class RynthAiPlugin
public string LongDesc { get; init; }
public bool InFellowship { get; init; }
public bool KillerIsFellow { get; init; }
/// <summary>Your own death corpse, to be recovered whole (LootOwnCorpse; see MatchOwnDeathCorpse).</summary>
public bool IsOwnDeathCorpse { get; init; }
}
// id → completed-at ms. Authoritative "looted, do not reopen" set. Aged out
@ -238,7 +241,7 @@ public sealed partial class RynthAiPlugin
{
string count = _lastCombatBusyStaleLogAt == 0 ? "first"
: $"{_combatBusyStaleSinceLog} in the last {(now - _lastCombatBusyStaleLogAt) / 1000.0:0}s";
Log($"[RynthAi] shadow busy-reset by combat (was {was}, {reason}; {count}) — real field left to the engine reconciler");
Log($"[RynthAi] shadow busy-reset for a leftover count (was {was}, {reason}; {count}) — real field left to the engine reconciler");
_lastCombatBusyStaleLogAt = now;
_combatBusyStaleSinceLog = 0;
}
@ -522,8 +525,9 @@ public sealed partial class RynthAiPlugin
if (_targetCorpseId == 0)
{
// Same gate as HasLootWork: this claim runs every tick whatever the arbiter
// decided, so without it a full pack still claimed the next corpse.
if (IsLootingBlockedByPack(settings))
// decided, so without it a full pack still claimed the next corpse. Your own
// corpse is let through unless no pack has a slot at all.
if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters))
return;
if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _))
@ -546,6 +550,22 @@ public sealed partial class RynthAiPlugin
LootDiag($"[RynthAi] Corpse loot: claimed corpse target 0x{(uint)corpse.Id:X8}.");
PauseNavigationForCorpse();
}
else if (_openedContainerId == 0 && settings.LootOwnCorpse)
{
// Your own corpse came into range while another (unopened) corpse was claimed:
// it beats normal looting, so switch to it.
WorldObject? claimed = _objectCache[_targetCorpseId];
if ((claimed == null || !EvaluateCorpseLootDecision(claimed).IsOwnDeathCorpse)
&& TryFindOwnCorpseInRange(maxMeters, out WorldObject? ownNow) && ownNow != null && ownNow.Id != _targetCorpseId)
{
LootDiag($"[RynthAi] Own corpse: 0x{(uint)ownNow.Id:X8} is in range; switching to it from 0x{(uint)_targetCorpseId:X8}.");
ResetCorpseTarget();
_targetCorpseId = ownNow.Id;
_corpseTargetSince = now;
_lastCorpseOpenAttemptAt = 0;
_lastOpenAttemptCorpseId = 0;
}
}
// A claim can be tentative: the killer is unknown until the corpse's ID lands.
// Once it says the corpse isn't ours to loot, drop the claim instead of walking
@ -685,6 +705,8 @@ public sealed partial class RynthAiPlugin
long now = CorpseNowMs;
int playerId = unchecked((int)_playerId);
WorldObject? ownCorpse = null;
double ownDistance = double.MaxValue;
foreach (WorldObject candidate in _objectCache.GetLandscapeObjects())
{
if (candidate.ObjectClass != AcObjectClass.Corpse)
@ -712,13 +734,28 @@ public sealed partial class RynthAiPlugin
}
double dist = _objectCache.Distance(playerId, candidate.Id);
if (dist > maxMeters || dist >= distanceMeters)
if (dist > maxMeters)
continue;
// Your own corpse beats any other corpse in range, whatever the distances.
if (decision.IsOwnDeathCorpse)
{
if (ownCorpse == null || dist < ownDistance) { ownCorpse = candidate; ownDistance = dist; }
continue;
}
if (dist >= distanceMeters)
continue;
corpse = candidate;
distanceMeters = dist;
}
if (ownCorpse != null)
{
corpse = ownCorpse;
distanceMeters = ownDistance;
}
return corpse != null;
}
@ -769,6 +806,44 @@ public sealed partial class RynthAiPlugin
};
}
// Your own death corpse (LootOwnCorpse): recovered whole, whatever Loot From says. A
// corpse with your name whose ID hasn't landed yet waits for it (no profile looting of
// it meanwhile); anything else falls through to the ownership rules below unchanged.
if (settings.LootOwnCorpse)
{
OwnCorpseMatch own = MatchOwnDeathCorpse(corpse.Name, myName, longDesc);
if (own == OwnCorpseMatch.Yes)
{
return new CorpseLootDecision
{
ShouldLoot = true,
ModeName = "Own corpse",
Reason = "Your own corpse: every item on it is recovered (Recover My Corpse).",
KillerName = killerName,
PlayerName = myName,
LongDesc = longDesc,
InFellowship = inFellowship,
KillerIsFellow = killerIsFellow,
IsOwnDeathCorpse = true
};
}
if (own == OwnCorpseMatch.Pending)
{
RequestOwnCorpseId(corpse.Id);
return new CorpseLootDecision
{
ShouldLoot = false,
ModeName = "Own corpse",
Reason = "Named like your corpse; waiting for its ID (the 'Killed by' line) before recovering it.",
KillerName = killerName,
PlayerName = myName,
LongDesc = longDesc,
InFellowship = inFellowship,
KillerIsFellow = killerIsFellow
};
}
}
if (lootOwnership >= 2)
{
return new CorpseLootDecision
@ -1017,6 +1092,15 @@ public sealed partial class RynthAiPlugin
TickPendingCorpsePickup(settings);
if (_currentLootItemMovePending)
return; // Still waiting for this pickup to clear
if (_openedContainerId != corpseId)
return; // the retry finished or paused the corpse (no pack had room)
}
// Your own corpse: every item, no profile (RynthAiPlugin.OwnCorpse.cs).
if (IsOwnDeathCorpseId(settings, corpseId))
{
TickOwnCorpseRecovery(settings, corpseId, containedItems, openAge, now);
return;
}
// Pre-classify items and batch-request IDs only for items that need them.
@ -1384,7 +1468,16 @@ public sealed partial class RynthAiPlugin
/// </summary>
private LootPickupResult SendLootPickup(int itemId, string itemName, int corpseId)
{
LootPickupResult r = LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out uint dest);
bool ownCorpse = corpseId != 0 && corpseId == _ownRecoveryCorpseId;
uint dest;
LootPickupResult r = ownCorpse
? SendOwnCorpsePickup(itemId, out dest)
: LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out dest);
if (ownCorpse && r == LootPickupResult.NoRoom)
{
PauseOwnCorpseNoRoom(corpseId, itemName);
return r;
}
switch (r)
{
case LootPickupResult.Moved:
@ -1412,6 +1505,8 @@ public sealed partial class RynthAiPlugin
_processedCorpseItems.Add(_currentLootItemId);
LootDiag($"[RynthAi] Corpse loot: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}.");
if (_openedContainerId != 0 && _openedContainerId == _ownRecoveryCorpseId)
NoteOwnCorpseItemRecovered(now);
if (!string.IsNullOrWhiteSpace(_currentLootItemName))
ChatLine($"[RynthAi] Looted [{_currentLootItemActionLabel}] {_currentLootItemName}");
@ -1462,7 +1557,8 @@ public sealed partial class RynthAiPlugin
}
// No room anywhere: don't start on another corpse (IsPackFull says so once in chat).
if (IsLootingBlockedByPack(settings))
// Your own corpse is let through unless no pack has a slot at all.
if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, GetCorpseApproachRangeMaxMeters(settings)))
return false;
// Loot grace: combat just ended and the corpse CreateObject has not
@ -1542,6 +1638,10 @@ public sealed partial class RynthAiPlugin
if (now - _corpseWaitingSince[candidate.Id] >= LootStarveMs)
_lootStarved = true;
}
else if (dist != double.MaxValue && decision.IsOwnDeathCorpse && _corpseSkipLogged.Add(candidate.Id))
{
LootDiag($"[RynthAi] Own corpse: 0x{(uint)candidate.Id:X8} '{candidate.Name}' is out of loot range (d={dist:0.0}m > {maxMeters:0.0}m); it is recovered once it is within range.");
}
else if (dist != double.MaxValue && IsOwnKill(decision) && _corpseSkipLogged.Add(candidate.Id))
{
LootDiag($"[RynthAi] Corpse loot: own corpse 0x{(uint)candidate.Id:X8} '{candidate.Name}' is out of loot range (d={dist:0.0}m > {maxMeters:0.0}m); not walking back for it.");
@ -1603,22 +1703,37 @@ public sealed partial class RynthAiPlugin
}
/// <summary>
/// Pure classification — evaluates an item against the active loot profile
/// without performing any pickup or side effects. Returns true if the item
/// matched a loot/salvage rule.
/// Classification: evaluates an item against the active loot profile and RynthAi's
/// built-in keeps without performing any pickup. Returns true if the item is to be
/// taken; actionLabel/ruleLabel are what [LootEval] logs. The looter's calls record
/// what they approve (pending sets, counters, chat); ClassifyLootItem has the preview.
/// </summary>
private bool ClassifyItemAgainstProfile(WorldObject item, LegacyUiSettings settings, out string actionLabel, out bool isSalvage, out string ruleLabel)
private bool ClassifyItemAgainstProfile(WorldObject item, LegacyUiSettings settings, out string actionLabel, out bool isSalvage, out string ruleLabel) =>
ClassifyLootItem(item, settings, preview: false, out actionLabel, out isSalvage, out ruleLabel, out _);
/// <summary>
/// The one place the looter decides, with <paramref name="preview"/>: the same verdict
/// with nothing recorded, counted, logged or said in chat (the "Add to loot profile"
/// popup asking why an item is taken). <paramref name="builtIn"/> is set when one of
/// RynthAi's built-in keeps took the item rather than a loot profile rule: Learn unknown
/// spells and mana stones (checked before the profile), Mana Tap (when no rule matches).
/// It says what and where to change it, in plain ASCII (the popup's font).
/// </summary>
private bool ClassifyLootItem(WorldObject item, LegacyUiSettings settings, bool preview,
out string actionLabel, out bool isSalvage, out string ruleLabel, out string builtIn)
{
actionLabel = string.Empty;
isSalvage = false;
ruleLabel = string.Empty;
builtIn = string.Empty;
// Learn unknown spells (VTank ReadUnknownScrolls): a built-in rule ahead of the loot
// profile, as in VTank. A scroll of a spell we don't know and can learn is looted to read.
if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule))
if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule, out string learnWhy, preview))
{
actionLabel = ScrollLearner.ReadAction;
ruleLabel = learnRule;
builtIn = $"Learn unknown spells ({learnWhy}) - change in Settings > Looting, Learn Unknown Spells";
return true;
}
@ -1663,15 +1778,17 @@ public sealed partial class RynthAiPlugin
int haveCount = liveCount + pendingNotYetCounted;
// One-time-per-corpse log so we can see what the count was based on.
if (_pendingManaStoneIds.Count == 0)
if (!preview && _pendingManaStoneIds.Count == 0)
Host.Log($"[RynthAi] ManaStone count for cap check: live={liveCount} pending={pendingNotYetCounted} cap={settings.ManaStoneKeepCount} (cache_known={_objectCache?.AllKnownObjects().Count() ?? 0})");
// If this specific stone is already approved, return the same answer
// we returned last time (no further log spam, no count change).
string stoneWhy = $"a mana stone, {haveCount} of {settings.ManaStoneKeepCount} kept - change in the Items panel, Mana Stone Tapping (Keep count)";
if (_pendingManaStoneIds.Contains(item.Id))
{
actionLabel = "Keep";
ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})";
builtIn = stoneWhy;
return true;
}
@ -1679,39 +1796,42 @@ public sealed partial class RynthAiPlugin
{
actionLabel = "Keep";
ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})";
builtIn = stoneWhy;
if (preview) return true;
ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}, +1) — looting.");
_pendingManaStoneIds.Add(item.Id);
return true;
}
ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving.");
if (!preview)
ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving.");
return false;
}
if (TryLoadNativeLootProfile(out LootProfile nativeProfile, out _))
{
_corpseItemsEvaluated++;
if (!preview) _corpseItemsEvaluated++;
var (nativeAction, nativeRule) = LootEvaluator.Classify(nativeProfile, item, _charSkills);
if (nativeRule == null)
{
if (TryClassifyAsManaTap(item, settings, out actionLabel, out ruleLabel))
if (TryClassifyAsManaTap(item, settings, preview, out actionLabel, out ruleLabel, out builtIn))
{
_corpseItemsMatched++;
if (!preview) _corpseItemsMatched++;
return true;
}
return false;
}
ruleLabel = string.IsNullOrWhiteSpace(nativeRule.Name) ? "rule" : nativeRule.Name.Trim();
if (nativeAction == LootAction.Read && IsReadOfNonScroll(item, ruleLabel))
if (nativeAction == LootAction.Read && IsReadOfNonScroll(item, ruleLabel, preview))
return false;
if (nativeAction == LootAction.KeepUpTo)
{
var rule = nativeRule;
if (!UnderKeepCap("n:" + ruleLabel, ruleLabel, item, rule.KeepCount,
inv => LootEvaluator.Matches(rule, inv, _charSkills)))
inv => LootEvaluator.Matches(rule, inv, _charSkills), preview))
return false;
}
_corpseItemsMatched++;
if (!preview) _corpseItemsMatched++;
actionLabel = nativeAction.ToString();
isSalvage = nativeAction == LootAction.Salvage;
return true;
@ -1721,15 +1841,15 @@ public sealed partial class RynthAiPlugin
if (!TryLoadLootProfile(string.Empty, out VTankLootProfile vtankProfile, out _))
return false;
_corpseItemsEvaluated++;
if (!preview) _corpseItemsEvaluated++;
VTankLootContext lootCtx = new(Host, _playerId) { Cache = _objectCache };
VTankLootRule? matchedRule = VTankLootEvaluator.FirstMatch(vtankProfile, item, lootCtx, out int matchedRuleIndex);
if (matchedRule == null)
{
if (TryClassifyAsManaTap(item, settings, out actionLabel, out ruleLabel))
if (TryClassifyAsManaTap(item, settings, preview, out actionLabel, out ruleLabel, out builtIn))
{
_corpseItemsMatched++;
if (!preview) _corpseItemsMatched++;
return true;
}
return false;
@ -1738,16 +1858,16 @@ public sealed partial class RynthAiPlugin
ruleLabel = string.IsNullOrWhiteSpace(matchedRule.Name)
? $"#{matchedRuleIndex}"
: matchedRule.Name.Trim();
if (matchedRule.Action == VTankLootAction.Read && IsReadOfNonScroll(item, ruleLabel))
if (matchedRule.Action == VTankLootAction.Read && IsReadOfNonScroll(item, ruleLabel, preview))
return false;
if (matchedRule.Action == VTankLootAction.KeepUpTo)
{
var rule = matchedRule;
if (!UnderKeepCap("v:" + matchedRuleIndex + ":" + ruleLabel, ruleLabel, item, rule.KeepCount ?? 0,
inv => VTankLootEvaluator.Match(rule, inv, lootCtx)))
inv => VTankLootEvaluator.Match(rule, inv, lootCtx), preview))
return false;
}
_corpseItemsMatched++;
if (!preview) _corpseItemsMatched++;
actionLabel = matchedRule.Action.ToString();
isSalvage = matchedRule.Action == VTankLootAction.Salvage;
return true;
@ -1760,9 +1880,10 @@ public sealed partial class RynthAiPlugin
/// attempted to classify item ... for reading, but that item does not appear to be a
/// scroll. Ignoring it." The item is left, with one log line.
/// </summary>
private bool IsReadOfNonScroll(WorldObject item, string ruleLabel)
private bool IsReadOfNonScroll(WorldObject item, string ruleLabel, bool preview = false)
{
if (ScrollLearner.LooksLikeScroll(item)) return false;
if (preview) return true;
if (_readNonScrollLogged.Count > 1000) _readNonScrollLogged.Clear();
if (_readNonScrollLogged.Add(item.Id))
Host.Log($"[Learn] loot rule '{ruleLabel}' says Read, but '{item.Name}' isn't a scroll - leaving it");
@ -1775,10 +1896,13 @@ public sealed partial class RynthAiPlugin
/// items already approved on this corpse that haven't reached the pack yet.
/// A matching Keep # rule used to loot everything, like a plain Keep.
/// </summary>
private bool UnderKeepCap(string key, string ruleLabel, WorldObject item, int cap, Func<WorldObject, bool> matches)
private bool UnderKeepCap(string key, string ruleLabel, WorldObject item, int cap, Func<WorldObject, bool> matches, bool preview = false)
{
if (!_pendingKeepUpTo.TryGetValue(key, out var pending))
_pendingKeepUpTo[key] = pending = new Dictionary<int, int>();
{
pending = new Dictionary<int, int>();
if (!preview) _pendingKeepUpTo[key] = pending;
}
if (pending.ContainsKey(item.Id)) return true; // approved on an earlier pass
// Whole stacks in the pack that the rule matches, plus approved-but-not-in-the-pack-yet
@ -1791,6 +1915,7 @@ public sealed partial class RynthAiPlugin
id => _objectCache?[id] != null);
int stack = LootKeepCap.StackOf(item);
if (preview) return LootKeepCap.UnderCap(have, cap);
if (!LootKeepCap.UnderCap(have, cap))
{
ChatLine($"[RynthAi] Keep # '{ruleLabel}': have {have}/{cap} — leaving {item.Name}.");
@ -1859,14 +1984,19 @@ public sealed partial class RynthAiPlugin
/// only way an item becomes a tap target: the pickup (label ManaTap) is
/// recorded via ManaStoneManager.MarkLootedForTap.
/// </summary>
private bool TryClassifyAsManaTap(WorldObject item, LegacyUiSettings settings,
out string actionLabel, out string ruleLabel)
private bool TryClassifyAsManaTap(WorldObject item, LegacyUiSettings settings, bool preview,
out string actionLabel, out string ruleLabel, out string builtIn)
{
actionLabel = string.Empty;
ruleLabel = string.Empty;
builtIn = string.Empty;
if (_manaStoneManager == null) return false;
if (!Host.HasGetObjectIntProperty) return false;
// ACE won't drain a wand, staff or orb into a stone, so ManaStoneManager never taps
// one (and its pending-drain count skips them, so the quota never filled): every
// high-mana wand was looted and kept for good. Drakkon's "Piercing Sceptre", 2026-10-05.
if (ManaStoneManager.IsWandLike(item)) return false;
int threshold = settings.ManaTapMinMana;
if (threshold <= 0) return false;
@ -1876,12 +2006,17 @@ public sealed partial class RynthAiPlugin
return false;
if (curMana < threshold) return false;
string tapWhy = "Mana Tap (" + curMana.ToString("N0", CultureInfo.InvariantCulture) + " mana >= "
+ threshold.ToString("N0", CultureInfo.InvariantCulture)
+ "), looted to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping";
// Already approved this session — return same answer without re-logging
// or re-counting against the quota.
if (_pendingManaTapIds.Contains(item.Id))
{
actionLabel = ManaTapActionLabel;
ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})";
builtIn = tapWhy;
return true;
}
@ -1893,6 +2028,8 @@ public sealed partial class RynthAiPlugin
actionLabel = ManaTapActionLabel;
ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})";
builtIn = tapWhy;
if (preview) return true;
ChatLine($"[RynthAi] Mana tap candidate: '{item.Name}' (mana {curMana}, slot {_pendingManaTapIds.Count + 1}) — looting to drain.");
_pendingManaTapIds.Add(item.Id);
return true;
@ -2090,13 +2227,13 @@ public sealed partial class RynthAiPlugin
ClearCorpseTurnMotions();
if (!_navigationEngine.ServoToward(desiredDeg))
{
if (_corpseAutorunActive) { Host.SetAutoRun(false); _corpseAutorunActive = false; }
if (_corpseAutorunActive) { Host.SetAutoRunBy("Loot", false); _corpseAutorunActive = false; }
return;
}
long nowMs = CorpseNowMs;
if (!_corpseAutorunActive || nowMs - _lastCorpseApproachHeartbeatAt >= 500)
{
Host.SetAutoRun(true);
Host.SetAutoRunBy("Loot", true);
_corpseAutorunActive = true;
_lastCorpseApproachHeartbeatAt = nowMs;
}
@ -2110,13 +2247,13 @@ public sealed partial class RynthAiPlugin
// Use smooth motion turns, same as NavigationEngine/CombatManager
if (signedError > 0)
{
Host.SetMotion(MotionTurnRight, true);
Host.SetMotion(MotionTurnLeft, false);
Host.SetMotionBy("Loot", MotionTurnRight, true);
Host.SetMotionBy("Loot", MotionTurnLeft, false);
}
else
{
Host.SetMotion(MotionTurnLeft, true);
Host.SetMotion(MotionTurnRight, false);
Host.SetMotionBy("Loot", MotionTurnLeft, true);
Host.SetMotionBy("Loot", MotionTurnRight, false);
}
_corpseApproachTurnsActive = true;
return;
@ -2127,7 +2264,7 @@ public sealed partial class RynthAiPlugin
long now = CorpseNowMs;
if (!_corpseAutorunActive || now - _lastCorpseApproachHeartbeatAt >= 500)
{
Host.SetAutoRun(true);
Host.SetAutoRunBy("Loot", true);
_corpseAutorunActive = true;
_lastCorpseApproachHeartbeatAt = now;
}
@ -2138,8 +2275,8 @@ public sealed partial class RynthAiPlugin
if (!_corpseApproachTurnsActive)
return;
_corpseApproachTurnsActive = false;
Host.SetMotion(MotionTurnRight, false);
Host.SetMotion(MotionTurnLeft, false);
Host.SetMotionBy("Loot", MotionTurnRight, false);
Host.SetMotionBy("Loot", MotionTurnLeft, false);
}
private void StopCorpseMovement()
@ -2149,9 +2286,9 @@ public sealed partial class RynthAiPlugin
if (!_corpseAutorunActive)
return;
Host.SetAutoRun(false);
Host.SetAutoRunBy("Loot", false);
if (Host.HasStopCompletely)
Host.StopCompletely();
Host.StopCompletelyBy("Loot");
_corpseAutorunActive = false;
}
@ -2457,7 +2594,21 @@ public sealed partial class RynthAiPlugin
bool openWasSent = wasOpened || _lastOpenAttemptCorpseId == corpseId;
int abandons =_corpseAbandonCounts.TryGetValue(corpseId, out int n) ? n + 1 : 1;
_corpseAbandonCounts[corpseId] = abandons;
if (wasOpened || abandons >= 3)
// Your own corpse is never written off after one timeout: it gets OwnCorpseMaxAbandons tries.
bool ownCorpse = IsOwnDeathCorpseId(_dashboard?.Settings, corpseId);
if (ownCorpse && abandons < OwnCorpseMaxAbandons)
{
_corpseCooldownUntil[corpseId] = now + NeverOpenedAbandonRetryMs;
LootDiag($"[RynthAi] Own corpse: 0x{(uint)corpseId:X8} timed out (try {abandons} of {OwnCorpseMaxAbandons}); trying again in {NeverOpenedAbandonRetryMs / 1000}s.");
}
else if (ownCorpse)
{
_completedCorpses[corpseId] = now;
_corpseCooldownUntil.Remove(corpseId);
_corpseAbandonCounts.Remove(corpseId);
ChatLine($"[RynthAi] Own corpse: giving up after {abandons} tries; recover what is left on it by hand.");
}
else if (wasOpened || abandons >= 3)
{
_completedCorpses[corpseId] = now;
_corpseCooldownUntil.Remove(corpseId);
@ -2509,7 +2660,7 @@ public sealed partial class RynthAiPlugin
if (Host.HasCancelAttack) Host.CancelAttack();
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
if (Host.HasStopCompletely) Host.StopCompletely();
if (Host.HasStopCompletely) Host.StopCompletelyBy("Loot/Wedge");
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
// The lock is client-side: AC's pending-item-request slot or attacking
// flag (see the engine's ClientActionGates). Open both now.

View file

@ -91,6 +91,22 @@ internal static class CreatureWeakness
return null;
}
/// <summary>
/// The creature type the world-database table gives this monster (0 = not in it). Same match
/// as <see cref="Rank"/>: the wcid's row when its name agrees (or no name is given); no wcid,
/// the first row of that name. Never guessed from name keywords.
/// </summary>
public static int TableCreatureType(uint wcid, string? name)
{
EnsureLoaded();
name ??= "";
if (wcid == 0 && name.Length > 0 && ByName.TryGetValue(name, out uint byName)) wcid = byName;
if (wcid != 0 && ByWcid.TryGetValue(wcid, out var row)
&& (name.Length == 0 || row.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
return row.Type > 0 ? row.Type : 0;
return 0;
}
/// <summary>Damage multiplier for one element from the server table or the type average; false when unknown.</summary>
public static bool TryGetMultiplier(uint wcid, string? name, int creatureType, string element, out double mult)
{

View file

@ -104,7 +104,7 @@ public sealed partial class RynthAiPlugin
_doorActionAt = now;
_navigationEngine?.Stop();
if (Host.HasStopCompletely) Host.StopCompletely();
if (Host.HasStopCompletely) Host.StopCompletelyBy("Door");
_doorPausedNav = true;
Host.UseFor(unchecked((uint)doorId), "Door",

View file

@ -1,6 +1,7 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -87,7 +88,7 @@ internal sealed class Jumper
{
_turningStartedAt = DateTime.UtcNow;
if (_host.HasTurnToHeading)
_host.TurnToHeading(_targetHeading);
_host.TurnToHeadingBy("Jump", _targetHeading);
_host.Log($"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms");
}
else

View file

@ -17,6 +17,7 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// CellType: Flat, SlopeUp (avg vertex Z above the layer), SlopeDown (below).
/// This was also RynthAi's plugin-drawn Dungeon Map window (with baked D3D9 floor
/// textures); that window is the engine's DungeonMapFace now, so nothing here draws.
/// The floor grids are also baked to disk (Maps/DungeonMapBake) for DrakRemote's /map.
/// </summary>
internal sealed class DungeonMapUi
{
@ -45,6 +46,31 @@ internal sealed class DungeonMapUi
internal int BestLayerIdxFor(float playerZ) => BestLayerIdx(playerZ);
// Last indoor landblock TickBake handed to the bake (0 = none yet).
private uint _bakeCheckLandblock;
/// <summary>
/// Game-thread tick (throttled by the caller): when the player is indoors in a landblock not
/// seen yet, bake its floor plans to disk for the StatusAgent's /map, whether or not a Radar
/// or Dungeon Map panel is open (only those build this cache). One pose read here; the dat
/// read, rasterise and disk work run on a pool thread, once per landblock per session.
/// Also logs what the background bakes reported.
/// </summary>
internal void TickBake(RynthCoreHost host)
{
Maps.DungeonMapBake.DrainLog(host.Log);
if (!host.HasGetPlayerPose
|| !host.TryGetPlayerPose(out uint cellId, out _, out _, out _, out _, out _, out _, out _))
return;
uint landblock = cellId >> 16;
bool isIndoor = (cellId & 0xFFFF) >= 0x100 && landblock != 0;
if (!isIndoor || landblock == _bakeCheckLandblock) return;
var los = _raycast?.GeometryLoader?.DungeonLOS;
if (los is null) return; // dats still loading; try again next tick
_bakeCheckLandblock = landblock;
Maps.DungeonMapBake.RequestFromDat(los, landblock);
}
private const float GridCell = 0.5f;
private const float FloorNormalThreshold = 0.4f; // |Nz|/|N| — must exceed to be floor-like
private const float FlatNormalThreshold = 0.95f; // |Nz|/|N| — must exceed to be flat (not a ramp)
@ -77,115 +103,14 @@ internal sealed class DungeonMapUi
var portalPolys = los.GetDungeonMapPolygons(landblock);
if (floorPolys.Count == 0 && portalPolys.Count == 0) return;
var zSet = new SortedSet<float>();
foreach (var p in floorPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
foreach (var p in portalPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
_zLayers = new List<float>(zSet);
_zLayers = LayerZs(floorPolys, portalPolys);
_outerEdges = new Dictionary<float, List<(float, float, float, float, CellType)>>(_zLayers.Count);
_fillStrips = new Dictionary<float, List<(float, float, float, float, CellType)>>(_zLayers.Count);
const float LayerTol = 1.0f;
foreach (float layerZ in _zLayers)
{
var filled = new Dictionary<(int, int), CellType>();
foreach (var poly in floorPolys)
{
if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue;
var verts = poly.Vertices;
if (verts == null || verts.Length < 3) continue;
CellType type = ClassifyPoly(verts, layerZ);
if ((byte)type == NotFloor) continue; // physics floor polys are upward-facing; skip any edge cases
RasterizeXY(verts, filled, type);
}
// ── Portal gap-closing (width-matched bridges) ───────────────
// For each pair of portals within 5 units, fill a rectangle
// bridge between them. Width = actual doorway opening derived
// from the portal polygon's larger XY bounding-box dimension.
{
var portals = new List<(float cx, float cy, float halfW)>();
var pDedup = new HashSet<(int, int)>();
foreach (var poly in portalPolys)
{
if (!poly.IsPortal) continue;
if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue;
var verts = poly.Vertices;
if (verts == null || verts.Length < 3) continue;
float cx = 0, cy = 0;
float xMin = verts[0].X, xMax = verts[0].X;
float yMin = verts[0].Y, yMax = verts[0].Y;
for (int k = 0; k < verts.Length; k++)
{
cx += verts[k].X; cy += verts[k].Y;
if (verts[k].X < xMin) xMin = verts[k].X;
if (verts[k].X > xMax) xMax = verts[k].X;
if (verts[k].Y < yMin) yMin = verts[k].Y;
if (verts[k].Y > yMax) yMax = verts[k].Y;
}
cx /= verts.Length; cy /= verts.Length;
float halfW = MathF.Max(xMax - xMin, yMax - yMin) * 0.5f;
halfW = MathF.Max(halfW, 1.0f); // minimum 1 unit wide
if (pDedup.Add(((int)MathF.Round(cx), (int)MathF.Round(cy))))
portals.Add((cx, cy, halfW));
}
const float ConnectDist = 5f;
for (int a = 0; a < portals.Count; a++)
for (int b = a + 1; b < portals.Count; b++)
{
float ddx = portals[b].cx - portals[a].cx;
float ddy = portals[b].cy - portals[a].cy;
float distSq = ddx * ddx + ddy * ddy;
if (distSq > ConnectDist * ConnectDist) continue;
float dist = MathF.Sqrt(distSq);
float hw = MathF.Max(portals[a].halfW, portals[b].halfW);
// Normalised A→B direction, then perpendicular scaled by half-width
float normDx = dist > 0.001f ? ddx / dist : 1f;
float normDy = dist > 0.001f ? ddy / dist : 0f;
float perpX = -normDy * hw;
float perpY = normDx * hw;
float pax = portals[a].cx, pay = portals[a].cy;
float pbx = portals[b].cx, pby = portals[b].cy;
// 4 corners of the bridge quad
float c0x = pax - perpX, c0y = pay - perpY;
float c1x = pax + perpX, c1y = pay + perpY;
float c2x = pbx + perpX, c2y = pby + perpY;
float c3x = pbx - perpX, c3y = pby - perpY;
float bbMinX = MathF.Min(MathF.Min(c0x, c1x), MathF.Min(c2x, c3x));
float bbMaxX = MathF.Max(MathF.Max(c0x, c1x), MathF.Max(c2x, c3x));
float bbMinY = MathF.Min(MathF.Min(c0y, c1y), MathF.Min(c2y, c3y));
float bbMaxY = MathF.Max(MathF.Max(c0y, c1y), MathF.Max(c2y, c3y));
int gcxMin2 = (int)MathF.Floor(bbMinX / GridCell);
int gcxMax2 = (int)MathF.Ceiling(bbMaxX / GridCell);
int gcyMin2 = (int)MathF.Floor(bbMinY / GridCell);
int gcyMax2 = (int)MathF.Ceiling(bbMaxY / GridCell);
for (int gcy2 = gcyMin2; gcy2 <= gcyMax2; gcy2++)
for (int gcx2 = gcxMin2; gcx2 <= gcxMax2; gcx2++)
{
float testX = (gcx2 + 0.5f) * GridCell;
float testY = (gcy2 + 0.5f) * GridCell;
if (PointInConvexQuad(testX, testY,
c0x, c0y, c1x, c1y, c2x, c2y, c3x, c3y))
{
var key = (gcx2, gcy2);
if (!filled.ContainsKey(key)) filled[key] = CellType.Flat;
}
}
}
}
var filled = RasterizeLayer(floorPolys, portalPolys, layerZ);
if (filled.Count == 0) continue;
@ -266,6 +191,149 @@ internal sealed class DungeonMapUi
if (strips.Count > 0) _fillStrips[layerZ] = strips;
}
// Disk floor plans for DrakRemote (StatusAgent /map). Once per landblock, off this
// thread; a plan that is already on disk with the same bytes is left alone.
Maps.DungeonMapBake.Request(landblock, _zLayers, _floorCells);
}
/// <summary>The floor heights (cell Z rounded to 0.1) of a landblock's polygons, ascending.
/// A layer's index in this list is the layer number in the baked map file names.</summary>
internal static List<float> LayerZs(List<DungeonLOS.MapPolygon> floorPolys, List<DungeonLOS.MapPolygon> portalPolys)
{
var zSet = new SortedSet<float>();
foreach (var p in floorPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
foreach (var p in portalPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
return new List<float>(zSet);
}
/// <summary>
/// The typed floor-cell grid of one layer (GridCell squares): physics floor polygons
/// rasterised, plus width-matched bridges between nearby portals. Pure; no state.
/// </summary>
internal static Dictionary<(int, int), CellType> RasterizeLayer(
List<DungeonLOS.MapPolygon> floorPolys, List<DungeonLOS.MapPolygon> portalPolys, float layerZ)
{
const float LayerTol = 1.0f;
var filled = new Dictionary<(int, int), CellType>();
foreach (var poly in floorPolys)
{
if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue;
var verts = poly.Vertices;
if (verts == null || verts.Length < 3) continue;
CellType type = ClassifyPoly(verts, layerZ);
if ((byte)type == NotFloor) continue; // physics floor polys are upward-facing; skip any edge cases
RasterizeXY(verts, filled, type);
}
// ── Portal gap-closing (width-matched bridges) ───────────────
// For each pair of portals within 5 units, fill a rectangle
// bridge between them. Width = actual doorway opening derived
// from the portal polygon's larger XY bounding-box dimension.
{
var portals = new List<(float cx, float cy, float halfW)>();
var pDedup = new HashSet<(int, int)>();
foreach (var poly in portalPolys)
{
if (!poly.IsPortal) continue;
if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue;
var verts = poly.Vertices;
if (verts == null || verts.Length < 3) continue;
float cx = 0, cy = 0;
float xMin = verts[0].X, xMax = verts[0].X;
float yMin = verts[0].Y, yMax = verts[0].Y;
for (int k = 0; k < verts.Length; k++)
{
cx += verts[k].X; cy += verts[k].Y;
if (verts[k].X < xMin) xMin = verts[k].X;
if (verts[k].X > xMax) xMax = verts[k].X;
if (verts[k].Y < yMin) yMin = verts[k].Y;
if (verts[k].Y > yMax) yMax = verts[k].Y;
}
cx /= verts.Length; cy /= verts.Length;
float halfW = MathF.Max(xMax - xMin, yMax - yMin) * 0.5f;
halfW = MathF.Max(halfW, 1.0f); // minimum 1 unit wide
if (pDedup.Add(((int)MathF.Round(cx), (int)MathF.Round(cy))))
portals.Add((cx, cy, halfW));
}
const float ConnectDist = 5f;
for (int a = 0; a < portals.Count; a++)
for (int b = a + 1; b < portals.Count; b++)
{
float ddx = portals[b].cx - portals[a].cx;
float ddy = portals[b].cy - portals[a].cy;
float distSq = ddx * ddx + ddy * ddy;
if (distSq > ConnectDist * ConnectDist) continue;
float dist = MathF.Sqrt(distSq);
float hw = MathF.Max(portals[a].halfW, portals[b].halfW);
// Normalised A→B direction, then perpendicular scaled by half-width
float normDx = dist > 0.001f ? ddx / dist : 1f;
float normDy = dist > 0.001f ? ddy / dist : 0f;
float perpX = -normDy * hw;
float perpY = normDx * hw;
float pax = portals[a].cx, pay = portals[a].cy;
float pbx = portals[b].cx, pby = portals[b].cy;
// 4 corners of the bridge quad
float c0x = pax - perpX, c0y = pay - perpY;
float c1x = pax + perpX, c1y = pay + perpY;
float c2x = pbx + perpX, c2y = pby + perpY;
float c3x = pbx - perpX, c3y = pby - perpY;
float bbMinX = MathF.Min(MathF.Min(c0x, c1x), MathF.Min(c2x, c3x));
float bbMaxX = MathF.Max(MathF.Max(c0x, c1x), MathF.Max(c2x, c3x));
float bbMinY = MathF.Min(MathF.Min(c0y, c1y), MathF.Min(c2y, c3y));
float bbMaxY = MathF.Max(MathF.Max(c0y, c1y), MathF.Max(c2y, c3y));
int gcxMin2 = (int)MathF.Floor(bbMinX / GridCell);
int gcxMax2 = (int)MathF.Ceiling(bbMaxX / GridCell);
int gcyMin2 = (int)MathF.Floor(bbMinY / GridCell);
int gcyMax2 = (int)MathF.Ceiling(bbMaxY / GridCell);
for (int gcy2 = gcyMin2; gcy2 <= gcyMax2; gcy2++)
for (int gcx2 = gcxMin2; gcx2 <= gcxMax2; gcx2++)
{
float testX = (gcx2 + 0.5f) * GridCell;
float testY = (gcy2 + 0.5f) * GridCell;
if (PointInConvexQuad(testX, testY,
c0x, c0y, c1x, c1y, c2x, c2y, c3x, c3y))
{
var key = (gcx2, gcy2);
if (!filled.ContainsKey(key)) filled[key] = CellType.Flat;
}
}
}
}
return filled;
}
/// <summary>
/// The layer heights and per-layer floor grids of a landblock, the same ones RefreshMap
/// builds, without touching this instance's cache. Used by the background map bake. Layers
/// with no cells are left out of the dictionary (but keep their index in the list).
/// </summary>
internal static (List<float> ZLayers, Dictionary<float, Dictionary<(int, int), CellType>> Cells) BuildFloorCells(
DungeonLOS los, uint landblock)
{
var floorPolys = los.GetDungeonMapFloorPolygons(landblock);
var portalPolys = los.GetDungeonMapPolygons(landblock);
var cells = new Dictionary<float, Dictionary<(int, int), CellType>>();
if (floorPolys.Count == 0 && portalPolys.Count == 0) return (new List<float>(), cells);
var zLayers = LayerZs(floorPolys, portalPolys);
foreach (float layerZ in zLayers)
{
var filled = RasterizeLayer(floorPolys, portalPolys, layerZ);
if (filled.Count > 0) cells[layerZ] = filled;
}
return (zLayers, cells);
}
// Merge collinear/adjacent axis-aligned edge segments into the fewest possible lines.

View file

@ -711,6 +711,13 @@ internal sealed class LegacyAdvancedSettingsUi
"alone. Default 1200 (20 minutes). At or below 'Rebuff With', only the\n" +
"expiring buff is recast.");
ImGui.Checkbox("Cast buffs even when an item gives them", ref _settings.CastBuffsOverItemBuffs);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Cast your own buff even when worn gear already gives that buff.\n" +
"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("Buff Difficulty (Min Buffed Skill)");
@ -757,6 +764,12 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Text("Corpse Ownership");
ImGui.SetNextItemWidth(180);
ImGui.Combo("Loot From", ref _settings.LootOwnership, LootOwnershipModes, LootOwnershipModes.Length);
ImGui.Checkbox("Recover My Corpse", ref _settings.LootOwnCorpse);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When your own corpse (\"Corpse of <you>\") is within loot range, open it and take\nevery item on it, whatever the loot profile and Loot From say.");
ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running.");
ImGui.Spacing();
ImGui.Text("Inventory Management");

View file

@ -8,6 +8,7 @@ using System.Text.Json;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
@ -294,6 +295,10 @@ internal sealed class LegacyDashboardRenderer
_dungeonMapUi.SetRaycast(raycast);
}
/// <summary>Bake the floor plans of a dungeon just entered, with no map panel open
/// (DrakRemote's /map). Cheap: one pose read; the work runs on a pool thread.</summary>
public void TickDungeonMapBake() => _dungeonMapUi?.TickBake(_host); // null in tests' bare dashboards
public void PushChatLine(string? text, int chatType) => _rynthChatUi.Push(text, chatType);
/// <summary>Set the handler invoked when the user submits a line from the
@ -1028,6 +1033,7 @@ internal sealed class LegacyDashboardRenderer
RebuffWhenIdle = s.RebuffWhenIdle,
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
@ -1048,6 +1054,8 @@ internal sealed class LegacyDashboardRenderer
LootJumpEnabled = s.LootJumpEnabled,
LootJumpHeight = s.LootJumpHeight,
LootOwnership = s.LootOwnership,
LootOwnCorpse = s.LootOwnCorpse,
TravelToOwnCorpse = s.TravelToOwnCorpse,
EnableAutostack = s.EnableAutostack,
ReadUnknownScrolls = s.ReadUnknownScrolls,
EnableCombineSalvage = s.EnableCombineSalvage,
@ -1228,6 +1236,7 @@ internal sealed class LegacyDashboardRenderer
s.RebuffWhenIdle = p.RebuffWhenIdle;
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
@ -1245,6 +1254,8 @@ internal sealed class LegacyDashboardRenderer
s.LootJumpEnabled = p.LootJumpEnabled;
s.LootJumpHeight = p.LootJumpHeight;
s.LootOwnership = p.LootOwnership;
if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged
if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged
s.EnableAutostack = p.EnableAutostack;
s.ReadUnknownScrolls = p.ReadUnknownScrolls;
s.EnableCombineSalvage = p.EnableCombineSalvage;
@ -1644,11 +1655,14 @@ internal sealed class LegacyDashboardRenderer
dst.OpenDoorRange = tmp.OpenDoorRange;
dst.AutoUnlockDoors = tmp.AutoUnlockDoors;
dst.LootOwnership = tmp.LootOwnership;
dst.LootOwnCorpse = tmp.LootOwnCorpse;
dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse;
dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses;
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
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
@ -2316,8 +2330,8 @@ internal sealed class LegacyDashboardRenderer
break;
case "addWaypoint":
_host.SetMotion(0x6500000D, false); // stop TurnRight
_host.SetMotion(0x6500000E, false); // stop TurnLeft
_host.SetMotionBy("UI", 0x6500000D, false); // stop TurnRight
_host.SetMotionBy("UI", 0x6500000E, false); // stop TurnLeft
if (_host.HasGetPlayerPose &&
_host.TryGetPlayerPose(out _, out float wx, out float wy, out float wz, out _, out _, out _, out _) &&
NavCoordinateHelper.TryGetNavCoords(_host, out double wNS, out double wEW))
@ -2441,7 +2455,11 @@ internal sealed class LegacyDashboardRenderer
sb.Append('{');
AppendBool(sb, "macroRunning", _settings.IsMacroRunning); sb.Append(',');
AppendString(sb, "currentState", _settings.CurrentState ?? string.Empty); sb.Append(',');
AppendString(sb, "botAction", _settings.BotAction ?? "Default"); sb.Append(',');
// "botAction" is what the displays show (the dashboard's activity line, and the phone through
// RynthRemote's status file): the control string, except that the Buffing slot says what it
// is doing (Healing, Restoring mana, ...). The control string itself is "botActionControl".
AppendString(sb, "botAction", ActivityArbiter.DisplayLabel(_settings.BotAction, _settings.BuffingLabel)); sb.Append(',');
AppendString(sb, "botActionControl", _settings.BotAction ?? "Default"); sb.Append(',');
AppendString(sb, "selectedProfile", _settings.SelectedProfile ?? "Default"); sb.Append(',');
// Copy the four profile lists under the lock so we never enumerate one
// while a Refresh*Files mutator Clear()s it on the pump thread — that

View file

@ -3,6 +3,7 @@ using System.IO;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
@ -97,8 +98,8 @@ internal sealed class LegacyNavigationUi
if (ImGui.Button("Add Waypoint", new Vector2(100, 25)))
{
// Stop any active turn motion so the character doesn't keep spinning
_host.SetMotion(0x6500000D, false); // TurnRight
_host.SetMotion(0x6500000E, false); // TurnLeft
_host.SetMotionBy("UI", 0x6500000D, false); // TurnRight
_host.SetMotionBy("UI", 0x6500000E, false); // TurnLeft
if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _))
{

View file

@ -24,6 +24,10 @@ public sealed class LegacyUiSettings
/// <summary>Bot action state — what the bot is doing right now (Default, Combat, Looting, Navigating, Buffing).
/// Separate from meta state so operational cycling doesn't corrupt meta rule matching.</summary>
[JsonIgnore] public string BotAction = "Default";
/// <summary>Display only: what the "Buffing" slot is doing (Healing, Restoring mana, Restoring
/// stamina, Buffing). Written by RynthAiPlugin every tick; never read by control flow.
/// Displays use ActivityArbiter.DisplayLabel, never this field alone.</summary>
[JsonIgnore] public string BuffingLabel = "Buffing";
[JsonIgnore] public bool IsRecordingNav;
public bool EnableBuffing = true;
@ -180,6 +184,18 @@ public sealed class LegacyUiSettings
public float OpenDoorRange = 5.0f;
public bool AutoUnlockDoors;
public int LootOwnership;
/// <summary>
/// Recover your own death corpse ("Corpse of &lt;you&gt;", identified by its "Killed by" line):
/// when it is within loot range the bot opens it and takes every item on it, whatever the
/// loot profile, Loot From, value or salvage rules say. On by default (owner, 2026-10-05);
/// a profile saved before this setting loads it as on.
/// </summary>
public bool LootOwnCorpse = 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>
public bool TravelToOwnCorpse;
public bool LootOnlyRareCorpses;
public bool PeaceModeWhenIdle = true;
public bool RebuffWhenIdle;
@ -197,6 +213,15 @@ public sealed class LegacyUiSettings
/// below RebuffSecondsRemaining only the expiring buff is recast.
/// </summary>
public int RebuffTopOffSecondsRemaining = 1200;
/// <summary>
/// Cast our own buff even when an item already gives that buff (a permanent, item-granted
/// enchantment at the same tier or higher). For servers with buff augments, where a player's
/// own cast is stronger or lasts longer than the item's. On by default: on retail the cost
/// is a few extra casts, while missing the buff is worse. A profile saved before this
/// setting existed loads it as on. Off = an item-granted buff at the tier we'd cast counts
/// as on for good (the behaviour before 2026-10-05).
/// </summary>
public bool CastBuffsOverItemBuffs = true;
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
/// <summary>
@ -828,6 +853,9 @@ public sealed class SettingsBridgePayload
public bool RebuffWhenIdle { get; set; }
public int RebuffSecondsRemaining { get; set; }
public int RebuffTopOffSecondsRemaining { get; set; } = 1200; // absent in older files
// 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; }
public int BuffMinSkillLevelTier1 { get; set; }
public int BuffMinSkillLevelTier2 { get; set; }
public int BuffMinSkillLevelTier3 { get; set; }
@ -850,6 +878,10 @@ public sealed class SettingsBridgePayload
public bool LootJumpEnabled { get; set; }
public int LootJumpHeight { get; set; }
public int LootOwnership { get; set; }
// 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? TravelToOwnCorpse { get; set; }
public bool EnableAutostack { get; set; }
public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default
public bool EnableCombineSalvage { get; set; }

View file

@ -187,6 +187,7 @@ internal sealed class LootEditorBridge
d.ItemName = facts.Name;
d.ClassName = LootItemRules.ClassName(facts.ObjectClass);
d.Stackable = facts.Stackable;
d.BuiltInReason = BuiltInSentence(Items.BuiltInKeep(id));
string inUse = InUse;
string target = req.ToOpenProfile && _session.IsOpen ? _session.Path : inUse;
@ -246,6 +247,7 @@ internal sealed class LootEditorBridge
}
else
d.OrderNote = $"Goes in at the end ({at + 1} of {count + 1}): no rule takes this item now, so at the end it only gets items no other rule wants.";
AppendBuiltIn(d);
if (s.IsDirty) return Refuse(d, $"The Loot Editor has unsaved changes in {d.TargetFile}. Save or discard them first.");
d.Ok = true;
@ -261,9 +263,30 @@ internal sealed class LootEditorBridge
{
d.Ok = false;
d.Error = error;
AppendBuiltIn(d);
return d;
}
/// <summary>
/// The popup's sentence for one of RynthAi's built-in keeps. "No rule matches" alone
/// misled: a wand Mana Tap had looted read as looted for no reason (2026-10-05).
/// </summary>
internal static string BuiltInSentence(LootBuiltInKeep? keep)
{
if (keep == null || keep.Reason.Length == 0) return string.Empty;
return keep.BeforeProfile
? $"RynthAi takes it before any loot profile rule: {keep.Reason}."
: $"No rule in the loot profile in use takes it, but RynthAi keeps it anyway: {keep.Reason}.";
}
// OrderNote is what every engine's popup (and /ra loot add) shows, so the reason rides on it;
// BuiltInReason carries it on its own for a face that wants it separately.
private static void AppendBuiltIn(LootEditItemDraft d)
{
if (d.BuiltInReason.Length == 0 || d.OrderNote.EndsWith(d.BuiltInReason, StringComparison.Ordinal)) return;
d.OrderNote = d.OrderNote.Length == 0 ? d.BuiltInReason : d.OrderNote + " " + d.BuiltInReason;
}
/// <summary>The editor's session when it has <paramref name="target"/> open, else a second one (fresh from disk).</summary>
private LootEditSession SessionFor(string target)
{
@ -321,4 +344,16 @@ internal sealed class LootItemHooks
public Func<uint, LootProfile, int> FirstMatchNative { get; set; } = (_, _) => -1;
/// <summary>A rule was added and saved: say so and reload the profile. Outside the bridge's lock.</summary>
public Action<LootEditItemDraft> Added { get; set; } = _ => { };
/// <summary>
/// One of RynthAi's built-in keeps that takes the item now with the loot profile in use
/// (the looter's own classification, run as a preview), or null.
/// </summary>
public Func<uint, LootBuiltInKeep?> BuiltInKeep { get; set; } = _ => null;
}
/// <summary>
/// A built-in keep: <see cref="Reason"/> says what and where to change it (ASCII);
/// <see cref="BeforeProfile"/> when it is checked ahead of the loot profile's rules
/// (Learn unknown spells, mana stones) rather than only when no rule matches (Mana Tap).
/// </summary>
internal sealed record LootBuiltInKeep(string Reason, bool BeforeProfile);

View file

@ -279,28 +279,38 @@ internal sealed class ScrollLearner
/// setting on, a scroll on a corpse whose spell the character doesn't know and can learn.
/// One copy per spell.
/// </summary>
public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel)
public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel) =>
ShouldLootFromCorpse(item, out ruleLabel, out _, preview: false);
// preview: the same answer with nothing recorded or logged (the loot popup asking why).
// why: the spell and why it is taken, in a few words.
public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel, out string why, bool preview)
{
ruleLabel = string.Empty;
why = string.Empty;
if (!_settings.ReadUnknownScrolls || !LooksLikeScroll(item)) return false;
ScrollJudgement j = Judge(item);
if (j.Verdict == ScrollVerdict.NoSpell) return false; // a book, a note: not ours to judge
if (!j.Learnable)
{
LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: {j.Why})");
if (!preview) LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: {j.Why})");
return false;
}
long now = NowMs();
if (OtherCopyTaken(j.SpellId, item.Id, now))
{
LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: another copy is already on its way)");
if (!preview) LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: another copy is already on its way)");
return false;
}
_approved[j.SpellId] = (item.Id, now);
LogItem(item.Id, $"[Learn] looting '{item.Name}' ({j.SpellName}: {j.Why})");
if (!preview)
{
_approved[j.SpellId] = (item.Id, now);
LogItem(item.Id, $"[Learn] looting '{item.Name}' ({j.SpellName}: {j.Why})");
}
ruleLabel = RuleLabel;
why = $"{j.SpellName}: {j.Why}";
return true;
}

View file

@ -303,7 +303,7 @@ public sealed partial class RynthAiPlugin
if (parts.Length < 3 || !float.TryParse(parts[2], out float degrees)) return false;
if (!Host.HasTurnToHeading) { ChatLine("[RynthAi] TurnToHeading not available."); return true; }
Host.TurnToHeading(degrees);
Host.TurnToHeadingBy("Command", degrees);
return true;
}
@ -470,7 +470,12 @@ public sealed partial class RynthAiPlugin
string itemName = argStr[..toIdx].Trim();
string targetName = argStr[(toIdx + 4)..].Trim();
var item = FindObject(itemName, inv: true, land: false, partial: partial);
// /mt give hands over the FIRST carried match (/ub give hands over all of them).
// Never worn or wielded gear: FindObject's inventory walk includes it.
var candidates = GiveCandidates(n => partial
? n.IndexOf(itemName, StringComparison.OrdinalIgnoreCase) >= 0
: string.Equals(n, itemName, StringComparison.OrdinalIgnoreCase));
var item = candidates.Count > 0 ? candidates[0] : null;
if (item == null) { ChatLine($"[RynthAi] Item not found: '{itemName}'"); return true; }
var target = FindObject(targetName, inv: false, land: true, partial: true);

View file

@ -249,6 +249,9 @@ internal sealed class ManaStoneManager
if (itemId != 0) _lootedForTap[itemId] = NowMs;
}
/// <summary>The looter picked this item up as "ManaTap" this session (it is waiting to be drained).</summary>
public bool WasLootedForTap(int itemId) => _lootedForTap.ContainsKey(itemId);
/// <summary>
/// Drops entries whose item has left the pack: drained (destroyed), sold, given
/// away, salvaged, dropped, or never arrived. Also drops items the player has
@ -685,7 +688,7 @@ internal sealed class ManaStoneManager
/// is unreliable for unappraised items, so we fall back to the name, matching
/// CombatManager/BuffManager.IsWandObject.
/// </summary>
private static bool IsWandLike(WorldObject item)
internal static bool IsWandLike(WorldObject item)
=> item.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(item.Name);
private static bool IsWandName(string name)

View file

@ -0,0 +1,279 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.Plugin.RynthAi.Maps;
/// <summary>
/// Writes each dungeon floor as a finished top-down raster to
/// C:\Games\RynthSuite\RynthAi\Maps\{landblock:X8}_{layer}.bin, which the RynthCore StatusAgent
/// serves at /map (re-encoded to PNG) for DrakRemote's dungeon map.
///
/// File format (must match the StatusAgent's MapService and the 81 plans baked before
/// 2026-09-28 by the old DungeonMapTexture): 20-byte header [uint32 Magic "XTMR" 0x524D5458,
/// int32 xMin, int32 yMin, int32 w, int32 h], then w*h little-endian ARGB uint32 pixels
/// (A&lt;&lt;24|R&lt;&lt;16|G&lt;&lt;8|B), 0.5 world units a pixel, row 0 = northernmost, 0 = empty.
/// xMin/yMin are grid-cell coordinates (world units * 2). The landblock in the file name is the
/// short form (cellId &gt;&gt; 16, e.g. 00006346_1.bin) and the layer is the index into the
/// landblock's ascending floor heights (DungeonMapUi.LayerZs), empty layers included.
///
/// This is the disk half of the old DungeonMapTexture only: no D3D9 textures. Each landblock
/// is baked at most once per session, on a pool thread, and a file that already holds the
/// same bytes is left alone (no mtime churn on the plans already there). Writes go to a temp
/// file that is then renamed over the target, so the agent never reads a half-written plan.
/// </summary>
internal static class DungeonMapBake
{
internal const uint Magic = 0x524D5458u; // "XTMR" - same constant as the StatusAgent's MapService
private const int MaxDim = 8192; // the agent refuses bigger rasters
/// <summary>Where plans go. A test points this at its own folder.</summary>
internal static string CacheDir { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
// Pixel colours, as the old DungeonMapTexture (and DungeonMapUi's former ImGui colours).
private static uint Argb(float r, float g, float b, float a) =>
((uint)(a * 255f) << 24) | ((uint)(r * 255f) << 16) | ((uint)(g * 255f) << 8) | (uint)(b * 255f);
private static readonly uint FillFlat = Argb(0.18f, 0.55f, 0.22f, 0.40f);
private static readonly uint FillSlopeUp = Argb(0.55f, 0.12f, 0.08f, 0.40f);
private static readonly uint FillSlopeDown = Argb(0.10f, 0.50f, 0.15f, 0.40f);
private static readonly uint EdgeFlat = Argb(0.55f, 0.80f, 1.00f, 1.00f);
private static readonly uint EdgeSlopeUp = Argb(1.00f, 0.35f, 0.25f, 1.00f);
private static readonly uint EdgeSlopeDown = Argb(0.25f, 1.00f, 0.35f, 1.00f);
internal enum SaveResult { Written, Unchanged, Failed }
// Landblocks already baked (or being baked) this session.
private static readonly ConcurrentDictionary<uint, byte> _requested = new();
// Messages from the pool thread, logged by the game-thread tick (DrainLog).
private static readonly ConcurrentQueue<string> _log = new();
/// <summary>Normalise to the short landblock id the file names use (0x63460000 -> 0x6346).</summary>
internal static uint ShortLandblock(uint landblock) =>
landblock > 0xFFFFu ? landblock >> 16 : landblock;
internal static bool WasRequested(uint landblock) => _requested.ContainsKey(ShortLandblock(landblock));
/// <summary>Messages queued by background bakes since the last call (game thread logs them).</summary>
internal static void DrainLog(Action<string> log)
{
while (_log.TryDequeue(out string? m)) log(m);
}
/// <summary>
/// Bake already-built floor grids (DungeonMapUi.RefreshMap) once per landblock. Returns at
/// once; the rasterise and disk work run on a pool thread. The dictionaries must not be
/// changed afterwards (RefreshMap builds new ones each time).
/// </summary>
internal static void Request(uint landblock, List<float>? zLayers,
Dictionary<float, Dictionary<(int, int), DungeonMapUi.CellType>>? floorCells)
{
if (zLayers is null || floorCells is null || floorCells.Count == 0) return;
uint lb = ShortLandblock(landblock);
if (lb == 0 || !_requested.TryAdd(lb, 0)) return;
Task.Run(() => BakeLogged(lb, zLayers, floorCells));
}
/// <summary>
/// Build the floor grids from the dat and bake them, once per landblock, on a pool thread.
/// For a landblock change indoors with no Radar or Dungeon Map panel open.
/// </summary>
internal static void RequestFromDat(DungeonLOS los, uint landblock)
{
uint lb = ShortLandblock(landblock);
if (lb == 0 || !_requested.TryAdd(lb, 0)) return;
Task.Run(() =>
{
try
{
var (zLayers, cells) = DungeonMapUi.BuildFloorCells(los, lb);
if (cells.Count == 0) return; // no floor geometry (not a dungeon, or no dat data)
BakeLogged(lb, zLayers, cells);
}
catch (Exception ex)
{
_requested.TryRemove(lb, out _);
_log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {ex.GetType().Name}: {ex.Message}");
}
});
}
private static void BakeLogged(uint lb, List<float> zLayers,
Dictionary<float, Dictionary<(int, int), DungeonMapUi.CellType>> floorCells)
{
try
{
var (written, unchanged, failed) = BakeLayers(CacheDir, lb, zLayers, floorCells);
// A layer that could not be written (file held open, disk full): let the next
// RefreshMap or re-entry try again instead of skipping it for the session.
if (failed > 0) _requested.TryRemove(lb, out _);
if (written > 0 || failed > 0)
_log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {written} written, {unchanged} unchanged, {failed} failed ({CacheDir})");
}
catch (Exception ex)
{
_requested.TryRemove(lb, out _);
_log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>Bake every non-empty layer of a landblock into <paramref name="dir"/>. Synchronous.</summary>
internal static (int Written, int Unchanged, int Failed) BakeLayers(string dir, uint landblock, List<float> zLayers,
Dictionary<float, Dictionary<(int, int), DungeonMapUi.CellType>> floorCells)
{
uint lb = ShortLandblock(landblock);
int written = 0, unchanged = 0, failed = 0;
foreach (var (layerZ, cells) in floorCells)
{
int idx = zLayers.IndexOf(layerZ);
if (idx < 0) continue;
byte[]? bytes = BuildFile(cells);
if (bytes is null) continue;
switch (SaveToDisk(dir, lb, idx, bytes))
{
case SaveResult.Written: written++; break;
case SaveResult.Unchanged: unchanged++; break;
default: failed++; break;
}
}
return (written, unchanged, failed);
}
internal static string FileName(uint landblock, int layerIdx) => $"{ShortLandblock(landblock):X8}_{layerIdx}.bin";
/// <summary>The whole .bin (header + pixels) for one layer's cells, or null if empty / too big.</summary>
internal static byte[]? BuildFile(Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells)
{
if (cells.Count == 0) return null;
int xMin = int.MaxValue, xMax = int.MinValue;
int yMin = int.MaxValue, yMax = int.MinValue;
foreach (var (gx, gy) in cells.Keys)
{
if (gx < xMin) xMin = gx; if (gx > xMax) xMax = gx;
if (gy < yMin) yMin = gy; if (gy > yMax) yMax = gy;
}
int w = xMax - xMin + 1, h = yMax - yMin + 1;
if (w <= 0 || h <= 0 || w > MaxDim || h > MaxDim) return null;
uint[] pixels = Rasterise(cells, xMin, yMax, w, h);
var bytes = new byte[20 + pixels.Length * 4];
var span = bytes.AsSpan();
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span, Magic);
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(4), xMin);
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(8), yMin);
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(12), w);
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(16), h);
for (int i = 0; i < pixels.Length; i++)
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(20 + i * 4), pixels[i]);
return bytes;
}
/// <summary>
/// One layer's cells as ARGB pixels: cells bordering empty space get the bright edge colour,
/// the rest the translucent fill, by cell type; empty = 0. Row 0 = northernmost (highest gy).
/// Unchanged from the old DungeonMapTexture.Rasterise.
/// </summary>
internal static uint[] Rasterise(Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells,
int xMin, int yMax, int w, int h)
{
var pixels = new uint[w * h];
foreach (var ((gx, gy), ctype) in cells)
{
bool isEdge = !cells.ContainsKey((gx + 1, gy))
|| !cells.ContainsKey((gx - 1, gy))
|| !cells.ContainsKey((gx, gy + 1))
|| !cells.ContainsKey((gx, gy - 1));
uint col = isEdge
? ctype switch
{
DungeonMapUi.CellType.SlopeUp => EdgeSlopeUp,
DungeonMapUi.CellType.SlopeDown => EdgeSlopeDown,
_ => EdgeFlat,
}
: ctype switch
{
DungeonMapUi.CellType.SlopeUp => FillSlopeUp,
DungeonMapUi.CellType.SlopeDown => FillSlopeDown,
_ => FillFlat,
};
pixels[(yMax - gy) * w + (gx - xMin)] = col;
}
return pixels;
}
/// <summary>
/// Write one plan unless the file already holds exactly these bytes. Temp file + rename, so a
/// reader sees the old plan or the new one, never a partial one. Never throws.
/// </summary>
internal static SaveResult SaveToDisk(string dir, uint landblock, int layerIdx, byte[] bytes)
{
string path = Path.Combine(dir, FileName(landblock, layerIdx));
string? tmp = null;
try
{
if (SameContent(path, bytes)) return SaveResult.Unchanged;
Directory.CreateDirectory(dir);
// Unique per process and call: two clients in the same dungeon can bake at once.
string tmpPath = path + "." + Environment.ProcessId.ToString("X") + "." + Guid.NewGuid().ToString("N").Substring(0, 8) + ".tmp";
tmp = tmpPath;
using (var fs = new FileStream(tmpPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
fs.Write(bytes, 0, bytes.Length);
// The agent may hold the target open for a moment (FileShare.ReadWrite, not Delete),
// which makes the replace fail; try a few times.
for (int attempt = 0; ; attempt++)
{
try
{
File.Move(tmpPath, path, overwrite: true);
tmp = null;
return SaveResult.Written;
}
catch (IOException) when (attempt < 4)
{
if (SameContent(path, bytes)) return SaveResult.Unchanged; // another client won
Thread.Sleep(100);
}
catch (UnauthorizedAccessException) when (attempt < 4)
{
Thread.Sleep(100);
}
}
}
catch
{
return SaveResult.Failed;
}
finally
{
if (tmp != null) { try { File.Delete(tmp); } catch { } }
}
}
private static bool SameContent(string path, byte[] bytes)
{
try
{
var fi = new FileInfo(path);
if (!fi.Exists || fi.Length != bytes.Length) return false;
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
var buf = new byte[64 * 1024];
int off = 0;
while (off < bytes.Length)
{
int got = fs.Read(buf, 0, Math.Min(buf.Length, bytes.Length - off));
if (got <= 0) return false;
if (!buf.AsSpan(0, got).SequenceEqual(bytes.AsSpan(off, got))) return false;
off += got;
}
return true;
}
catch { return false; }
}
}

View file

@ -2543,7 +2543,7 @@ internal sealed class ExpressionEngine
if (!_castCombatTornDown && (mode == CombatMode.Melee || mode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletely();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Meta");
_castCombatTornDown = true;
_host.Log($"[MetaCast] CancelAttack+StopCompletely before wand equip (mode was {mode})");
}
@ -2882,7 +2882,7 @@ internal sealed class ExpressionEngine
if (!MotionValues.TryGetValue(motionArg, out uint motionVal)) return "0";
bool on = ToDouble(stateArg) != 0;
_wantedMotion[motionArg] = on;
return _host.SetMotion(motionVal, on) ? "1" : "0";
return _host.SetMotionBy("Meta", motionVal, on) ? "1" : "0";
}
private string EvalGetMotion(string motionArg)
@ -2899,7 +2899,7 @@ internal sealed class ExpressionEngine
if (_host.HasSetMotion)
{
foreach (var kvp in MotionValues)
_host.SetMotion(kvp.Value, false);
_host.SetMotionBy("Meta", kvp.Value, false);
}
_wantedMotion.Clear();
return "1";
@ -3305,6 +3305,8 @@ internal sealed class ExpressionEngine
["StopMacroOnDeath"] = (() => B(s.StopMacroOnDeath), v => s.StopMacroOnDeath = ToDouble(v) != 0),
["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),
["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0),
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0),
["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0),
@ -3340,6 +3342,7 @@ internal sealed class ExpressionEngine
["ManaStoneKeepCount"] = (() => I(s.ManaStoneKeepCount), v => { if (int.TryParse(v, out int i)) s.ManaStoneKeepCount = i; }),
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0),
["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0),

View file

@ -367,7 +367,7 @@ internal sealed class NavigationEngine
if (Now - _stopRequestedAt >= (long)StopDebounceMs)
{
_host.SetAutoRun(false);
_host.SetAutoRunBy("Nav", false);
_isMovingForward = false;
_isTurning = false;
_hasStopped = true;
@ -444,16 +444,16 @@ internal sealed class NavigationEngine
// Handle active settle period
if (_globalSettling)
{
_host.SetAutoRun(false);
_host.SetAutoRunBy("Nav", false);
ClearTurnMotions();
if (_host.HasStopCompletely) _host.StopCompletely();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav");
_isMovingForward = false;
_isTurning = false;
if (Now - _globalSettleStart > (long)PostTeleportMs)
{
_host.Log($"Nav: global post-teleport settle done ({PostTeleportMs:F0}ms)");
if (_host.HasStopCompletely) _host.StopCompletely();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav");
if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount();
if (_combatManager != null) _combatManager.BusyCount = 0;
_hasGoodHeading = false;
@ -632,7 +632,7 @@ internal sealed class NavigationEngine
_offTrackSince = 0;
RememberFiredPortalAction();
ResetPortalState();
_host.SetAutoRun(false);
_host.SetAutoRunBy("Nav", false);
ClearTurnMotions();
_isMovingForward = false;
_isTurning = false;
@ -999,11 +999,11 @@ internal sealed class NavigationEngine
int want = absError <= DeadZone ? 0 : (error > 0 ? 1 : -1);
if (want != _tier1TurnDir)
{
if (_tier1TurnDir > 0) _host.StopMovement(MotionTurnRight, 0);
else if (_tier1TurnDir < 0) _host.StopMovement(MotionTurnLeft, 0);
if (_tier1TurnDir > 0) _host.StopMovementBy("Nav", MotionTurnRight, 0);
else if (_tier1TurnDir < 0) _host.StopMovementBy("Nav", MotionTurnLeft, 0);
if (want > 0) _host.DoMovement(MotionTurnRight, (float)Tier1TurnSpeed, 0);
else if (want < 0) _host.DoMovement(MotionTurnLeft, (float)Tier1TurnSpeed, 0);
if (want > 0) _host.DoMovementBy("Nav", MotionTurnRight, (float)Tier1TurnSpeed, 0);
else if (want < 0) _host.DoMovementBy("Nav", MotionTurnLeft, (float)Tier1TurnSpeed, 0);
_tier1TurnDir = want;
}
@ -1019,14 +1019,14 @@ internal sealed class NavigationEngine
double newHeading = currentDeg + step;
if (newHeading >= 360.0) newHeading -= 360.0;
else if (newHeading < 0.0) newHeading += 360.0;
_host.TurnToHeading((float)newHeading);
_host.TurnToHeadingBy("Nav", (float)newHeading);
}
}
// ── Heartbeat: periodically re-assert autorun ───────────────────────
if (_isMovingForward && Now - _lastHeartbeat > (long)HeartbeatMs)
{
_host.SetAutoRun(true);
_host.SetAutoRunBy("Nav", true);
_lastHeartbeat = Now;
}
}
@ -1050,13 +1050,13 @@ internal sealed class NavigationEngine
if (error > 0)
{
_host.SetMotion(MotionTurnRight, true);
_host.SetMotion(MotionTurnLeft, false);
_host.SetMotionBy("Nav", MotionTurnRight, true);
_host.SetMotionBy("Nav", MotionTurnLeft, false);
}
else
{
_host.SetMotion(MotionTurnLeft, true);
_host.SetMotion(MotionTurnRight, false);
_host.SetMotionBy("Nav", MotionTurnLeft, true);
_host.SetMotionBy("Nav", MotionTurnRight, false);
}
return;
}
@ -1067,13 +1067,13 @@ internal sealed class NavigationEngine
StopForward();
if (error > 0)
{
_host.SetMotion(MotionTurnRight, true);
_host.SetMotion(MotionTurnLeft, false);
_host.SetMotionBy("Nav", MotionTurnRight, true);
_host.SetMotionBy("Nav", MotionTurnLeft, false);
}
else
{
_host.SetMotion(MotionTurnLeft, true);
_host.SetMotion(MotionTurnRight, false);
_host.SetMotionBy("Nav", MotionTurnLeft, true);
_host.SetMotionBy("Nav", MotionTurnRight, false);
}
_isTurning = true;
return;
@ -1098,13 +1098,13 @@ internal sealed class NavigationEngine
if (_lastTurnDir > 0)
{
_host.SetMotion(MotionTurnRight, true);
_host.SetMotion(MotionTurnLeft, false);
_host.SetMotionBy("Nav", MotionTurnRight, true);
_host.SetMotionBy("Nav", MotionTurnLeft, false);
}
else
{
_host.SetMotion(MotionTurnLeft, true);
_host.SetMotion(MotionTurnRight, false);
_host.SetMotionBy("Nav", MotionTurnLeft, true);
_host.SetMotionBy("Nav", MotionTurnRight, false);
}
}
else
@ -1115,7 +1115,7 @@ internal sealed class NavigationEngine
if (_isMovingForward && Now - _lastHeartbeat > (long)HeartbeatMs)
{
_host.SetAutoRun(true);
_host.SetAutoRunBy("Nav", true);
_lastHeartbeat = Now;
}
}
@ -1742,7 +1742,7 @@ internal sealed class NavigationEngine
case PortalState.Settling:
// Keep clearing motions until settled
ClearTurnMotions();
_host.SetAutoRun(false);
_host.SetAutoRunBy("Nav", false);
_isMovingForward = false;
if (Now - _portalStateStart > (long)SettleDelayMs)
@ -1861,9 +1861,9 @@ internal sealed class NavigationEngine
// Hammer-stop to cancel any lingering UseItem walk and clear
// the client's internal action queue (prevents stuck hourglass
// cursor when UseObject is interrupted by portal teleport).
_host.SetAutoRun(false);
_host.SetAutoRunBy("Nav", false);
ClearTurnMotions();
if (_host.HasStopCompletely) _host.StopCompletely();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav");
_isMovingForward = false;
_isTurning = false;
@ -1874,7 +1874,7 @@ internal sealed class NavigationEngine
// Force-clear the client's internal busy count (hourglass cursor)
// and our tracked busy count. Portal teleport interrupts actions
// without firing the matching DecrementBusyCount callback.
if (_host.HasStopCompletely) _host.StopCompletely();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav");
if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount();
if (_combatManager != null) _combatManager.BusyCount = 0;
@ -2096,13 +2096,13 @@ internal sealed class NavigationEngine
double step = Math.Clamp(err, -MaxStepDeg, MaxStepDeg);
double newHeading = curDeg + step;
if (newHeading >= 360.0) newHeading -= 360.0; else if (newHeading < 0.0) newHeading += 360.0;
_host.TurnToHeading((float)newHeading);
_host.TurnToHeadingBy("Nav", (float)newHeading);
// Run only once roughly aligned, so we don't arc wide on a big turn.
if (Math.Abs(err) <= BigTurnEnter) StartForward(); else StopForward();
}
else
{
_host.TurnToHeading((float)desiredDeg);
_host.TurnToHeadingBy("Nav", (float)desiredDeg);
StartForward();
}
}
@ -2220,7 +2220,7 @@ internal sealed class NavigationEngine
if (escapeHeading >= 360.0) escapeHeading -= 360.0; else if (escapeHeading < 0.0) escapeHeading += 360.0;
_host.Log($"Nav: stuck x{_stuckCount} — escape burst {offset:+0;-0}° for {RecoveryBurstMs:F0}ms.");
_host.TurnToHeading((float)escapeHeading);
_host.TurnToHeadingBy("Nav", (float)escapeHeading);
StartForward();
_recoveryKind = RecoveryKind.Escape;
_recoveryUntil = Now + (long)RecoveryBurstMs;
@ -2767,7 +2767,7 @@ internal sealed class NavigationEngine
long now = Environment.TickCount64;
if (!_isMovingForward || now - _lastForwardAssertMs >= ForwardReassertMs)
{
_host.SetAutoRun(true);
_host.SetAutoRunBy("Nav", true);
_isMovingForward = true;
_lastForwardAssertMs = now;
}
@ -2775,15 +2775,15 @@ internal sealed class NavigationEngine
private void StopForward()
{
_host.SetAutoRun(false);
_host.SetAutoRunBy("Nav", false);
_isMovingForward = false;
}
private void ClearTurnMotions()
{
// Mode-0/legacy motion keys are local cmdinterp toggles — cheap, always clear.
_host.SetMotion(MotionTurnRight, false);
_host.SetMotion(MotionTurnLeft, false);
_host.SetMotionBy("Nav", MotionTurnRight, false);
_host.SetMotionBy("Nav", MotionTurnLeft, false);
// Tier 1 turns are CM_Movement *server events* (0xF661). Only send a
// StopMovement when a turn is actually in flight — this method is called
@ -2791,7 +2791,7 @@ internal sealed class NavigationEngine
// send floods the server. _tier1TurnDir tracks the one active direction.
if (_tier1TurnDir != 0 && _host.HasStopMovement)
{
_host.StopMovement(_tier1TurnDir > 0 ? MotionTurnRight : MotionTurnLeft, 0);
_host.StopMovementBy("Nav", _tier1TurnDir > 0 ? MotionTurnRight : MotionTurnLeft, 0);
_tier1TurnDir = 0;
}
}
@ -2850,7 +2850,7 @@ internal sealed class NavigationEngine
if (!_host.HasTurnToHeading) return true;
if (!TryGetQuaternionHeading(out float curDeg))
{
_host.TurnToHeading((float)desiredDeg);
_host.TurnToHeadingBy("Nav", (float)desiredDeg);
return true;
}
long nowTicks = System.Diagnostics.Stopwatch.GetTimestamp();
@ -2862,7 +2862,7 @@ internal sealed class NavigationEngine
double maxStep = Math.Max(10.0, _settings.NavTurnRateDegPerSec) * Math.Max(dt, 0.01);
double newHeading = curDeg + Math.Clamp(err, -maxStep, maxStep);
if (newHeading >= 360.0) newHeading -= 360.0; else if (newHeading < 0.0) newHeading += 360.0;
_host.TurnToHeading((float)newHeading);
_host.TurnToHeadingBy("Nav", (float)newHeading);
double abs = Math.Abs(err);
if (_servoTurning) { if (abs <= BigTurnExit) _servoTurning = false; }

View file

@ -159,6 +159,34 @@ public static unsafe class PluginExports
}
}
// ── Hot-reload deferral (2026-10-05) ─────────────────────────────────────────
// The engine calls this on its reload thread before it tears itself down for a hot reload:
// a non-empty text ("in combat (a monster engaged, ...)") makes it wait and ask again, up to
// its cap. Fixed signature, const char* (void); null or "" = safe. Optional: an engine that
// doesn't know it simply reloads, and a plugin without it never holds a reload. Per-thread
// buffer (same reasoning as _snapshotPtr).
[ThreadStatic] private static IntPtr _reloadBlockerPtr;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginReloadBlocker", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr ReloadBlocker()
{
try
{
string reason = Runtime.Plugin?.ReloadBlocker ?? "";
if (reason.Length == 0) return IntPtr.Zero;
IntPtr newPtr = Marshal.StringToHGlobalAnsi(reason);
IntPtr oldPtr = _reloadBlockerPtr;
_reloadBlockerPtr = newPtr;
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// ── Full-inventory bridge (read-only remote inventory viewer, P1) ───────────
// Dedicated export (NOT folded into the 150ms status snapshot) so 100s of items never ride the
// hot path. The RynthRemote plugin polls this on its own slower cadence (P2). Per-thread buffer

View file

@ -68,6 +68,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it");
ChatLine("[RynthAi] /ra jump[swzxc] [heading] [holdtime] — jump with optional face/direction (s=run w=fwd x=back z=strafeL c=strafeR)");
ChatLine("[RynthAi] /ra corpseinfo — show corpse range/open diagnostics");
ChatLine("[RynthAi] /ra owncorpse [go|stop] — where your corpse is; travel back to it, or stop");
ChatLine("[RynthAi] /ra corpsecheck — explain whether a corpse would be looted");
ChatLine("[RynthAi] /ra corpseopen — force the nearest corpse open flow");
ChatLine("[RynthAi] /ra fellowinfo — show fellowship tracker state");
@ -1209,8 +1210,8 @@ public sealed partial class RynthAiPlugin
}
// Stop any active turn motion so the character doesn't keep spinning
Host.SetMotion(0x6500000D, false); // TurnRight
Host.SetMotion(0x6500000E, false); // TurnLeft
Host.SetMotionBy("Command", 0x6500000D, false); // TurnRight
Host.SetMotionBy("Command", 0x6500000E, false); // TurnLeft
if (!Host.HasGetPlayerPose || !Host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _))
{
@ -1517,9 +1518,38 @@ public sealed partial class RynthAiPlugin
FirstMatchUtl = FirstLootRuleFor,
FirstMatchNative = FirstLootRuleFor,
Added = OnLootRuleAdded,
BuiltInKeep = LootBuiltInKeepFor,
},
};
/// <summary>
/// Why RynthAi's looting takes the item without a loot profile rule, for the "Add to
/// loot profile" popup: the looter's own ClassifyItemAgainstProfile as a preview (nothing
/// recorded), so the answer is exactly what [LootEval] would tag. An item already in the
/// pack that Mana Tap looted earlier says so even when the tap quota is full now.
/// </summary>
private Loot.LootBuiltInKeep? LootBuiltInKeepFor(uint itemId)
{
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
LegacyUiSettings? settings = _dashboard?.Settings;
if (wo == null || settings == null) return null;
try
{
if (ClassifyLootItem(wo, settings, preview: true, out string action, out _, out _, out string builtIn)
&& builtIn.Length > 0)
return new Loot.LootBuiltInKeep(builtIn, BeforeProfile: action != ManaTapActionLabel);
if (_manaStoneManager?.WasLootedForTap(wo.Id) == true)
return new Loot.LootBuiltInKeep(
"it was looted for Mana Tap, to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping",
BeforeProfile: false);
}
catch (Exception ex)
{
Host.Log($"[LootAdd] built-in keep check failed for 0x{itemId:X8}: {ex.GetType().Name}: {ex.Message}");
}
return null;
}
/// <summary>
/// The Loot Editor saved <paramref name="path"/>: drop the cached copies and,
/// when it is the loot profile in use, load it again now (its chat line says so).
@ -2121,7 +2151,7 @@ public sealed partial class RynthAiPlugin
if (Host.HasForceResetBusyCount)
Host.ForceResetBusyCount();
if (Host.HasStopCompletely)
Host.StopCompletely();
Host.StopCompletelyBy("Command");
// Reset all tracked counts — engine, plugin, combat, buff
_busyCount = 0;
_busyCountLastIncrementAt = 0;
@ -2144,7 +2174,7 @@ public sealed partial class RynthAiPlugin
if (Host.HasCancelAttack) Host.CancelAttack();
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
if (Host.HasStopCompletely) Host.StopCompletely();
if (Host.HasStopCompletely) Host.StopCompletelyBy("Command");
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
// The item-action lock itself is not the busy count: AC refuses every use,
// equip and move while its pending-item-request slot or attacking flag is
@ -2409,6 +2439,38 @@ public sealed partial class RynthAiPlugin
private enum GiveItemMatch { Exact, Partial, Regex }
/// <summary>
/// Hands <paramref name="amount"/> of an item to a player or NPC with AC's give action
/// (Event_GiveObjectRequest) when the engine has it; MoveItemExternal is move-to-container
/// and silently does nothing for an NPC. amount 0 or the whole stack = the whole object.
/// </summary>
internal bool GiveItem(uint itemId, uint targetId, int amount, int stackSize)
{
if (Host.HasGiveObjectTo)
return Host.GiveObjectTo(itemId, targetId, amount <= 0 || amount >= stackSize ? 0 : amount);
return Host.MoveItemExternal(itemId, targetId, Math.Max(1, amount));
}
/// <summary>
/// Carried items a give may hand over, in pack order: never worn or wielded gear. Walks the
/// live inventory, then every known object the client says the player carries (the live walk
/// can miss items off AC's main thread, as FindObject notes).
/// </summary>
private List<WorldObject> GiveCandidates(Func<string, bool> nameMatches)
{
var found = new List<WorldObject>();
var seen = new HashSet<int>();
if (_objectCache == null) return found;
foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: true))
if (nameMatches(wo.Name) && !WorldObjectCache.IsWieldedByPlayer(Host, wo) && seen.Add(wo.Id))
found.Add(wo);
foreach (var wo in _objectCache.AllKnownObjects())
if (!seen.Contains(wo.Id) && nameMatches(wo.Name) && IsCarriedByPlayer(wo.Id)
&& !WorldObjectCache.IsWieldedByPlayer(Host, wo) && seen.Add(wo.Id))
found.Add(wo);
return found;
}
private void HandleGiveCommand(string[] parts, GiveItemMatch itemMatch, bool partialPlayer, bool allItems = false)
{
if (_objectCache == null) { ChatLine("[RynthAi] Object cache not ready."); return; }
@ -2463,22 +2525,15 @@ public sealed partial class RynthAiPlugin
catch { ChatLine($"[RynthAi] Invalid regex: {itemPart}"); return; }
}
// Collect matching inventory stacks
var matches = new List<WorldObject>();
foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: true))
// Collect matching carried stacks (never worn or wielded gear)
var matches = GiveCandidates(name => itemMatch switch
{
// GetDirectInventory includes worn and wielded gear; never give that away.
if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) continue;
bool hit = itemMatch switch
{
GiveItemMatch.Exact => string.Equals(wo.Name, itemPart, StringComparison.OrdinalIgnoreCase),
GiveItemMatch.Partial => wo.Name.IndexOf(itemPart, StringComparison.OrdinalIgnoreCase) >= 0,
GiveItemMatch.Regex => rx!.IsMatch(wo.Name),
_ => false,
};
if (hit) matches.Add(wo);
if (matches.Count >= maxCount) break;
}
GiveItemMatch.Exact => string.Equals(name, itemPart, StringComparison.OrdinalIgnoreCase),
GiveItemMatch.Partial => name.IndexOf(itemPart, StringComparison.OrdinalIgnoreCase) >= 0,
GiveItemMatch.Regex => rx!.IsMatch(name),
_ => false,
});
if (!allItems && matches.Count > maxCount) matches.RemoveRange(maxCount, matches.Count - maxCount);
if (matches.Count == 0) { ChatLine($"[RynthAi] No items found matching '{itemPart}'"); return; }
@ -2509,7 +2564,8 @@ public sealed partial class RynthAiPlugin
}
if (gives.Count == 1)
{
Host.MoveItemExternal((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount);
GiveItem((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount,
Math.Max(1, gives[0].Item.Values(LongValueKey.StackCount, 1)));
ChatLine($"[RynthAi] Giving {gives[0].Amount} x '{gives[0].Item.Name}' to {target.Name}");
}
else
@ -2523,7 +2579,7 @@ public sealed partial class RynthAiPlugin
{
var item = matches[0];
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
Host.MoveItemExternal((uint)item.Id, (uint)target.Id, stackSize);
GiveItem((uint)item.Id, (uint)target.Id, stackSize, stackSize);
ChatLine($"[RynthAi] Giving '{item.Name}' to {target.Name}");
}
}

View file

@ -0,0 +1,687 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>What <see cref="RynthAiPlugin.MatchOwnDeathCorpse"/> made of a corpse.</summary>
internal enum OwnCorpseMatch
{
/// <summary>Not your death corpse.</summary>
No,
/// <summary>Named "Corpse of &lt;you&gt;", but its ID (the "Killed by" line) hasn't landed yet.</summary>
Pending,
/// <summary>Your death corpse.</summary>
Yes,
}
/// <summary>
/// Own-corpse recovery (owner, 2026-10-05: "It needs to loot your corpse and every item on it.
/// If it's a setting default to true please").
///
/// Recover My Corpse (LootOwnCorpse, default on): when your own death corpse is within loot range
/// the looter opens it and takes every item on it, one at a time with the normal looter's
/// pick-up confirmation, ignoring the loot profile, Loot From, value and salvage rules and the
/// weapon-swap free-slot reserve (only "no pack has a slot at all" stops it). It beats any other
/// corpse in range but not combat (the arbiter's Looting slot, loot starvation as usual).
///
/// It is identified as: name exactly "Corpse of &lt;your name&gt;" (ACE names a player's corpse
/// "Corpse of " + the player's full name, GM sigil included; character names are unique per
/// server, so no other player's corpse can carry it and a pet's corpse carries the pet's name),
/// AND an identified LongDesc that is the server's "Killed by X." line with X not you (a death
/// corpse is never killed by its own victim, so a namesake monster you killed is not it). The
/// corpse's owner (the Victim instance id) is not sent to clients by ACE, so it can't be checked.
/// Until the ID lands a corpse with your name is held, never looted by the profile meanwhile.
///
/// The death spot (position at the death) is remembered and logged, and with Travel Back To My
/// Corpse (TravelToOwnCorpse, default off) the bot walks back there with RynthNav after the
/// respawn: /rnav go &lt;coords&gt; through the engine's plugin-command broker, the way RynthRemote's
/// Travel tab does. RynthNav routes on the map only, so this works for outdoor deaths only.
/// RynthNav walks on its own and does not fight, so whenever RynthAi wants the tick (combat,
/// buffing, looting, salvage) the walk is stopped and RynthAi does that; it resumes once RynthAi
/// is idle again. Gives up on no progress or a timeout, and says why.
/// </summary>
public sealed partial class RynthAiPlugin
{
internal const string OwnCorpsePrefix = "Corpse of ";
// ── Identifying it ───────────────────────────────────────────────────────
/// <summary>
/// Is this your death corpse? Pure (tests call it directly). <paramref name="myName"/> is the
/// player object's name as the client has it (with a GM sigil if any, as the corpse name has).
/// </summary>
internal static OwnCorpseMatch MatchOwnDeathCorpse(string? corpseName, string? myName, string? longDesc)
{
if (string.IsNullOrWhiteSpace(myName) || string.IsNullOrEmpty(corpseName))
return OwnCorpseMatch.No;
if (!string.Equals(corpseName, OwnCorpsePrefix + myName, StringComparison.Ordinal))
return OwnCorpseMatch.No;
if (string.IsNullOrWhiteSpace(longDesc))
return OwnCorpseMatch.Pending;
// The server writes exactly "Killed by X." on every corpse it makes for a death.
if (!longDesc.TrimStart().StartsWith("Killed by ", StringComparison.OrdinalIgnoreCase))
return OwnCorpseMatch.No;
string? killer = ExtractCorpseKillerName(longDesc);
if (string.IsNullOrWhiteSpace(killer))
return OwnCorpseMatch.No;
if (NormalizeCharName(killer).Equals(NormalizeCharName(myName), StringComparison.OrdinalIgnoreCase))
return OwnCorpseMatch.No; // your own kill of a namesake, not your death corpse
return OwnCorpseMatch.Yes;
}
/// <summary>Recover My Corpse is on and this corpse id is your identified death corpse.</summary>
private bool IsOwnDeathCorpseId(LegacyUiSettings? settings, int corpseId)
{
if (settings == null || !settings.LootOwnCorpse || corpseId == 0 || _objectCache == null)
return false;
WorldObject? corpse = _objectCache[corpseId];
if (corpse == null)
return false;
return MatchOwnDeathCorpse(corpse.Name, GetPlayerNameForLootOwnership(),
corpse.Values(StringValueKey.LongDesc, string.Empty)) == OwnCorpseMatch.Yes;
}
// A corpse with your name waiting for its ID: asked again every OwnCorpseIdRetryMs (the
// general corpse ID request goes out once per corpse; a lost answer must not strand it).
private readonly Dictionary<int, long> _ownCorpseIdRequestedAt = new();
private const long OwnCorpseIdRetryMs = 5_000;
private void RequestOwnCorpseId(int corpseId)
{
long now = CorpseNowMs;
if (!_ownCorpseIdRequestedAt.TryGetValue(corpseId, out long last))
{
_ownCorpseIdRequestedAt[corpseId] = now; // the general request just went out
LootDiag($"[RynthAi] Own corpse: 0x{(uint)corpseId:X8} is named like yours; waiting for its ID to confirm it.");
return;
}
if (now - last < OwnCorpseIdRetryMs || !Host.HasRequestId)
return;
_ownCorpseIdRequestedAt[corpseId] = now;
Host.RequestId(unchecked((uint)corpseId));
}
/// <summary>Your identified death corpse within <paramref name="maxMeters"/> (not completed, not cooling down).</summary>
private bool TryFindOwnCorpseInRange(double maxMeters, out WorldObject? corpse)
{
corpse = null;
var settings = _dashboard?.Settings;
if (settings == null || !settings.LootOwnCorpse || _objectCache == null || _playerId == 0)
return false;
string myName = GetPlayerNameForLootOwnership();
if (myName.Length == 0)
return false;
string wanted = OwnCorpsePrefix + myName;
long now = CorpseNowMs;
int playerId = unchecked((int)_playerId);
double best = double.MaxValue;
foreach (WorldObject candidate in _objectCache.GetLandscapeObjects())
{
if (candidate.ObjectClass != AcObjectClass.Corpse || !string.Equals(candidate.Name, wanted, StringComparison.Ordinal))
continue;
if (_completedCorpses.ContainsKey(candidate.Id))
continue;
if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long until) && until > now)
continue;
if (!EvaluateCorpseLootDecision(candidate).IsOwnDeathCorpse)
continue;
double d = _objectCache.Distance(playerId, candidate.Id);
if (d > maxMeters || d >= best)
continue;
best = d;
corpse = candidate;
}
return corpse != null;
}
/// <summary>
/// The pack gates (Stop Looting When Pack Full, the weapon-swap reserve) don't hold your own
/// corpse back: only "no pack has a free slot at all" does, since then nothing can move.
/// </summary>
private bool OwnCorpseBypassesPackGate(LegacyUiSettings settings, double maxMeters)
=> settings.LootOwnCorpse && !IsPackFull() && TryFindOwnCorpseInRange(maxMeters, out _);
// ── Recovering it ────────────────────────────────────────────────────────
private int _ownRecoveryCorpseId; // the own corpse this recovery is about (kept across pauses)
private int _ownRecoveryTotal; // items on it when first opened
private int _ownRecoveryTaken; // confirmed moved into a pack
private int _ownRecoveryRounds; // opens that ended with items that would not move
private readonly HashSet<int> _ownCorpseNoRoomSaid = new();
internal const int OwnCorpseMaxAbandons = 5; // timeouts before it is written off
private const int OwnCorpseMaxRounds = 3; // reopen rounds for items that would not move
private const long OwnCorpseNoRoomPauseMs = 60_000; // no pack has a slot: look again after this
private const long OwnCorpseRetryPauseMs = 30_000; // items would not move: reopen after this
private const long OwnCorpseBusyWaitMs = 1_000; // hold a pickup this long behind a busy count
private const long OwnCorpseSettleMs = 1_000; // after the last pickup, before judging what is left
/// <summary>
/// One tick of recovering your own corpse (it is open and its contents are listed): the next
/// item still on it is moved into a pack; the normal pick-up confirmation in
/// TickPendingCorpsePickup confirms it. Then the corpse is closed and completed.
/// </summary>
private void TickOwnCorpseRecovery(LegacyUiSettings settings, int corpseId, List<WorldObject> items, long openAge, long now)
{
if (items.Count == 0)
{
if (openAge < Math.Max(200, settings.LootEmptyCorpseMs))
return;
if (_ownRecoveryCorpseId != corpseId)
BeginOwnCorpseRecovery(corpseId, 0);
FinishOwnCorpseRecovery(corpseId, items);
return;
}
if (_ownRecoveryCorpseId != corpseId)
BeginOwnCorpseRecovery(corpseId, items.Count);
WorldObject? next = null;
int remaining = 0;
foreach (WorldObject item in items)
{
if (item.Id == 0 || _processedCorpseItems.Contains(item.Id))
continue;
remaining++;
next ??= item;
}
if (next == null)
{
// Every item was tried. Let the last confirmed move leave the corpse's list first.
if (_lastLootActionAt != 0 && now - _lastLootActionAt < OwnCorpseSettleMs)
return;
FinishOwnCorpseRecovery(corpseId, items);
return;
}
// One item at a time, as the looter does: wait out a busy count from our last action,
// but only briefly (CheckBusyTimeout clears a leaked one).
if (_busyCount > 0 && _lastLootActionAt != 0 && now - _lastLootActionAt < OwnCorpseBusyWaitMs)
return;
string name = string.IsNullOrWhiteSpace(next.Name) ? $"0x{(uint)next.Id:X8}" : next.Name;
_currentLootItemId = next.Id;
Host.SelectItem(unchecked((uint)next.Id));
LootDiag($"[RynthAi] Own corpse: taking 0x{(uint)next.Id:X8} '{name}' ({remaining} left on 0x{(uint)corpseId:X8}).");
LootPickupResult pickup = SendLootPickup(next.Id, name, corpseId);
if (pickup == LootPickupResult.NoRoom || pickup == LootPickupResult.Refused)
return; // SendLootPickup paused the corpse / left the item
if (pickup != LootPickupResult.Moved && pickup != LootPickupResult.Used)
{
if (_busyCount > 0)
return;
LootDiag($"[RynthAi] Own corpse: the move of 0x{(uint)next.Id:X8} was not sent.");
if (IncrementCorpseItemAttempt(next.Id) >= 3)
_processedCorpseItems.Add(next.Id);
ResetCurrentLootItem();
_lastLootActionAt = now;
return;
}
_currentLootItemMovePending = true;
_currentLootItemMoveRequestedAt = now;
_currentLootItemMoveAttempts = 1;
_currentLootItemActionLabel = "Recover";
_currentLootItemName = name;
_currentLootItemIsSalvage = false; // never salvage your own things
_lastLootActionAt = now;
_corpseTargetSince = now; // progress: a long recovery must not hit the corpse timeout
}
private void BeginOwnCorpseRecovery(int corpseId, int itemCount)
{
_ownRecoveryCorpseId = corpseId;
_ownRecoveryTotal = itemCount;
_ownRecoveryTaken = 0;
_ownRecoveryRounds = 0;
_ownCorpseNoRoomSaid.Remove(corpseId);
// Anything the profile looter passed over before the corpse was known to be yours
// (opened by hand before its ID landed) is taken now; items already moved have left it.
_processedCorpseItems.Clear();
_corpseItemAttempts.Clear();
if (itemCount > 0)
OwnCorpseSay($"[RynthAi] Own corpse: recovering {itemCount} item{(itemCount == 1 ? "" : "s")}.");
}
/// <summary>A pick-up from your corpse was confirmed (ConfirmCurrentLootItemMoved).</summary>
private void NoteOwnCorpseItemRecovered(long now)
{
_ownRecoveryTaken++;
_corpseTargetSince = now;
}
private void FinishOwnCorpseRecovery(int corpseId, List<WorldObject> items)
{
var left = items.Where(i => i.Id != 0).ToList();
if (left.Count == 0)
{
OwnCorpseSay(_ownRecoveryTaken > 0
? $"[RynthAi] Own corpse: recovered everything ({_ownRecoveryTaken} item{(_ownRecoveryTaken == 1 ? "" : "s")})."
: "[RynthAi] Own corpse: there was nothing on it to recover.");
MarkDeathSpotRecovered();
_ownRecoveryCorpseId = 0;
MarkCorpseCompleted(corpseId);
return;
}
_ownRecoveryRounds++;
string names = string.Join(", ", left.Take(5).Select(i => string.IsNullOrWhiteSpace(i.Name) ? $"0x{(uint)i.Id:X8}" : i.Name))
+ (left.Count > 5 ? ", ..." : "");
if (_ownRecoveryRounds >= OwnCorpseMaxRounds)
{
OwnCorpseSay($"[RynthAi] Own corpse: recovered {_ownRecoveryTaken}; {left.Count} item(s) would not move after {_ownRecoveryRounds} tries ({names}). Take them by hand.");
_ownRecoveryCorpseId = 0;
MarkCorpseCompleted(corpseId);
return;
}
OwnCorpseSay($"[RynthAi] Own corpse: {left.Count} item(s) would not move ({names}); trying again in {OwnCorpseRetryPauseMs / 1000}s.");
PauseOwnCorpse(corpseId, OwnCorpseRetryPauseMs, "own corpse: retry later");
}
/// <summary>No pack has a slot for the next item: close the corpse and look again later (never write it off).</summary>
private void PauseOwnCorpseNoRoom(int corpseId, string itemName)
{
LootDiag($"[RynthAi] Own corpse: no pack has room for '{itemName}'; pausing {OwnCorpseNoRoomPauseMs / 1000}s.");
if (_ownCorpseNoRoomSaid.Add(corpseId))
{
ChatLine("[RynthAi] Own corpse: your packs are full. Make room and it carries on (it looks again every minute).");
WorldObjectCache.WarnPackFull(Host, "own corpse recovery paused, no pack has a free slot");
}
PauseOwnCorpse(corpseId, OwnCorpseNoRoomPauseMs, "own corpse: no room");
}
/// <summary>Closes the corpse and holds it for <paramref name="ms"/>, without the completed mark.</summary>
private void PauseOwnCorpse(int corpseId, long ms, string why)
{
ResetCurrentLootItem();
CloseCorpseContainer(corpseId, why);
if (_openedContainerId == corpseId)
{
_openedContainerId = 0;
_openedContainerAt = 0;
_openedContainerInventoryObservedAt = 0;
}
MarkCorpseCooldown(corpseId, (int)ms);
ResetCorpseTarget();
}
/// <summary>
/// The move for an item on your corpse. A pack (or a foci) only fits the main pack, and its
/// contents come with it (ACE never drops packs on death, but a slippery one can); everything
/// else goes where the looter puts things (LootPickup).
/// </summary>
private LootPickupResult SendOwnCorpsePickup(int itemId, out uint destination)
{
destination = 0;
WorldObject? item = _objectCache?[itemId];
if (item != null && item.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci
&& Host.HasMoveItemExternal && _playerId != 0)
{
destination = _playerId;
return Host.MoveItemExternal(unchecked((uint)itemId), _playerId, 0) ? LootPickupResult.Moved : LootPickupResult.Failed;
}
return LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out destination);
}
private void OwnCorpseSay(string text)
{
Log(text);
ChatLine(text);
}
// ── Where you died ───────────────────────────────────────────────────────
internal sealed class OwnDeathSpot
{
public uint Cell; // 0 when only the server's chat line gave the place
public float X, Y, Z;
public double Ns, Ew;
public bool HasCoords;
public bool Outdoors; // outdoor landblock cell: map coordinates mean something
public DateTime AtUtc;
public bool NothingDropped; // "You have retained all your items..."
public bool Recovered;
public string Where
{
get
{
if (Cell == 0)
return FormatMapCoords(Ns, Ew);
string cell = $"landblock 0x{Cell >> 16:X4}, cell 0x{Cell & 0xFFFF:X4}";
return HasCoords && Outdoors
? $"{FormatMapCoords(Ns, Ew)} ({cell})"
: $"{cell} at ({X:0.0}, {Y:0.0}, {Z:0.0}), indoors";
}
}
}
private OwnDeathSpot? _deathSpot;
internal OwnDeathSpot? DeathSpot => _deathSpot;
/// <summary>The death edge (CheckPlayerDeath): where the player stands is where the corpse will be.</summary>
private void RecordDeathSpot()
{
if (_ownCorpseTravel != OwnCorpseTravelState.None)
EndOwnCorpseTravel("you died again", sayInChat: false);
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _) || cell == 0)
{
_deathSpot = null;
Log("[RynthAi] Death spot: no player position to remember.");
return;
}
bool outdoors = (cell & 0xFFFF) < 0x100;
bool hasCoords = NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew);
_deathSpot = new OwnDeathSpot
{
Cell = cell, X = x, Y = y, Z = z, Ns = ns, Ew = ew,
HasCoords = hasCoords, Outdoors = outdoors, AtUtc = DateTime.UtcNow,
};
OwnCorpseSay($"[RynthAi] Your corpse is at {_deathSpot.Where}.");
}
private static readonly Regex CorpseLocatedRx = new(
@"Your corpse is located at \(\s*(\d+(?:\.\d+)?)\s*([NS])\s*,\s*(\d+(?:\.\d+)?)\s*([EW])\s*\)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>The server's death lines: where the corpse is (outdoor deaths), or that nothing dropped.</summary>
private void OnOwnCorpseChat(string text)
{
if (text.IndexOf("You do not need to recover your corpse", StringComparison.OrdinalIgnoreCase) >= 0)
{
if (_deathSpot != null && (DateTime.UtcNow - _deathSpot.AtUtc).TotalMinutes < 2)
{
_deathSpot.NothingDropped = true;
Log("[RynthAi] Own corpse: the server says nothing dropped; no need to go back for it.");
}
return;
}
Match m = CorpseLocatedRx.Match(text);
if (!m.Success)
return;
double ns = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) * (m.Groups[2].Value.Equals("S", StringComparison.OrdinalIgnoreCase) ? -1 : 1);
double ew = double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) * (m.Groups[4].Value.Equals("W", StringComparison.OrdinalIgnoreCase) ? -1 : 1);
if (_deathSpot != null && (DateTime.UtcNow - _deathSpot.AtUtc).TotalMinutes < 2)
{
Log($"[RynthAi] Own corpse: the server confirms {FormatMapCoords(ns, ew)} (remembered {_deathSpot.Where}).");
return;
}
// No position at the death edge (or it was missed): the server's line is the death spot.
_deathSpot = new OwnDeathSpot { Ns = ns, Ew = ew, HasCoords = true, Outdoors = true, AtUtc = DateTime.UtcNow };
OwnCorpseSay($"[RynthAi] Your corpse is at {FormatMapCoords(ns, ew)} (from the server).");
}
private void MarkDeathSpotRecovered()
{
if (_deathSpot != null)
_deathSpot.Recovered = true;
}
internal static string FormatMapCoords(double ns, double ew)
=> Math.Abs(ns).ToString("0.00", CultureInfo.InvariantCulture) + (ns >= 0 ? "N" : "S") + ", "
+ Math.Abs(ew).ToString("0.00", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W");
/// <summary>/ra owncorpse [go|stop]: where your corpse is, the two settings, the travel state.</summary>
private void HandleOwnCorpseCommand(string[] parts)
{
var s = _dashboard?.Settings;
string sub = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : string.Empty;
if (sub == "stop")
{
if (_ownCorpseTravel == OwnCorpseTravelState.None) ChatLine("[RynthAi] Own corpse: not travelling.");
else EndOwnCorpseTravel("stopped by /ra owncorpse stop");
return;
}
if (sub == "go")
{
StartOwnCorpseTravel(manual: true);
return;
}
var spot = _deathSpot;
if (spot == null)
ChatLine("[RynthAi] Own corpse: no death remembered this session.");
else
{
int mins = (int)(DateTime.UtcNow - spot.AtUtc).TotalMinutes;
string state = spot.Recovered ? ", recovered" : spot.NothingDropped ? ", nothing dropped" : string.Empty;
ChatLine($"[RynthAi] Your corpse is at {spot.Where}, died {mins} min ago{state}.");
}
if (s != null)
ChatLine($"[RynthAi] Recover My Corpse: {(s.LootOwnCorpse ? "on" : "off")}, Travel Back To My Corpse: {(s.TravelToOwnCorpse ? "on" : "off")}; travel: {OwnCorpseTravelText()}. /ra owncorpse go|stop");
}
// ── Travelling back (TravelToOwnCorpse) ─────────────────────────────────
internal enum OwnCorpseTravelState { None, Waiting, Travelling, Paused, Arrived }
private OwnCorpseTravelState _ownCorpseTravel;
private long _travelStartedAt;
private long _travelIdleSince;
private long _travelBestAt;
private long _travelArrivedAt;
private double _travelBestDistance;
private bool _ownCorpseTravelManual;
internal const long OwnCorpseTravelTimeoutMs = 15 * 60_000; // whole trip, fights included
internal const long OwnCorpseTravelNoProgressMs = 120_000; // walking without getting 10 m closer
internal const double OwnCorpseTravelProgressMeters = 10.0;
internal const double OwnCorpseArriveMeters = 6.0; // at the spot: stop walking, look for it
internal const long OwnCorpseArriveSearchMs = 20_000; // at the spot with no corpse in range
internal const long OwnCorpseTravelResumeMs = 1_500; // idle this long before walking (again)
internal const string RynthNavPlugin = "RynthNav";
/// <summary>While travelling back, RynthAi's own nav route stays parked (the arbiter's wantNav).</summary>
private bool OwnCorpseTravelHoldsNav => _ownCorpseTravel != OwnCorpseTravelState.None;
private string OwnCorpseTravelText() => _ownCorpseTravel switch
{
OwnCorpseTravelState.None => "off",
OwnCorpseTravelState.Waiting => "waiting for a quiet moment",
OwnCorpseTravelState.Travelling => "walking (RynthNav)",
OwnCorpseTravelState.Paused => "paused while RynthAi works",
OwnCorpseTravelState.Arrived => "at the spot, looking for the corpse",
_ => _ownCorpseTravel.ToString(),
};
/// <summary>The respawn edge (HoldForDeath): start the trip back when Travel Back To My Corpse is on.</summary>
private void OnRespawnedForOwnCorpse()
{
var s = _dashboard?.Settings;
if (s == null || !s.TravelToOwnCorpse)
return;
StartOwnCorpseTravel(manual: false);
}
private void StartOwnCorpseTravel(bool manual)
{
var s = _dashboard?.Settings;
var spot = _deathSpot;
if (s == null)
return;
if (spot == null)
{
if (manual) ChatLine("[RynthAi] Own corpse: no death remembered this session, so nowhere to go.");
return;
}
if (spot.Recovered)
{
if (manual) ChatLine("[RynthAi] Own corpse: already recovered.");
return;
}
if (spot.NothingDropped && !manual)
{
Log("[RynthAi] Own corpse: nothing dropped on it; not travelling back.");
return;
}
if (!s.IsMacroRunning)
{
OwnCorpseSay("[RynthAi] Own corpse: the macro is off; not travelling back (start it and use /ra owncorpse go).");
return;
}
if (!spot.Outdoors || !spot.HasCoords)
{
OwnCorpseSay($"[RynthAi] Own corpse: you died indoors ({spot.Where}); travelling back only works outdoors, where RynthNav can route on the map.");
return;
}
if (!Host.HasSendPluginCommand)
{
OwnCorpseSay("[RynthAi] Own corpse: this engine can't send RynthNav commands; not travelling back.");
return;
}
long now = Environment.TickCount64;
_ownCorpseTravel = OwnCorpseTravelState.Waiting;
_ownCorpseTravelManual = manual;
_travelStartedAt = now;
_travelIdleSince = 0;
_travelArrivedAt = 0;
_travelBestAt = now;
_travelBestDistance = double.MaxValue;
OwnCorpseSay($"[RynthAi] Own corpse: travelling back to {FormatMapCoords(spot.Ns, spot.Ew)} with RynthNav once nothing else needs doing.");
}
/// <summary>
/// Every tick after the arbiter's decision. Walks (RynthNav) only while RynthAi is idle; stops
/// the walk the moment RynthAi wants the tick (combat, buffing, looting, salvage, a vendor or
/// trade session, crafting) and resumes after. Ends when your corpse is in loot range.
/// </summary>
private void TickOwnCorpseTravel(LegacyUiSettings s)
{
if (_ownCorpseTravel == OwnCorpseTravelState.None)
return;
long now = Environment.TickCount64;
var spot = _deathSpot;
if (spot == null) { EndOwnCorpseTravel("no death spot"); return; }
if (!s.TravelToOwnCorpse && !_ownCorpseTravelManual) { EndOwnCorpseTravel("Travel Back To My Corpse was turned off"); return; }
if (!s.IsMacroRunning) { EndOwnCorpseTravel("the macro stopped"); return; }
if (spot.Recovered) { EndOwnCorpseTravel("your corpse is recovered", sayInChat: false); return; }
double lootRange = GetCorpseApproachRangeMaxMeters(s);
if (s.EnableLooting && TryFindOwnCorpseInRange(lootRange, out WorldObject? corpse) && corpse != null)
{
EndOwnCorpseTravel($"your corpse (0x{(uint)corpse.Id:X8}) is in loot range; recovering it");
return;
}
if (now - _travelStartedAt > OwnCorpseTravelTimeoutMs)
{
EndOwnCorpseTravel($"gave up: not there after {OwnCorpseTravelTimeoutMs / 60_000} min");
return;
}
double d = DistanceToDeathSpotMeters(spot);
if (!double.IsNaN(d) && d <= OwnCorpseArriveMeters)
{
if (_ownCorpseTravel != OwnCorpseTravelState.Arrived)
{
if (_ownCorpseTravel == OwnCorpseTravelState.Travelling) SendRynthNav("stop");
_ownCorpseTravel = OwnCorpseTravelState.Arrived;
_travelArrivedAt = now;
Log($"[RynthAi] Own corpse: at the death spot ({d:0.0} m); looking for the corpse.");
}
if (now - _travelArrivedAt > OwnCorpseArriveSearchMs)
EndOwnCorpseTravel(s.EnableLooting
? "gave up: at the spot, but no corpse of yours in loot range (it may have decayed, or lie further than loot range)"
: "at the spot; Enable Looting is off, so it is not recovered");
return;
}
if (OwnCorpseTravelBlockedBy(out string by))
{
if (_ownCorpseTravel == OwnCorpseTravelState.Travelling)
{
SendRynthNav("stop");
Log($"[RynthAi] Own corpse: travel paused for {by}.");
}
if (_ownCorpseTravel != OwnCorpseTravelState.Waiting)
_ownCorpseTravel = OwnCorpseTravelState.Paused;
_travelIdleSince = 0;
_travelBestAt = now; // a fight is not "no progress"
return;
}
if (_ownCorpseTravel != OwnCorpseTravelState.Travelling)
{
if (_travelIdleSince == 0) _travelIdleSince = now;
if (now - _travelIdleSince < OwnCorpseTravelResumeMs)
return;
bool resume = _ownCorpseTravel == OwnCorpseTravelState.Paused || _ownCorpseTravel == OwnCorpseTravelState.Arrived;
if (!SendRynthNav("go " + FormatMapCoords(spot.Ns, spot.Ew)))
{
EndOwnCorpseTravel("gave up: RynthNav isn't loaded in this client", sendStop: false);
return;
}
Log($"[RynthAi] Own corpse: {(resume ? "resuming the walk" : "walking")} to {FormatMapCoords(spot.Ns, spot.Ew)}{(double.IsNaN(d) ? "" : $" ({d:0} m away)")}.");
_ownCorpseTravel = OwnCorpseTravelState.Travelling;
_travelArrivedAt = 0;
_travelBestAt = now;
_travelBestDistance = double.IsNaN(d) ? double.MaxValue : d;
return;
}
if (!double.IsNaN(d) && (_travelBestDistance == double.MaxValue || d < _travelBestDistance - OwnCorpseTravelProgressMeters))
{
_travelBestDistance = d;
_travelBestAt = now;
}
else if (now - _travelBestAt > OwnCorpseTravelNoProgressMs)
{
EndOwnCorpseTravel($"gave up: no closer in {OwnCorpseTravelNoProgressMs / 1000}s (RynthNav may have no route or navmesh here; /rnav here says)");
}
}
/// <summary>RynthAi wants the tick for something, so RynthNav must not be walking.</summary>
private bool OwnCorpseTravelBlockedBy(out string by)
{
by = string.Empty;
if (_activity != BotActivity.Idle) by = ActivityArbiter.ToBotAction(_activity);
else if (_autoVendor?.HoldsBot == true) by = "AutoVendor";
else if (_autoTrade?.HoldsBot == true) by = "AutoTrade";
else if (_missileCraftingManager?.IsCrafting == true) by = "ammo crafting";
else if (Host.HasIsPortaling && Host.IsPortaling()) by = "portal space";
return by.Length > 0;
}
private void EndOwnCorpseTravel(string why, bool sayInChat = true, bool sendStop = true)
{
if (sendStop && _ownCorpseTravel == OwnCorpseTravelState.Travelling)
SendRynthNav("stop");
_ownCorpseTravel = OwnCorpseTravelState.None;
_ownCorpseTravelManual = false;
_travelIdleSince = 0;
_travelArrivedAt = 0;
string line = $"[RynthAi] Own corpse: travel back ended: {why}.";
if (sayInChat) OwnCorpseSay(line); else Log(line);
// RynthAi's own nav carries on from the nearest waypoint, not one from before the death.
_navigationEngine?.ResumeFromNearestWaypoint();
}
private bool SendRynthNav(string command)
{
bool sent = Host.HasSendPluginCommand && Host.SendPluginCommand(RynthNavPlugin, "rnav", command);
Log($"[RynthAi] Own corpse: /rnav {command} -> RynthNav {(sent ? "ok" : "NOT delivered")}.");
return sent;
}
/// <summary>Metres from the player to the death spot by map coordinates (NaN without a position).</summary>
private double DistanceToDeathSpotMeters(OwnDeathSpot spot)
{
if (!spot.HasCoords)
return double.NaN;
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out _, out _, out _, out _, out _) || cell == 0)
return double.NaN;
if (!NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew))
return double.NaN;
// 0.1 of a map coordinate is 24 m.
return Math.Sqrt(Math.Pow(ns - spot.Ns, 2) + Math.Pow(ew - spot.Ew, 2)) * 240.0;
}
}

View file

@ -29,6 +29,8 @@ public sealed partial class RynthAiPlugin
{
_deathSeen = true;
Log("[RynthAi] Death detected (health 0).");
try { RecordDeathSpot(); } // where the corpse will be (RynthAiPlugin.OwnCorpse.cs)
catch (Exception ex) { Log($"[RynthAi] Death spot not recorded: {ex.Message}"); }
if (s.StopMacroOnDeath && s.IsMacroRunning)
{
HandleMacroRunCommand("stop", Array.Empty<string>());
@ -82,7 +84,11 @@ public sealed partial class RynthAiPlugin
_navigationEngine?.Stop();
}
else
{
Log("[RynthAi] Respawned — resuming.");
try { OnRespawnedForOwnCorpse(); } // Travel Back To My Corpse
catch (Exception ex) { Log($"[RynthAi] Own corpse travel not started: {ex.Message}"); }
}
}
return hold;
}

View file

@ -14,6 +14,7 @@ using RynthCore.Plugin.RynthAi.Vendor;
using RynthCore.PluginCore;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -64,14 +65,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginModule.HandWrittenVersion);
/// <summary>
/// Oldest engine RynthAi runs on. Players get plugin updates automatically but engine
/// updates only when they click, so this stays at 66 while newer calls are feature-
/// detected (Host.HasVendorTrade for API v67 vendor trading: AutoVendor reports "needs a
/// RynthCore update" without it). The SDK default is CurrentApiVersion, which would make
/// every SDK bump refuse older engines. Raise it only for a call RynthAi can't run without.
/// </summary>
public override uint MinimumApiVersion => 66;
// Oldest engine RynthAi runs on: RynthPluginMinEngineApi in the csproj (66), which is both its
// manifest's minEngineApi and, through RynthPluginBase.MinimumApiVersion's default, its own
// runtime check. Players get plugin updates automatically but engine updates only when they
// click, so it stays at 66 while newer calls are feature-detected (Host.HasVendorTrade for API
// v67 vendor trading: AutoVendor reports "needs a RynthCore update" without it). Raise it only
// for a call RynthAi can't run without.
private LegacyDashboardRenderer? _dashboard;
@ -105,7 +104,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
private ActivityArbiter? _arbiter; // STEP 1: shadow-mode only (ACTIVITY_ARBITER_PLAN.md)
private PlayerVitalsCache _vitals = new();
private uint _playerId;
private int _vitalsTickCounter;
private long _lastVitalsPollAt;
private const long VitalsPollMs = 100; // see the poll in OnTick
private bool _initialized;
private bool _loginComplete;
private bool _patrolOnLoginPending;
@ -153,6 +153,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
private readonly HashSet<uint> _seenMonstersThisSession = new();
private int _creatureSaveTickCounter;
private int _settingsSaveTickCounter;
private int _mapBakeTickCounter;
private int _settingsLoadRetryCounter;
public override int Initialize()
@ -167,6 +168,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line
// each, and no automatic door/corpse use while the macro is off.
RynthCore.Plugin.Shared.UseAudit.Reset("RynthAi", () => _dashboard?.Settings.IsMacroRunning == true);
// Every movement call is logged with its subsystem (Plugins/Shared/MoveAudit.cs).
RynthCore.Plugin.Shared.MoveAudit.Reset();
_objectCache = new WorldObjectCache(Host); // must exist before CreateObject events fire during login
// Items we use (or use something on) get re-identified before a meta reads them.
// ObjectUsed is a static event and Shutdown never unsubscribes: when the engine
@ -242,9 +245,82 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
Log("RynthAi: logout — tearing down session.");
try { _dashboard?.SaveSettings(); } catch { }
// A real logout: the next OnLoginComplete is a fresh login, not a hot reload.
ClearInGameMarker();
TeardownSession();
}
// ── Hot reload vs real login (2026-10-05) ──────────────────────────────────────────────
// The engine calls OnLoginComplete on a real login AND on a freshly (re)loaded plugin while
// the character is already in game. After the engine reload at 13:42:55 RynthAi treated it as
// a login: the buff refresh waited 5.8 s for two equal reads of an enchantment registry that
// was already complete. A process-wide environment variable (it outlives the plugin's load
// context and a NativeAOT plugin's runtime alike, and dies with the client) names the player
// whose live buffs were read in this client; a real logout clears it.
private const string InGameMarkerVar = "RYNTHAI_INGAME_PLAYER";
private bool _inGameMarkerSet;
private static string InGameMarkerValue(uint playerId) => $"{Environment.ProcessId}:{playerId:X8}";
/// <summary>At login: true when this player's live buffs were already read in this client
/// and no logout came since (an engine or plugin hot reload).</summary>
private static bool IsCarriedOverSession(uint playerId)
{
if (playerId == 0) return false;
try { return Environment.GetEnvironmentVariable(InGameMarkerVar) == InGameMarkerValue(playerId); }
catch { return false; }
}
/// <summary>Each tick until done: once the login refresh has a trusted snapshot, mark this
/// player as in game for a later hot reload.</summary>
private void NoteCarriedOverSessionReady()
{
if (_inGameMarkerSet || _buffManager == null || !_buffManager.LiveBuffsReady || _playerId == 0) return;
_inGameMarkerSet = true;
try { Environment.SetEnvironmentVariable(InGameMarkerVar, InGameMarkerValue(_playerId)); } catch { }
}
private void ClearInGameMarker()
{
_inGameMarkerSet = false;
try { Environment.SetEnvironmentVariable(InGameMarkerVar, null); } catch { }
}
// ── Reload deferral (2026-10-05) ───────────────────────────────────────────────────────
// The engine asks every plugin before a hot reload (RynthPluginReloadBlocker) and waits while
// one answers with a reason. Computed here on the pump thread each tick; the export reads the
// last text from the engine's reload thread. A text older than ReloadBlockerStaleMs (the tick
// stopped, a logout) counts as safe, so a stalled plugin can't hold a reload.
private volatile string _reloadBlocker = "";
private long _reloadBlockerAt;
private const long ReloadBlockerStaleMs = 5000;
private void UpdateReloadBlocker()
{
var s = _dashboard?.Settings;
string reason = "";
if (s != null && _buffManager != null)
{
string line = _buffManager.HealLineNow(out int hp, out int lineValue);
reason = ReloadSafety.Reason(s.IsMacroRunning, _combatManager?.HasEngageableTarget == true,
line, hp, lineValue, _buffManager.CastInFlightName);
}
_reloadBlocker = reason;
Interlocked.Exchange(ref _reloadBlockerAt, Environment.TickCount64);
}
/// <summary>For the RynthPluginReloadBlocker export (any thread): why a hot reload now would
/// hurt, or "" when it is safe.</summary>
internal string ReloadBlocker
{
get
{
if (!_loginComplete) return "";
if (Environment.TickCount64 - Interlocked.Read(ref _reloadBlockerAt) > ReloadBlockerStaleMs) return "";
return _reloadBlocker;
}
}
/// <summary>
/// Releases every component that depends on being in-world. Idempotent.
/// Used by both Shutdown (full plugin unload) and OnLogout (session-only).
@ -493,6 +569,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_weaponSwapGate ??= new WeaponSwapGate();
_buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals);
_inGameMarkerSet = false;
if (IsCarriedOverSession(_playerId))
{
// A hot reload: the registry is complete, and heals must not wait on a login refresh.
_buffManager.CarriedOverSession = true;
Log("RynthAi: hot reload - this character was already in game in this client; the buff refresh trusts its first read.");
}
_buffManager.SetWeaponSwapGate(_weaponSwapGate);
_buffManager.SetCastResolvedCallback(OnBuffCastResolved);
_buffManager.SetCharacterSkills(_charSkills);
@ -525,6 +608,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
_combatManager.SetCharacterSkills(_charSkills);
@ -651,7 +735,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_navigationEngine?.Stop();
if (Host.HasStopCompletely)
Host.StopCompletely();
Host.StopCompletelyBy("Arbiter");
// Combat taking the tick invalidates any in-progress door interaction.
// The legacy cascade did this on the combat edge only; keep it there.
@ -1262,6 +1346,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_settingsSaveTickCounter = 0;
_dashboard?.TickAutoSave();
}
// Dungeon floor plans on disk for DrakRemote (StatusAgent /map), whether or not a
// map panel is open: one pose read about twice a second; the bake itself runs once
// per landblock on a pool thread.
if (_loginComplete && ++_mapBakeTickCounter >= 30)
{
_mapBakeTickCounter = 0;
_dashboard?.TickDungeonMapBake();
}
// Pick up an external Monster Editor save (monsters.json watcher). This used
// to run only inside the legacy dashboard's Render(), which the engine no
// longer calls, so edits waited for the next login. A flag check when idle.
@ -1317,9 +1409,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// One bot per client (Decal bridge): VTank's macro started -> ours stops, before
// anything below can move, attack, cast or buff this tick.
if (_dashboard?.Settings is { } yieldSettings) TickVTankYield(yieldSettings);
if (++_vitalsTickCounter >= 30)
// Player vitals: AC sends none of its own health through OnUpdateHealth (that is the
// 0x01C0 health-of-a-target message), so this read is how the bot learns health
// dropped. It ran every 30th tick: ~1 s at a background client's 30 fps, 1.5-3 s on a
// slower or busier PC, added to every heal at random (2026-10-05, "heals sometimes
// late"). The engine's snapshot is a locked struct copy kept current by its vitals
// hook, so read it every VitalsPollMs instead.
long vitalsNow = Environment.TickCount64;
if (vitalsNow - _lastVitalsPollAt >= VitalsPollMs)
{
_vitalsTickCounter = 0;
_lastVitalsPollAt = vitalsNow;
if (Host.HasGetPlayerVitals &&
Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out uint st, out uint maxSt, out uint mp, out uint maxMp))
{
@ -1342,6 +1441,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (diag) Host.Log("[RynthAi] OnTick: before buffManager");
_buffManager?.OnHeartbeat();
if (diag) Host.Log("[RynthAi] OnTick: after buffManager");
NoteCarriedOverSessionReady();
UpdateReloadBlocker();
var settings = _dashboard?.Settings;
if (settings == null)
@ -1370,7 +1471,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
int busyBefore = Host.HasGetBusyState ? Host.GetBusyState() : -1;
if (Host.HasCancelAttack) Host.CancelAttack();
if (Host.HasStopCompletely) Host.StopCompletely();
if (Host.HasStopCompletely) Host.StopCompletelyBy("MacroStop");
if (busyBefore > 0 && Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
_busyCount = 0;
_busyCountLastIncrementAt = 0;
@ -1499,8 +1600,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
bool followActive = (settings.FollowMode && settings.FollowTargetId != 0)
|| (settings.CurrentRoute != null && settings.CurrentRoute.RouteType == NavRouteType.Follow
&& settings.CurrentRoute.FollowTargetName.Length > 0);
// Travelling back to your corpse (RynthNav walks): RynthAi's own route waits.
bool wantNav = settings.IsMacroRunning && settings.EnableNavigation
&& (routeLoaded || followActive);
&& (routeLoaded || followActive)
&& !OwnCorpseTravelHoldsNav;
// Loot starvation: a lootable corpse in range has waited LootStarveMs behind
// combat and no monster is within LootStarveCloseYards. A busy spawn always
// has a monster inside MonsterRange, so without this corpses waited until
@ -1515,6 +1618,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
lootStarved: lootStarved);
_activity = _arbiter.Apply(in inputs, settings);
_lootStarveTurn = lootStarved && _activity == BotActivity.Looting;
// Display only: what the Buffing slot is doing (ActivityArbiter.DisplayLabel),
// and the decision for [HealLatency]'s "arbiter gave the tick to" part.
if (_buffManager != null)
{
settings.BuffingLabel = _activity == BotActivity.Buffing ? _buffManager.BuffingLabel : BuffManager.LabelBuffing;
_buffManager.ArbiterActivity = ActivityArbiter.ToBotAction(_activity);
}
}
catch (Exception ex)
{
@ -1531,6 +1641,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
}
// ── Travel back to your corpse (TravelToOwnCorpse) ─────────────────
// After the decision, ahead of every early return below: RynthNav walks only
// while the arbiter says Idle, and is stopped the moment RynthAi wants the tick.
try { TickOwnCorpseTravel(settings); }
catch (Exception ex)
{
if (Environment.TickCount64 - _lastOwnCorpseTravelErrorLogAt > 10_000)
{
_lastOwnCorpseTravelErrorLogAt = Environment.TickCount64;
Host.Log($"[RynthAi] Own corpse travel tick threw: {ex.GetType().Name}: {ex.Message}");
}
}
// ── Meta Manager ─────────────────────────────────────────────────
// Here, ahead of every early return below (buffing, vendor, crafting),
// so its timers and polls keep running; it reads _activity to wait for
@ -1819,6 +1942,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
private long _lastArbiterErrorLogAt = -100_000;
private long _lastMetaScheduleErrorLogAt = -100_000;
private long _lastOwnCorpseTravelErrorLogAt = -100_000;
private long _lastTickErrorLogAt = -100_000;
private bool _lootInspectMode = true; // always on; /ra lootcheck off to disable
@ -1877,6 +2001,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_metaManager?.HandleChat(text, chatType);
_questTracker?.OnChatLine(text);
CheckChatForSafetyStops(text);
try { OnOwnCorpseChat(text); } catch { }
}
// ACE sends GameEventKillerNotification (0x01AD) to the killer at the
@ -2845,7 +2970,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return;
var (itemId, targetId, stackSize) = _pendingGives.Dequeue();
Host.MoveItemExternal(itemId, targetId, stackSize);
// The queued amount is what to hand over; GiveItem gives the whole object when it is
// the whole stack (amount 0) and uses AC's real give action, which an NPC accepts.
int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize;
GiveItem(itemId, targetId, stackSize, whole);
_lastGiveAt = DateTime.UtcNow;
if (_pendingGives.Count == 0)
@ -2926,6 +3054,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "corpseinfo": HandleCorpseInfoCommand(); break;
case "corpsecheck": HandleCorpseCheckCommand(parts); break;
case "corpseopen": HandleCorpseOpenCommand(); break;
case "owncorpse":
case "mycorpse": HandleOwnCorpseCommand(parts); break;
case "fellow":
case "fellowship": HandleFellowshipCommand(parts); break;
case "fellowinfo": HandleFellowshipInfoCommand(); break;

View file

@ -15,8 +15,19 @@
<RootNamespace>RynthCore.Plugin.RynthAi</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthAi</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Every call above v66 (vendor v67, plugin interfaces v68, use/weenie results and wield v70, trade v72, instance ids v73, VTank state v74, CloseContainer v76) is behind a Has*/version check with a fallback. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>The bot: combat, buffs, looting, navigation routes and metas.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
<!-- Plugins it can use when they are loaded (looked up at run time; optional, so they never block or reorder it). -->
<RynthPluginDependency Include="RynthNav" Optional="true" />
<RynthPluginDependency Include="RynthLua" Optional="true" />
<RynthPluginDependency Include="RynthNet" Optional="true" />
</ItemGroup>
<ItemGroup>
<!-- Interfaces shared with other RynthSuite plugins (RynthLua uses RynthAi.Script, RynthNet RynthAi.Status). -->
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
@ -26,6 +37,8 @@
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
<!-- One logged, guarded way to use an object (who used what, and why). -->
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
<!-- Movement calls logged with the subsystem that sent them (stuck-cast diagnosis, 2026-10-05). -->
<Compile Include="..\Shared\MoveAudit.cs" Link="Shared\MoveAudit.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -76,7 +76,7 @@ public sealed partial class RynthAiPlugin
{
w.WriteStartObject();
w.WriteBoolean("macro", st.IsMacroRunning);
w.WriteString("action", st.BotAction ?? "");
w.WriteString("action", ActivityArbiter.DisplayLabel(st.BotAction, st.BuffingLabel)); // display (RynthNet)
w.WriteString("state", st.CurrentState ?? "");
w.WriteBoolean("combat", st.EnableCombat);
w.WriteBoolean("buff", st.EnableBuffing);

View file

@ -117,6 +117,22 @@ public sealed partial class RynthAiPlugin
// through to HandleMtCommand returning false → "Unrecognized /ub".
int sp = fullCommand.IndexOf(' ');
// /ub give[p] [count] <item> to <target>: UtilityBelt gives EVERY matching carried item
// (Tom, 2026-10-05: "/ub give ... should give every item that matches the name"), unless
// a count is given. It used to fall through to /mt give, which hands over only the first.
// Targets match partially, as /mt give always did. give = exact item, givep = partial item.
if (sp > 0 && cmd is "give" or "givep")
{
string rest = fullCommand.Substring(sp + cmd.Length + 1).TrimStart();
string first = rest.Split(' ', 2)[0];
bool counted = int.TryParse(first, out int n) && n > 0;
string verb = cmd == "givep"
? (counted ? "givepp" : "giveapp")
: (counted ? "givexp" : "giveaxp");
HandleRaCommand("/ra " + verb + " " + rest);
return true;
}
// Verbs /mt doesn't implement but /ra does — route to the /ra dispatcher
// (VTank-meta migration). "/ub follow X" → "/ra follow X"; myquests → /ra
// quest-flag refresh.

View file

@ -337,7 +337,7 @@ internal sealed class AutoVendorManager
_openAttempts = 1;
_openNextAt = Now() + 250; // UB fudges the first attempt to ~250 ms after the command
_opening = true;
if (_host.HasSetAutoRun) _host.SetAutoRun(false);
if (_host.HasSetAutoRun) _host.SetAutoRunBy("Vendor", false);
_host.Log($"[RynthAi] AutoVendor: attempting to open vendor {vendor.Name}");
}
@ -959,9 +959,9 @@ internal sealed class AutoVendorManager
private void CancelUse()
{
if (_host.HasTurnToHeading && _host.TryGetPlayerHeading(out float h))
_host.TurnToHeading((h + 359f) % 360f);
_host.TurnToHeadingBy("Vendor", (h + 359f) % 360f);
else if (_host.HasStopCompletely)
_host.StopCompletely();
_host.StopCompletelyBy("Vendor");
}
private WorldObject? FindVendor(string target, bool partial)

View file

@ -15,6 +15,9 @@
<RootNamespace>RynthCore.Plugin.RynthChat</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthChat</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded; see Plugins\Directory.Build.targets). Nothing above the SDK baseline. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>A chat window that sorts messages into tabs.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>

View file

@ -22,6 +22,10 @@
<RootNamespace>RynthCore.Plugin.RynthInventory</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthInventory</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw the search window and instance ids (v73) fall back to ownership info; below v71 it still scans and saves (/ginv status), as with ImGui off. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Search every character's items.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>

View file

@ -15,8 +15,17 @@
<RootNamespace>RynthCore.Plugin.RynthLua</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthLua</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Vendor v67, the RynthAi bridge v68, live ids v69, action results v70, script windows v71, trade v72 and instance ids v73 are all guarded; scripts run without them (views.Available is false below v71). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Lua scripting for metas and your own scripts.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
<!-- Plugins it can use when they are loaded (looked up at run time; optional, so they never block or reorder it). -->
<RynthPluginDependency Include="RynthAi" Optional="true" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />

View file

@ -15,6 +15,10 @@
<RootNamespace>RynthCore.Plugin.RynthNav</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthNav</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Live object ids (v69) and WieldItem (v70) are behind Has* checks; without them portal avoidance/aiming and wand wielding fall back. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB).</RynthPluginDescription>
<!-- Publish straight to the launcher-registered home (mirrors RynthVision). -->
<PublishDir>C:\Games\RynthSuite\RynthNav\</PublishDir>
</PropertyGroup>

View file

@ -15,8 +15,17 @@
<RootNamespace>RynthCore.Plugin.RynthNet</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthNet</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. The RynthAi status lookup (GetPluginInterface, v68) is guarded; networking needs nothing above v66. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Lets the RynthCore clients on this PC talk to each other: shared commands, vitals, positions and bot state.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
<!-- Plugins it can use when they are loaded (looked up at run time; optional, so they never block or reorder it). -->
<RynthPluginDependency Include="RynthAi" Optional="true" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />

View file

@ -20,6 +20,10 @@
<RootNamespace>RynthCore.Plugin.RynthOracle</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthOracle</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw its window and titles/server info (v75) are guarded with fallbacks; below v71 it runs without a window (/ro status), as on an engine with ImGui off. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Quests, character, titles and leaderboards.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>

View file

@ -15,6 +15,10 @@
<RootNamespace>RynthCore.Plugin.RynthTracker</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthTracker</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Nothing above the v66 baseline. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Kills, experience and luminance per hour for each session.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>

View file

@ -15,6 +15,10 @@
<RootNamespace>RynthCore.Plugin.RynthVision</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthVision</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Only the v60/v61 Nav3D calls, behind HasNav3DTriangle. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Shows unclimbable slopes, impassable water and your radar range in the world.</RynthPluginDescription>
<!-- Publish straight to the plugin's launcher-registered home so a bare
`dotnet publish` lands where the engine hot-reloads it. Build still
uses bin\; only publish is redirected. Deploy-RynthCore.ps1 points its

136
Plugins/Shared/MoveAudit.cs Normal file
View file

@ -0,0 +1,136 @@
// ============================================================================
// RynthSuite - Plugins/Shared/MoveAudit.cs
// Movement calls with a caller tag: host.SetAutoRunBy("Nav", true) and friends.
// Linked into the plugins that move the character, like UseAudit.cs.
//
// Why (2026-10-05, Drakkon's stuck casts on DreamWeave): a movement packet sent
// while a cast winds up can cancel the cast, or leave the server holding it open.
// The engine logged only one movement call in eight and never said who sent it,
// so "which subsystem sent SetAutoRun during Buffing" could not be answered.
// Every call is now one log line:
//
// [Move] RynthAi/Nav SetAutoRun(False)
//
// Identical calls from the same subsystem in a row (the nav servo turns every
// tick; any angle counts as identical for turns) are counted instead of written
// one by one, and the count goes out with the next line that is written (the
// next different call, or the next repeat after RepeatWindowMs):
//
// [Move] RynthAi/Arbiter StopCompletely() (+14 more TurnToHeading, last 230.5 before this, over 480 ms)
//
// The engine logs the same calls (with the plugin's name) behind its own move
// trace switch; this line adds the subsystem, which only the plugin knows.
// ============================================================================
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.Shared;
internal static class MoveAudit
{
/// <summary>Off = the calls go through without a line. On by default.</summary>
public static volatile bool Enabled = true;
/// <summary>The plugin's name in every line (UseAudit.PluginName is set at Init too).</summary>
public static string PluginName => UseAudit.PluginName;
/// <summary>Clock (ms); tests replace it.</summary>
public static Func<long> NowMs = () => Environment.TickCount64;
// Identical calls closer than this to the last WRITTEN line are only counted.
private const long RepeatWindowMs = 1000;
private static readonly object Gate = new();
private static string _lastKey = "";
private static long _lastWrittenMs = long.MinValue;
private static int _repeats;
private static string _repeatLastArg = "";
private static long _repeatFirstMs;
public static bool SetAutoRunBy(this RynthCoreHost host, string who, bool on)
{
Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false);
return host.SetAutoRun(on);
}
public static bool StopCompletelyBy(this RynthCoreHost host, string who)
{
Note(host, who, "StopCompletely", "", collapseByKindOnly: false);
return host.StopCompletely();
}
public static bool SetMotionBy(this RynthCoreHost host, string who, uint motion, bool on)
{
Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false);
return host.SetMotion(motion, on);
}
public static bool DoMovementBy(this RynthCoreHost host, string who, uint motion, float speed, int holdKey)
{
Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false);
return host.DoMovement(motion, speed, holdKey);
}
public static bool StopMovementBy(this RynthCoreHost host, string who, uint motion, int holdKey)
{
Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false);
return host.StopMovement(motion, holdKey);
}
/// <summary>A heading snap. Successive turns from one subsystem collapse whatever the angle.</summary>
public static bool TurnToHeadingBy(this RynthCoreHost host, string who, float headingDegrees)
{
Note(host, who, "TurnToHeading", headingDegrees.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture), collapseByKindOnly: true);
return host.TurnToHeading(headingDegrees);
}
/// <summary>Writes (or counts) one call. Internal for the tests.</summary>
internal static string? Note(RynthCoreHost host, string who, string call, string arg, bool collapseByKindOnly)
{
if (!Enabled) return null;
string? line = null;
lock (Gate)
{
long now = NowMs();
string key = collapseByKindOnly ? $"{who}|{call}" : $"{who}|{call}({arg})";
if (key == _lastKey && now - _lastWrittenMs < RepeatWindowMs)
{
if (_repeats == 0) _repeatFirstMs = now;
_repeats++;
_repeatLastArg = arg;
return null;
}
string more = _repeats > 0
? $" (+{_repeats} more {RepeatName()} before this, over {now - _repeatFirstMs} ms)"
: "";
line = $"[Move] {PluginName}/{who} {call}({arg}){more}";
_lastKey = key;
_lastWrittenMs = now;
_repeats = 0;
_repeatLastArg = "";
}
try { host.Log(line); } catch { }
return line;
}
private static string RepeatName()
{
int bar = _lastKey.IndexOf('|');
string last = bar >= 0 ? _lastKey.Substring(bar + 1) : _lastKey;
return _lastKey.EndsWith(")", StringComparison.Ordinal) ? last : $"{last}, last {_repeatLastArg}";
}
/// <summary>Back to a fresh load (Init, tests).</summary>
public static void Reset()
{
lock (Gate)
{
_lastKey = "";
_lastWrittenMs = long.MinValue;
_repeats = 0;
_repeatLastArg = "";
}
}
}