RynthSuite as of 2026-10-05 (internal 8b7d487): navigation no longer stalls after doorway turns, faster target and attack, corpses used from a distance and closed after looting, patrol wall clearance, add-to-loot-profile from an item, WCID loot rules, scroll and slayer fixes, release 2026.10.5.1
This commit is contained in:
parent
12ca25f911
commit
53438c65c1
29 changed files with 3951 additions and 86 deletions
58
Plugins/RynthCore.Plugin.RynthAi/Combat/CombatBusyGate.cs
Normal file
58
Plugins/RynthCore.Plugin.RynthAi/Combat/CombatBusyGate.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// Tells combat when the plugin's busy count is a leftover rather than a real busy client.
|
||||
///
|
||||
/// The plugin counts AC's busy count from the engine's increment/decrement events. A cast or
|
||||
/// an item use (a corpse open) raises it through the hooked increment, but AC lowers it inline
|
||||
/// when the server's UseDone (0x01C7) arrives, which the hook never sees (see the engine's
|
||||
/// BusyCountHooks: "the shadow counter never sees AC's inline UseDone decrement"). The engine's
|
||||
/// reconciler only decrements what is still in the real field, so after a UseDone there is
|
||||
/// nothing left for it and no decrement event follows. The plugin's count then sits at 1 until
|
||||
/// its own watchdog force-clears it 5 s later (CorpseOpenController.CheckBusyTimeout), and
|
||||
/// combat's "busy, don't attack" gate waits all of that.
|
||||
///
|
||||
/// Measured (2026-09-29 caster logs, 157 kills): kill to the next cast median 2.5 s, p90 2.7 s,
|
||||
/// nearly all of it waiting for busy=0, and the steady cast cadence pinned near 5 s by the
|
||||
/// force-clear. Melee/missile after a corpse open waited up to 4 s the same way (10-01 log).
|
||||
///
|
||||
/// The rule: the count is stale when the server has finished an action (the UseDone count moved)
|
||||
/// SINCE the count last rose, and no cast gesture is animating. Melee and missile swings raise
|
||||
/// and lower the count through the hooked calls (CommenceAttack / AttackDone), so a swing in
|
||||
/// progress is never mistaken for stale: no UseDone arrives for it. Inert without the engine's
|
||||
/// UseDone counter.
|
||||
/// </summary>
|
||||
internal sealed class CombatBusyGate
|
||||
{
|
||||
private int _lastCount;
|
||||
private int _seqAtRise;
|
||||
private bool _haveRise;
|
||||
|
||||
/// <summary>Record a new busy count. A rise remembers the UseDone count at that moment.</summary>
|
||||
public void NoteCount(int count, int useDoneSeqNow)
|
||||
{
|
||||
if (count > _lastCount)
|
||||
{
|
||||
_seqAtRise = useDoneSeqNow;
|
||||
_haveRise = true;
|
||||
}
|
||||
if (count <= 0) _haveRise = false;
|
||||
_lastCount = count;
|
||||
}
|
||||
|
||||
/// <summary>True when the busy count is positive but every action behind it has been finished
|
||||
/// by the server: a UseDone arrived after the last rise and no cast gesture is animating.</summary>
|
||||
public bool IsStale(int busyCount, bool hasUseDoneSeq, int useDoneSeqNow, bool gestureInProgress)
|
||||
{
|
||||
if (busyCount <= 0 || !hasUseDoneSeq || !_haveRise) return false;
|
||||
if (gestureInProgress) return false;
|
||||
return useDoneSeqNow != _seqAtRise;
|
||||
}
|
||||
|
||||
/// <summary>Forget the remembered rise (the count was reset to 0 elsewhere).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_lastCount = 0;
|
||||
_haveRise = false;
|
||||
}
|
||||
}
|
||||
122
Plugins/RynthCore.Plugin.RynthAi/Combat/CombatLatencyTracker.cs
Normal file
122
Plugins/RynthCore.Plugin.RynthAi/Combat/CombatLatencyTracker.cs
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// Measures how long combat takes from locking a target to sending the first attack or cast at
|
||||
/// it, and what it waited on, so a player's own log answers "why didn't it attack right away".
|
||||
///
|
||||
/// CombatManager calls <see cref="OnLock"/> when it locks a new target, <see cref="OnTick"/> once
|
||||
/// per combat tick with the reason that tick didn't attack (the time since the previous tick is
|
||||
/// charged to that reason), and <see cref="OnAttack"/> when the first attack or cast goes out.
|
||||
/// OnAttack returns one line per engagement, at most one per <see cref="MinLineGapMs"/> (the
|
||||
/// skipped ones are counted into the next line):
|
||||
///
|
||||
/// [CombatLatency] lock->attack 180 ms (stance 0, face 60, busy 0, cast 120, interval 0, other 0) Magic 'Olthoi Nymph', kill->attack 210 ms
|
||||
///
|
||||
/// Pure: the caller passes the clock. Pump thread only.
|
||||
/// </summary>
|
||||
internal sealed class CombatLatencyTracker
|
||||
{
|
||||
/// <summary>What a tick waited on. Index into the bucket array.</summary>
|
||||
public enum Wait
|
||||
{
|
||||
/// <summary>Weapon or stance not ready (EquipWeaponAndSetStance said wait).</summary>
|
||||
Stance,
|
||||
/// <summary>Turning to face, or the settle after letting go of a held turn.</summary>
|
||||
Face,
|
||||
/// <summary>The client busy count (an action still in progress).</summary>
|
||||
Busy,
|
||||
/// <summary>Magic gates: the previous cast resolving, the cast gesture, the equip gate.</summary>
|
||||
Cast,
|
||||
/// <summary>The attack/cast interval since the previous attack command.</summary>
|
||||
Interval,
|
||||
/// <summary>Anything else (stall watchdog, scan grace, distance, no ammo).</summary>
|
||||
Other,
|
||||
}
|
||||
|
||||
public const double MinLineGapMs = 1000;
|
||||
private const int WaitCount = 6;
|
||||
|
||||
private readonly double[] _waits = new double[WaitCount];
|
||||
private int _targetId;
|
||||
private double _lockAtMs = double.NaN;
|
||||
private double _lastTickMs = double.NaN;
|
||||
private double _killAtMs = double.NaN;
|
||||
private double _lastLineAtMs = double.NegativeInfinity;
|
||||
private int _suppressed;
|
||||
|
||||
/// <summary>True between a lock and its first attack.</summary>
|
||||
public bool Pending => !double.IsNaN(_lockAtMs);
|
||||
|
||||
/// <summary>A new target was locked. <paramref name="killAtMs"/> is when the previous target's
|
||||
/// kill was noticed, or NaN when this lock didn't follow a kill.</summary>
|
||||
public void OnLock(int targetId, double nowMs, double killAtMs = double.NaN)
|
||||
{
|
||||
_targetId = targetId;
|
||||
_lockAtMs = nowMs;
|
||||
_lastTickMs = nowMs;
|
||||
_killAtMs = killAtMs;
|
||||
Array.Clear(_waits);
|
||||
}
|
||||
|
||||
/// <summary>The lock was dropped before any attack went out.</summary>
|
||||
public void OnDrop()
|
||||
{
|
||||
_lockAtMs = double.NaN;
|
||||
_lastTickMs = double.NaN;
|
||||
}
|
||||
|
||||
/// <summary>A combat tick that did not attack: charge the time since the previous tick to
|
||||
/// <paramref name="wait"/>.</summary>
|
||||
public void OnTick(int targetId, double nowMs, Wait wait)
|
||||
{
|
||||
if (!Pending) return;
|
||||
if (targetId != _targetId) { OnDrop(); return; }
|
||||
double dt = nowMs - _lastTickMs;
|
||||
if (dt > 0) _waits[(int)wait] += dt;
|
||||
_lastTickMs = nowMs;
|
||||
}
|
||||
|
||||
/// <summary>The first attack or cast went out. Returns the log line, or null when nothing was
|
||||
/// pending for this target or the line is throttled.</summary>
|
||||
public string? OnAttack(int targetId, double nowMs, string mode, string? targetName)
|
||||
{
|
||||
if (!Pending || targetId != _targetId) return null;
|
||||
// The tick that attacked: whatever it waited on before the attack call was the
|
||||
// interval/other bookkeeping of that same tick, so its slice goes to Other.
|
||||
double dt = nowMs - _lastTickMs;
|
||||
if (dt > 0) _waits[(int)Wait.Other] += dt;
|
||||
double total = nowMs - _lockAtMs;
|
||||
double killToAttack = double.IsNaN(_killAtMs) ? double.NaN : nowMs - _killAtMs;
|
||||
_lockAtMs = double.NaN;
|
||||
_lastTickMs = double.NaN;
|
||||
|
||||
if (nowMs - _lastLineAtMs < MinLineGapMs)
|
||||
{
|
||||
_suppressed++;
|
||||
return null;
|
||||
}
|
||||
_lastLineAtMs = nowMs;
|
||||
|
||||
var sb = new StringBuilder(160);
|
||||
sb.Append("[CombatLatency] lock->attack ").Append(Ms(total)).Append(" ms (")
|
||||
.Append("stance ").Append(Ms(_waits[(int)Wait.Stance]))
|
||||
.Append(", face ").Append(Ms(_waits[(int)Wait.Face]))
|
||||
.Append(", busy ").Append(Ms(_waits[(int)Wait.Busy]))
|
||||
.Append(", cast ").Append(Ms(_waits[(int)Wait.Cast]))
|
||||
.Append(", interval ").Append(Ms(_waits[(int)Wait.Interval]))
|
||||
.Append(", other ").Append(Ms(_waits[(int)Wait.Other]))
|
||||
.Append(") ").Append(mode);
|
||||
if (!string.IsNullOrEmpty(targetName)) sb.Append(" '").Append(targetName).Append('\'');
|
||||
if (!double.IsNaN(killToAttack)) sb.Append(", kill->attack ").Append(Ms(killToAttack)).Append(" ms");
|
||||
if (_suppressed > 0) { sb.Append(" (+").Append(_suppressed).Append(" engagements not logged)"); _suppressed = 0; }
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The time charged to one wait so far (tests and diagnostics).</summary>
|
||||
public double Waited(Wait wait) => _waits[(int)wait];
|
||||
|
||||
private static long Ms(double v) => (long)Math.Round(Math.Max(0, v));
|
||||
}
|
||||
|
|
@ -226,8 +226,30 @@ public partial class CombatManager : IDisposable
|
|||
_host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat;
|
||||
|
||||
/// <summary>Client busy count — set by plugin from OnBusyCountIncremented/Decremented.
|
||||
/// When > 0, combat must not send any game actions (SelectItem, attack, cast).</summary>
|
||||
public int BusyCount { get; set; }
|
||||
/// When > 0, combat must not send any game actions (SelectItem, attack, cast) — unless
|
||||
/// <see cref="_busyGate"/> shows the count is a leftover the server already finished.</summary>
|
||||
public int BusyCount
|
||||
{
|
||||
get => _busyCount;
|
||||
set
|
||||
{
|
||||
_busyCount = value;
|
||||
_busyGate.NoteCount(value, _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0);
|
||||
}
|
||||
}
|
||||
private int _busyCount;
|
||||
private readonly CombatBusyGate _busyGate = new();
|
||||
|
||||
/// <summary>Resets the plugin's shared busy mirror (not AC's real field) once combat finds the
|
||||
/// count is a leftover: the same thing BuffManager's cast-resolved callback does for buffs.
|
||||
/// Set by RynthAiPlugin; the argument says why.</summary>
|
||||
private Action<string>? _onStaleBusy;
|
||||
public void SetStaleBusyCallback(Action<string> cb) => _onStaleBusy = cb;
|
||||
|
||||
private readonly CombatLatencyTracker _latency = new();
|
||||
private CombatLatencyTracker.Wait _tickWait = CombatLatencyTracker.Wait.Other;
|
||||
private bool _attackedThisTick;
|
||||
private int _lastAttackCmdTargetId; // the target the last attack command (lastAttackCmd) was for
|
||||
|
||||
/// <summary>D4 (record-only): human-readable reason combat did NOT cast on the
|
||||
/// most recent tick (or "cast" when it did). Set at every magic skip site; read
|
||||
|
|
@ -1617,6 +1639,20 @@ public partial class CombatManager : IDisposable
|
|||
_damageSincePendingCast = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Take a just-killed (or predicted-killed) monster out of the current scan list. The scan
|
||||
/// skips <see cref="_recentlyKilled"/> ids, but it runs at most every SCAN_INTERVAL_MS and the
|
||||
/// kill notice arrives between ticks, so the next tick's target pick still saw the dead mob
|
||||
/// in the old list and locked it again (score ~140: closest and wounded) — a "lock" of the
|
||||
/// corpse-to-be right after "DropTarget ... killed", dropped one tick later as "hp=0". On
|
||||
/// every kill in the 2026-10-01/10-04 Olthoi logs; a cast or swing could go at it.
|
||||
/// </summary>
|
||||
private void ForgetScanned(int id)
|
||||
{
|
||||
for (int i = _scannedTargets.Count - 1; i >= 0; i--)
|
||||
if (_scannedTargets[i].Id == id) _scannedTargets.RemoveAt(i);
|
||||
}
|
||||
|
||||
private void DropTarget(string reason)
|
||||
{
|
||||
if (activeTargetId != 0)
|
||||
|
|
@ -1673,6 +1709,7 @@ public partial class CombatManager : IDisposable
|
|||
if (swapId == 0) return;
|
||||
|
||||
_recentlyKilled[swapId] = DateTime.Now.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS);
|
||||
ForgetScanned(swapId);
|
||||
// Queue this predicted one-shot so it's CREDITED when its death confirms —
|
||||
// we may swap away before its KillerNotification. Capture the name LIVE
|
||||
// from the world filter (_fightTargetName is often empty this early).
|
||||
|
|
@ -1840,6 +1877,7 @@ public partial class CombatManager : IDisposable
|
|||
else if (tid != 0 && curMatches)
|
||||
{
|
||||
_recentlyKilled[tid] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS);
|
||||
ForgetScanned(tid);
|
||||
DropTarget("killed (KillerNotification)");
|
||||
}
|
||||
}
|
||||
|
|
@ -2093,7 +2131,67 @@ public partial class CombatManager : IDisposable
|
|||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Floor between attack commands for the first cast at a new target when the server
|
||||
/// gates are available (see <see cref="AttackIntervalMs"/>). Only bounds how fast a refused
|
||||
/// cast could be retried; a refusal sets the target as the last attacked, so the retry waits
|
||||
/// the full interval anyway.</summary>
|
||||
internal const double NewTargetCastFloorMs = 300;
|
||||
|
||||
/// <summary>True when <see cref="BusyCount"/> is positive only because AC lowered it inline at a
|
||||
/// server UseDone the busy hook can't see (see <see cref="CombatBusyGate"/>).</summary>
|
||||
internal bool BusyIsLeftover()
|
||||
{
|
||||
bool gesture = _host.HasGetCastBusyState && !_host.CanCastNow;
|
||||
return _busyGate.IsStale(BusyCount, _host.HasUseDoneSeq,
|
||||
_host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0, gesture);
|
||||
}
|
||||
|
||||
/// <summary>Times combat found the busy count was a leftover and went ahead (status/tests).</summary>
|
||||
internal int StaleBusyResets => _staleBusyResets;
|
||||
private int _staleBusyResets;
|
||||
|
||||
/// <summary>
|
||||
/// The interval the combat tick waits after an attack command before the next one.
|
||||
/// Melee/missile: 1000 ms (AC paces swings and shots itself). Magic: the Attack Spell Delay
|
||||
/// setting (≤0 = 1500), except for the first cast at a new target when the engine has the
|
||||
/// server gates (UseDone and the cast gesture): those already hold the cast until the
|
||||
/// previous one is finished, so the new target only waits <see cref="NewTargetCastFloorMs"/>.
|
||||
/// Casting at the same target keeps the full setting.
|
||||
/// </summary>
|
||||
internal static double AttackIntervalMs(int combatMode, int attackSpellIntervalMs, bool hasServerGates, bool newTarget)
|
||||
{
|
||||
if (combatMode != CombatMode.Magic) return 1000.0;
|
||||
double interval = attackSpellIntervalMs > 0 ? attackSpellIntervalMs : 1500;
|
||||
if (newTarget && hasServerGates) return Math.Min(interval, NewTargetCastFloorMs);
|
||||
return interval;
|
||||
}
|
||||
|
||||
public bool Think()
|
||||
{
|
||||
_tickWait = CombatLatencyTracker.Wait.Other;
|
||||
_attackedThisTick = false;
|
||||
bool result = ThinkCore();
|
||||
|
||||
// [CombatLatency]: charge this tick to what it waited on, or log the engagement once
|
||||
// its first attack/cast went out (see CombatLatencyTracker).
|
||||
if (_latency.Pending)
|
||||
{
|
||||
double nowMs = Environment.TickCount64;
|
||||
if (activeTargetId == 0)
|
||||
_latency.OnDrop();
|
||||
else if (_attackedThisTick)
|
||||
{
|
||||
string? line = _latency.OnAttack(activeTargetId, nowMs, CombatModeName(CurrentCombatMode),
|
||||
_worldFilter[activeTargetId]?.Name);
|
||||
if (line != null) _host.Log(line);
|
||||
}
|
||||
else
|
||||
_latency.OnTick(activeTargetId, nowMs, _tickWait);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private bool ThinkCore()
|
||||
{
|
||||
if (!_settings.EnableCombat) return false;
|
||||
|
||||
|
|
@ -2189,9 +2287,15 @@ public partial class CombatManager : IDisposable
|
|||
else if (target != null && IsSpellProjectileName(target.Name))
|
||||
DropTarget("spell projectile (not a monster)");
|
||||
else if (target != null && (int)target.ObjectClass != (int)AcObjectClass.Monster)
|
||||
{
|
||||
ForgetScanned(activeTargetId);
|
||||
DropTarget("became corpse");
|
||||
}
|
||||
else if (_worldFilter.GetHealthRatio(activeTargetId) == 0f)
|
||||
{
|
||||
ForgetScanned(activeTargetId);
|
||||
DropTarget("hp=0");
|
||||
}
|
||||
else if (target != null &&
|
||||
_worldFilter.Distance(_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId) > disengageLimit)
|
||||
DropTarget("out of range");
|
||||
|
|
@ -2315,7 +2419,10 @@ public partial class CombatManager : IDisposable
|
|||
if (!(CurrentCombatMode == CombatMode.Magic && IsCastInFlight()))
|
||||
{
|
||||
if (!EquipWeaponAndSetStance(targetObj, "Auto"))
|
||||
{
|
||||
_tickWait = CombatLatencyTracker.Wait.Stance;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool useNative = _settings.UseNativeAttack && _host.HasNativeAttack;
|
||||
|
|
@ -2331,10 +2438,17 @@ public partial class CombatManager : IDisposable
|
|||
// offensive casts stops back-to-back "You're too busy!" refusals that
|
||||
// silently drop casts and cost kills. ≤0 (e.g. a pre-existing settings
|
||||
// file saved before this field existed) falls back to 1500ms.
|
||||
double attackCmdIntervalMs = CurrentCombatMode == CombatMode.Magic
|
||||
? (_settings.AttackSpellIntervalMs > 0 ? _settings.AttackSpellIntervalMs : 1500)
|
||||
: 1000.0;
|
||||
if ((DateTime.Now - lastAttackCmd).TotalMilliseconds >= attackCmdIntervalMs)
|
||||
// The first cast at a NEW target (after a kill or a predicted-kill swap) doesn't wait out
|
||||
// the interval left over from the last target when the engine reports UseDone: the
|
||||
// cast-resolution gate (UseDone) and the gesture gate (CanCastNow) below already hold it
|
||||
// until the previous cast is finished, which is what the interval stood in for before
|
||||
// those gates existed (it predates them, 2026-06-06 vs 06-20). See AttackIntervalMs.
|
||||
double attackCmdIntervalMs = AttackIntervalMs(CurrentCombatMode, _settings.AttackSpellIntervalMs,
|
||||
hasServerGates: _host.HasUseDoneSeq && _host.HasGetCastBusyState,
|
||||
newTarget: activeTargetId != _lastAttackCmdTargetId);
|
||||
if ((DateTime.Now - lastAttackCmd).TotalMilliseconds < attackCmdIntervalMs)
|
||||
_tickWait = CombatLatencyTracker.Wait.Interval;
|
||||
else
|
||||
{
|
||||
_offensiveCastThisCycle = false;
|
||||
// Convert any pending offensive cast whose refusal window has
|
||||
|
|
@ -2343,11 +2457,25 @@ public partial class CombatManager : IDisposable
|
|||
JudgePendingOffensiveCast();
|
||||
JudgePendingCast(); // verdict on the last cast once its window elapses
|
||||
|
||||
// Client is busy processing a previous action — don't queue more
|
||||
// Client is busy processing a previous action — don't queue more. Unless the count
|
||||
// is a leftover: the server finished every action behind it (a UseDone arrived after
|
||||
// it last rose) and no gesture is animating — AC lowered it inline, where the busy
|
||||
// hook can't see it, and it would otherwise hold combat until the 5 s force-clear.
|
||||
// The shared mirror is reset (not AC's real field — the engine reconciler owns that),
|
||||
// the same as BuffManager does when a buff resolves. See CombatBusyGate.
|
||||
if (BusyCount > 0)
|
||||
{
|
||||
LastCombatSkipReason = "busy-count"; // D4 record-only
|
||||
return true;
|
||||
if (!BusyIsLeftover())
|
||||
{
|
||||
LastCombatSkipReason = "busy-count"; // D4 record-only
|
||||
_tickWait = CombatLatencyTracker.Wait.Busy;
|
||||
return true;
|
||||
}
|
||||
int was = BusyCount;
|
||||
_staleBusyResets++;
|
||||
_onStaleBusy?.Invoke($"combat: the server finished the action (UseDone) — was {was}");
|
||||
if (BusyCount > 0) BusyCount = 0; // no callback, or the shared mirror was already 0
|
||||
_busyGate.Reset();
|
||||
}
|
||||
|
||||
// Magic cadence guard: while a previous combat cast is still
|
||||
|
|
@ -2359,6 +2487,7 @@ public partial class CombatManager : IDisposable
|
|||
if (CurrentCombatMode == CombatMode.Magic && IsAwaitingCastResolution())
|
||||
{
|
||||
LastCombatSkipReason = "cast-cadence"; // D4 record-only (IsCastInFlight)
|
||||
_tickWait = CombatLatencyTracker.Wait.Cast;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -2385,12 +2514,14 @@ public partial class CombatManager : IDisposable
|
|||
_facingTarget = false;
|
||||
_faceSettledAt = DateTime.Now;
|
||||
LastCombatSkipReason = "face-settle-release"; // D4 record-only
|
||||
_tickWait = CombatLatencyTracker.Wait.Face;
|
||||
return true; // settle tick
|
||||
}
|
||||
if (CurrentCombatMode == CombatMode.Magic
|
||||
&& (DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS)
|
||||
{
|
||||
LastCombatSkipReason = "face-settle-wait"; // D4 record-only
|
||||
_tickWait = CombatLatencyTracker.Wait.Face;
|
||||
return true; // let the turn-stop settle on the server first
|
||||
}
|
||||
}
|
||||
|
|
@ -2413,7 +2544,10 @@ public partial class CombatManager : IDisposable
|
|||
_faceStartTime = DateTime.Now;
|
||||
}
|
||||
if ((DateTime.Now - _faceStartTime).TotalMilliseconds < FACE_TIMEOUT_MS)
|
||||
{
|
||||
_tickWait = CombatLatencyTracker.Wait.Face;
|
||||
return true; // not facing yet, keep waiting
|
||||
}
|
||||
}
|
||||
_facingTarget = false;
|
||||
ClearCombatTurnMotions();
|
||||
|
|
@ -2453,6 +2587,7 @@ public partial class CombatManager : IDisposable
|
|||
if ((DateTime.Now - lastAttackCmd).TotalMilliseconds > 5000)
|
||||
_host.Log($"[CombatCast] CanCastNow=false — gesture gate blocking cast (last attack {(DateTime.Now - lastAttackCmd).TotalMilliseconds:0}ms ago, target=0x{activeTargetId:X8})");
|
||||
LastCombatSkipReason = "cast-gate"; // D4 record-only (CanCastNow=false)
|
||||
_tickWait = CombatLatencyTracker.Wait.Cast;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -2515,6 +2650,7 @@ public partial class CombatManager : IDisposable
|
|||
_lastEquipTime = DateTime.Now; // gate AttackWithMagic until wand is wielded
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
lastAttackCmd = DateTime.Now;
|
||||
_lastAttackCmdTargetId = activeTargetId;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -2523,6 +2659,7 @@ public partial class CombatManager : IDisposable
|
|||
// Physical combat always attacks — spell shape flags (UseArc/Bolt/Ring/Streak)
|
||||
// are only relevant in magic mode and must not gate melee/missile attacks.
|
||||
physicalSent = AttackTarget();
|
||||
if (physicalSent) _attackedThisTick = true;
|
||||
}
|
||||
|
||||
// Ring spells hit an area — no per-target damage feedback is generated,
|
||||
|
|
@ -2537,6 +2674,7 @@ public partial class CombatManager : IDisposable
|
|||
if (!_lastCastWasRing && (!magicMode || _offensiveCastThisCycle) && physicalSent)
|
||||
RecordOffensiveCast(activeTargetId);
|
||||
lastAttackCmd = DateTime.Now;
|
||||
_lastAttackCmdTargetId = activeTargetId;
|
||||
|
||||
// Predicted kill shot (set in AttackWithMagic): the cast we just fired
|
||||
// is expected to finish this mob. DON'T swap yet — on ACE a war cast is
|
||||
|
|
@ -3119,6 +3257,11 @@ public partial class CombatManager : IDisposable
|
|||
else
|
||||
_host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, priority {bestPriority}, {DescribeTargetPos(bestId)})");
|
||||
|
||||
// [CombatLatency]: time this engagement from the lock to its first attack.
|
||||
double lockMs = Environment.TickCount64;
|
||||
double sinceKillMs = _lastKillAt == DateTime.MinValue ? double.MaxValue : (DateTime.Now - _lastKillAt).TotalMilliseconds;
|
||||
_latency.OnLock(bestId, lockMs, sinceKillMs <= 2000 ? lockMs - sinceKillMs : double.NaN);
|
||||
|
||||
activeTargetId = bestId;
|
||||
_lockedTargetId = bestId;
|
||||
_lockedPriority = bestPriority;
|
||||
|
|
@ -4311,6 +4454,7 @@ public partial class CombatManager : IDisposable
|
|||
/// cast waits for it to resolve on the server (see IsAwaitingCastResolution).</summary>
|
||||
private void MarkCombatCastIssued()
|
||||
{
|
||||
_attackedThisTick = true; // [CombatLatency]: a debuff or attack cast went out
|
||||
_awaitingCastResolution = true;
|
||||
_castResolutionDeadline = DateTime.Now.AddMilliseconds(CAST_RESOLUTION_TIMEOUT_MS);
|
||||
_useDoneSeqAtCast = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
|
||||
|
|
@ -4555,9 +4699,10 @@ public partial class CombatManager : IDisposable
|
|||
LastCombatSkipReason = "equip-gate"; // D4 record-only
|
||||
return;
|
||||
}
|
||||
// Cadence is the motion-end gate (CanCastNow at the AttackWithMagic
|
||||
// call site, CombatManager.cs:905) — no fixed inter-cast interval;
|
||||
// fire as soon as the cast gesture completes.
|
||||
// Cadence is set in Think before this is called: the previous cast must have resolved
|
||||
// (UseDone, IsAwaitingCastResolution), its gesture must be over (CanCastNow), and the
|
||||
// Attack Spell Delay must have passed since the last cast at this same target (the first
|
||||
// cast at a new target skips that delay when the two server gates exist — AttackIntervalMs).
|
||||
|
||||
if (_waitingForDebuffResult)
|
||||
{
|
||||
|
|
@ -4630,6 +4775,22 @@ public partial class CombatManager : IDisposable
|
|||
int warTier = _spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0;
|
||||
int voidTier = _spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0;
|
||||
int offensiveSpellId = FindBestShapedSpell(element, rule, out bool isRing, out int castShape, arcTargetId: activeTargetId);
|
||||
// No spell of that element known (a low caster whose listed knife says Slash, with no
|
||||
// Slash war spell): cast an element the character does know rather than nothing every
|
||||
// cycle (2026-10-02 log; found 2026-10-04). Not when an arc gave way to an obstacle.
|
||||
if (offensiveSpellId == 0 && !_lastShapeArcGaveWay)
|
||||
{
|
||||
foreach (string alt in WeaponPlanner.FallbackOrder)
|
||||
{
|
||||
if (alt.Equals(element, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
int altId = FindBestShapedSpell(alt, rule, out bool altRing, out int altShape, arcTargetId: activeTargetId);
|
||||
if (altId == 0) continue;
|
||||
if (_noElementFallbackLogged.Add(element))
|
||||
_host.Log($"[CombatCast] no {element} attack spell known: casting {alt} instead");
|
||||
element = alt; offensiveSpellId = altId; isRing = altRing; castShape = altShape;
|
||||
break;
|
||||
}
|
||||
}
|
||||
LogArcChoice(rule, target, castShape);
|
||||
if (offensiveSpellId != 0)
|
||||
{
|
||||
|
|
@ -4711,6 +4872,7 @@ public partial class CombatManager : IDisposable
|
|||
}
|
||||
|
||||
private int _autoElemDiagCount;
|
||||
private readonly HashSet<string> _noElementFallbackLogged = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private string GetPreferredElement(WorldObject? target, MonsterRule? rule)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -988,10 +988,16 @@ public class WorldObjectCache
|
|||
/// Read an STypeInt property from an object via CBaseQualities::InqInt.
|
||||
/// Returns defaultValue if the API is unavailable or the property is not set.
|
||||
/// </summary>
|
||||
/// <summary>Decal's synthetic LongValueKey "Type" (0x0D000000): the object's weenie class id
|
||||
/// (WCID). VTank profiles match WCIDs with it ("loot everything that isn't retail").</summary>
|
||||
public const uint DecalTypeKey = 0x0D000000;
|
||||
|
||||
public int GetIntProperty(int id, uint stype, int defaultValue)
|
||||
{
|
||||
if (!_host.HasGetObjectIntProperty) return defaultValue;
|
||||
uint uid = unchecked((uint)id);
|
||||
if (stype == DecalTypeKey)
|
||||
return _host.HasGetObjectWcid && _host.TryGetObjectWcid(uid, out uint wcid) ? unchecked((int)wcid) : defaultValue;
|
||||
if (!_host.HasGetObjectIntProperty) return defaultValue;
|
||||
return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -215,6 +215,35 @@ public sealed partial class RynthAiPlugin
|
|||
Log($"[RynthAi] shadow busy-reset on cast resolve (was {was}, {reason}) — real field left to the engine reconciler");
|
||||
}
|
||||
|
||||
// CombatManager calls this when the busy count holding its attack is a leftover: the server
|
||||
// finished every action behind it (a UseDone arrived after it last rose) and no gesture is
|
||||
// animating — AC lowered the real field inline, where the busy hook can't see it (see
|
||||
// CombatBusyGate). Same as OnBuffCastResolved: the shadow only, the real field stays with the
|
||||
// engine reconciler, and it spares CheckBusyTimeout's real-field force-clear 5 s later.
|
||||
// Logged at most every 10 s (it can happen on every cast).
|
||||
private long _lastCombatBusyStaleLogAt;
|
||||
private int _combatBusyStaleSinceLog;
|
||||
private void OnCombatBusyStale(string reason)
|
||||
{
|
||||
if (_busyCount <= 0) return;
|
||||
int was = _busyCount;
|
||||
_busyCount = 0;
|
||||
_busyCountLastIncrementAt = 0;
|
||||
_busyCountBecamePositiveAt = 0;
|
||||
if (_combatManager != null) _combatManager.BusyCount = 0;
|
||||
if (_buffManager != null) _buffManager.BusyCount = 0;
|
||||
_combatBusyStaleSinceLog++;
|
||||
long now = CorpseNowMs;
|
||||
if (now - _lastCombatBusyStaleLogAt >= 10_000)
|
||||
{
|
||||
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");
|
||||
_lastCombatBusyStaleLogAt = now;
|
||||
_combatBusyStaleSinceLog = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private long _lastCorpsePruneAt;
|
||||
private const long CorpsePruneIntervalMs = 60_000; // prune once per minute
|
||||
// Retain a completed-corpse mark this long. Must exceed the longest AC corpse
|
||||
|
|
@ -285,9 +314,9 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
// _completedCorpses is authoritative. FinalizeCorpse deliberately leaves a
|
||||
// looted corpse open server-side, so AC re-announces its contents every time
|
||||
// it re-streams into range on a patrol loop. Treat any reopen of a completed
|
||||
// _completedCorpses is authoritative. On an engine without CloseContainer (API
|
||||
// before v76) a looted corpse stays open server-side, so AC re-announces its
|
||||
// contents every time it re-streams into range on a patrol loop. Treat any reopen of a completed
|
||||
// corpse as a passive re-announce: never clear the mark, never start a loot
|
||||
// session. Membership alone decides — same rule the polling reconciler
|
||||
// already enforces in SyncCorpseContainerState. A corpse NOT in the set
|
||||
|
|
@ -1993,10 +2022,13 @@ public sealed partial class RynthAiPlugin
|
|||
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
|
||||
ResetCurrentLootItem();
|
||||
|
||||
// Clear container state immediately. Do NOT send UseObject(corpse) to close it —
|
||||
// that increments busy count and blocks the next open until the server acks the close.
|
||||
// The server will auto-close this corpse when the next UseObject open is sent.
|
||||
// SyncCorpseContainerState guards against re-claiming via _completedCorpses.
|
||||
// Close the loot window (CloseCorpseContainer: the client's own close packet, which
|
||||
// adds nothing to the busy count; never UseObject(corpse), which does and blocks the
|
||||
// next open until the server acks it). Engines without it keep the old behaviour: the
|
||||
// server closes this corpse when the next UseObject open is sent.
|
||||
// Clear container state immediately; SyncCorpseContainerState guards against
|
||||
// re-claiming via _completedCorpses until the server's close lands.
|
||||
CloseCorpseContainer(corpseId, "completed");
|
||||
if (_openedContainerId == corpseId)
|
||||
{
|
||||
_openedContainerId = 0;
|
||||
|
|
@ -2363,6 +2395,49 @@ public sealed partial class RynthAiPlugin
|
|||
_corpseTargetSince = now - _corpseHoldFrozenAge;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the loot window of a corpse the bot is done with, when it is the open container:
|
||||
/// Host.CloseContainer (API v76) sends the 0x0195 NoLongerViewingContents game action, the
|
||||
/// packet the client sends when the player closes the window. It is not an inventory request:
|
||||
/// AC's busy count doesn't move (no OnBusyCountIncremented, so the next open isn't held) and
|
||||
/// the client's one pending item request is left alone. The engine queues it on AC's main
|
||||
/// thread ahead of the next corpse's UseObject. The server answers with CloseGroundContainer,
|
||||
/// which closes the window and brings OnStopViewingObjectContents. Older engines: nothing
|
||||
/// (the server closes the corpse when the next one is opened, as before).
|
||||
/// </summary>
|
||||
private void CloseCorpseContainer(int corpseId, string why)
|
||||
{
|
||||
if (corpseId == 0 || !Host.HasCloseContainer)
|
||||
return;
|
||||
|
||||
bool isOpen = _openedContainerId == corpseId
|
||||
|| (Host.HasGetGroundContainerId && unchecked((int)Host.GetGroundContainerId()) == corpseId);
|
||||
if (!isOpen)
|
||||
return;
|
||||
|
||||
if (Host.CloseContainer(unchecked((uint)corpseId)))
|
||||
LootDiag($"[RynthAi] Corpse loot: closing 0x{(uint)corpseId:X8} ({why}).");
|
||||
else
|
||||
LootDiag($"[RynthAi] Corpse loot: close of 0x{(uint)corpseId:X8} not sent ({why}).");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The macro was switched off with a corpse open: close it (the corpse isn't marked
|
||||
/// completed, so a later run can still loot what is left). The open-container state is
|
||||
/// cleared by the server's answer (OnStopViewingObjectContents), as for a window the
|
||||
/// player closes. Called once, on the running-to-stopped transition, so a corpse the
|
||||
/// player opens by hand while the macro is off is never closed.
|
||||
/// </summary>
|
||||
private void CloseOpenCorpseOnMacroStop()
|
||||
{
|
||||
int corpseId = _openedContainerId;
|
||||
if (corpseId == 0 || !IsCorpseLikeObject(corpseId))
|
||||
return;
|
||||
|
||||
ResetCurrentLootItem();
|
||||
CloseCorpseContainer(corpseId, "macro stopped");
|
||||
}
|
||||
|
||||
private void AbandonCurrentCorpse(long now, string reason)
|
||||
{
|
||||
int corpseId = _targetCorpseId != 0 ? _targetCorpseId : _openedContainerId;
|
||||
|
|
@ -2394,8 +2469,10 @@ public sealed partial class RynthAiPlugin
|
|||
LootDiag($"[RynthAi] Corpse loot: 0x{(uint)corpseId:X8} was never opened (abandon #{abandons}) — retry in {NeverOpenedAbandonRetryMs / 1000}s instead of completed-marking.");
|
||||
}
|
||||
|
||||
// Force-clear container state — don't try UseObject to close.
|
||||
// The server will auto-close when we open the next corpse or move away.
|
||||
// Close it the client's way (no busy count; see CloseCorpseContainer) and force-clear
|
||||
// container state. Never UseObject to close. Without CloseContainer the server closes
|
||||
// it when we open the next corpse or move away.
|
||||
CloseCorpseContainer(corpseId, "abandoned");
|
||||
if (_openedContainerId == corpseId)
|
||||
{
|
||||
_openedContainerId = 0;
|
||||
|
|
|
|||
|
|
@ -62,11 +62,42 @@ internal sealed class DungeonGeometry
|
|||
private readonly Dictionary<uint, List<Vector3[]>> _floors = new();
|
||||
private readonly Dictionary<uint, List<WallSeg>> _walls = new();
|
||||
|
||||
// Every floor polygon and wall of the landblock, bucketed on a grid, for clearance.
|
||||
private readonly List<FloorPoly> _floorAll = new();
|
||||
private readonly Dictionary<long, List<int>> _floorGrid = new();
|
||||
private readonly List<WallSeg> _wallAll = new();
|
||||
private readonly Dictionary<long, List<int>> _wallGrid = new();
|
||||
|
||||
private readonly struct WallSeg
|
||||
{
|
||||
public readonly double X0, Y0, X1, Y1, ZMin, ZMax;
|
||||
public WallSeg(double x0, double y0, double x1, double y1, double zMin, double zMax)
|
||||
{ X0 = x0; Y0 = y0; X1 = x1; Y1 = y1; ZMin = zMin; ZMax = zMax; }
|
||||
public readonly Vector3[]? Poly; // the wall polygon, for its height at a point along it
|
||||
public WallSeg(double x0, double y0, double x1, double y1, double zMin, double zMax, Vector3[]? poly = null)
|
||||
{ X0 = x0; Y0 = y0; X1 = x1; Y1 = y1; ZMin = zMin; ZMax = zMax; Poly = poly; }
|
||||
|
||||
/// <summary>The wall's height range straight above (x, y), a point on its footprint: a
|
||||
/// wall over a ramp, or the face above an arch, doesn't reach down to the floor all along.</summary>
|
||||
public (double Lo, double Hi) ZRangeAt(double x, double y)
|
||||
{
|
||||
if (Poly == null) return (ZMin, ZMax);
|
||||
double ux = X1 - X0, uy = Y1 - Y0, len = Math.Sqrt(ux * ux + uy * uy);
|
||||
if (len < 1e-9) return (ZMin, ZMax);
|
||||
ux /= len; uy /= len;
|
||||
double s = (x - X0) * ux + (y - Y0) * uy;
|
||||
double lo = double.MaxValue, hi = double.MinValue;
|
||||
int n = Poly.Length;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var a = Poly[i]; var b = Poly[(i + 1) % n];
|
||||
double sa = (a.X - X0) * ux + (a.Y - Y0) * uy, sb = (b.X - X0) * ux + (b.Y - Y0) * uy;
|
||||
if ((s < Math.Min(sa, sb) - 1e-6) || (s > Math.Max(sa, sb) + 1e-6)) continue;
|
||||
double z;
|
||||
if (Math.Abs(sb - sa) < 1e-9) { lo = Math.Min(lo, Math.Min(a.Z, b.Z)); hi = Math.Max(hi, Math.Max(a.Z, b.Z)); continue; }
|
||||
z = a.Z + (b.Z - a.Z) * (s - sa) / (sb - sa);
|
||||
lo = Math.Min(lo, z); hi = Math.Max(hi, z);
|
||||
}
|
||||
return lo <= hi ? (lo, hi) : (ZMin, ZMax);
|
||||
}
|
||||
}
|
||||
|
||||
public int DoorwayCount => _doorways.Count;
|
||||
|
|
@ -95,6 +126,7 @@ internal sealed class DungeonGeometry
|
|||
if (!IsUpwardFloor(v)) continue; // the "floor" list holds ceilings too
|
||||
if (!g._floors.TryGetValue(cell, out var list)) g._floors[cell] = list = new List<Vector3[]>();
|
||||
list.Add(v);
|
||||
g.AddFloorToGrid(v);
|
||||
}
|
||||
|
||||
foreach (var (cell, v) in wallPolys)
|
||||
|
|
@ -103,6 +135,7 @@ internal sealed class DungeonGeometry
|
|||
if (!TryWallFootprint(v, out var seg)) continue;
|
||||
if (!g._walls.TryGetValue(cell, out var list)) g._walls[cell] = list = new List<WallSeg>();
|
||||
list.Add(seg);
|
||||
g.AddWallToGrid(seg);
|
||||
}
|
||||
|
||||
// Portal polygons per cell: centre, horizontal normal, width.
|
||||
|
|
@ -228,7 +261,7 @@ internal sealed class DungeonGeometry
|
|||
if (p.Z > maxZ) maxZ = p.Z;
|
||||
}
|
||||
if (maxS - minS < 0.05) return false;
|
||||
seg = new WallSeg(sx0, sy0, sx1, sy1, minZ, maxZ);
|
||||
seg = new WallSeg(sx0, sy0, sx1, sy1, minZ, maxZ, v);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -248,6 +281,13 @@ internal sealed class DungeonGeometry
|
|||
|
||||
public bool TryGetDoorway(uint a, uint b, out DungeonDoorway door) => _doorways.TryGetValue(EdgeKey(a, b), out door!);
|
||||
|
||||
/// <summary>Openings whose centre is within r (horizontally) of (x, y) and 2 m of height z.</summary>
|
||||
public IEnumerable<DungeonDoorway> DoorwaysNear(double x, double y, double z, double r)
|
||||
{
|
||||
foreach (var d in _doorways.Values)
|
||||
if ((d.X - x) * (d.X - x) + (d.Y - y) * (d.Y - y) <= r * r && Math.Abs(d.Z - z) < 2.0) yield return d;
|
||||
}
|
||||
|
||||
public bool HasFloor(uint cell) => _floors.ContainsKey(cell);
|
||||
|
||||
/// <summary>True when (x, y) is on one of the cell's floor polygons, the floor at most 1 m
|
||||
|
|
@ -325,6 +365,404 @@ internal sealed class DungeonGeometry
|
|||
return true;
|
||||
}
|
||||
|
||||
// ── Clearance from walls ────────────────────────────────────────────────
|
||||
//
|
||||
// How far a character standing at a point is from anything it can't walk into: an upright
|
||||
// wall reaching above step height, or the edge of the walkable floor (a drop, or a slope
|
||||
// too steep to stand on, like the raised sides of the Olthoi hive's corridors). Measured
|
||||
// over the whole landblock, not one cell: a point beside a doorway is close to the next
|
||||
// cell's walls too. Probed along 16 directions in 0.1 m steps, following the floor up and
|
||||
// down ramps, plus the exact distance to the nearest wall.
|
||||
|
||||
/// <summary>AC's walkable slope limit (PhysicsGlobals.FloorZ = 0.66417, about 48 degrees):
|
||||
/// a steeper "floor" polygon is a slope the character slides off, so it bounds the floor.</summary>
|
||||
public const double WalkableNz = 0.664;
|
||||
|
||||
private const double GridCell = 4.0;
|
||||
private const int ProbeDirs = 16;
|
||||
private const double ProbeStep = 0.1;
|
||||
// Height change allowed between two probe steps 0.1 m apart: a 48 degree slope rises 0.11,
|
||||
// a stair 0.25; more is a ledge.
|
||||
private const double ProbeMaxRise = 0.3;
|
||||
// A wall counts for clearance when it reaches into this band above the floor: lower lips
|
||||
// are stepped over (the human Setup's step-up height is 0.45; see PatrolProof "human").
|
||||
private const double ClearWallLow = 0.45, ClearWallHigh = 1.8;
|
||||
|
||||
private sealed class FloorPoly
|
||||
{
|
||||
public Vector3[] V = null!;
|
||||
public double Nx, Ny, Nz, Px, Py, Pz; // unit normal and a point on the plane
|
||||
public double MinX, MinY, MaxX, MaxY;
|
||||
public bool Walkable;
|
||||
public double HeightAt(double x, double y) => Pz - (Nx * (x - Px) + Ny * (y - Py)) / Nz;
|
||||
}
|
||||
|
||||
private static long GridKey(int gx, int gy) => ((long)gx << 32) ^ (uint)gy;
|
||||
private static int GridOf(double v) => (int)Math.Floor(v / GridCell);
|
||||
|
||||
private void AddFloorToGrid(Vector3[] v)
|
||||
{
|
||||
NewellNormal(v, out double nx, out double ny, out double nz);
|
||||
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
|
||||
if (len < 1e-9 || nz <= 1e-9) return;
|
||||
var f = new FloorPoly { V = v, Nx = nx / len, Ny = ny / len, Nz = nz / len, MinX = double.MaxValue, MinY = double.MaxValue, MaxX = double.MinValue, MaxY = double.MinValue };
|
||||
double sx = 0, sy = 0, sz = 0;
|
||||
foreach (var p in v)
|
||||
{
|
||||
sx += p.X; sy += p.Y; sz += p.Z;
|
||||
f.MinX = Math.Min(f.MinX, p.X); f.MaxX = Math.Max(f.MaxX, p.X);
|
||||
f.MinY = Math.Min(f.MinY, p.Y); f.MaxY = Math.Max(f.MaxY, p.Y);
|
||||
}
|
||||
f.Px = sx / v.Length; f.Py = sy / v.Length; f.Pz = sz / v.Length;
|
||||
f.Walkable = f.Nz >= WalkableNz;
|
||||
int idx = _floorAll.Count;
|
||||
_floorAll.Add(f);
|
||||
for (int gx = GridOf(f.MinX); gx <= GridOf(f.MaxX); gx++)
|
||||
for (int gy = GridOf(f.MinY); gy <= GridOf(f.MaxY); gy++)
|
||||
{
|
||||
long k = GridKey(gx, gy);
|
||||
if (!_floorGrid.TryGetValue(k, out var list)) _floorGrid[k] = list = new List<int>();
|
||||
list.Add(idx);
|
||||
}
|
||||
}
|
||||
|
||||
private void AddWallToGrid(WallSeg w)
|
||||
{
|
||||
int idx = _wallAll.Count;
|
||||
_wallAll.Add(w);
|
||||
for (int gx = GridOf(Math.Min(w.X0, w.X1)); gx <= GridOf(Math.Max(w.X0, w.X1)); gx++)
|
||||
for (int gy = GridOf(Math.Min(w.Y0, w.Y1)); gy <= GridOf(Math.Max(w.Y0, w.Y1)); gy++)
|
||||
{
|
||||
long k = GridKey(gx, gy);
|
||||
if (!_wallGrid.TryGetValue(k, out var list)) _wallGrid[k] = list = new List<int>();
|
||||
list.Add(idx);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The floor under (x, y) nearest in height to zRef, at most <paramref name="up"/>
|
||||
/// above and <paramref name="down"/> below it, of any cell. <paramref name="walkable"/>:
|
||||
/// flat enough to stand on.</summary>
|
||||
private bool FloorUnder(double x, double y, double zRef, double up, double down, out double h, out bool walkable)
|
||||
{
|
||||
if (FloorUnderExact(x, y, zRef, up, down, out h, out walkable)) return true;
|
||||
// A point exactly on the seam between two polygons can fall outside both.
|
||||
return FloorUnderExact(x + 1.3e-3, y + 0.7e-3, zRef, up, down, out h, out walkable);
|
||||
}
|
||||
|
||||
private bool FloorUnderExact(double x, double y, double zRef, double up, double down, out double h, out bool walkable)
|
||||
{
|
||||
h = 0; walkable = false;
|
||||
if (!_floorGrid.TryGetValue(GridKey(GridOf(x), GridOf(y)), out var list)) return false;
|
||||
double best = double.MaxValue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
var f = _floorAll[i];
|
||||
if (x < f.MinX || x > f.MaxX || y < f.MinY || y > f.MaxY) continue;
|
||||
if (!InsidePolygon2D(f.V, x, y)) continue;
|
||||
double fh = f.HeightAt(x, y), dz = fh - zRef;
|
||||
if (dz > up || dz < -down) continue;
|
||||
if (Math.Abs(dz) < best) { best = Math.Abs(dz); h = fh; walkable = f.Walkable; }
|
||||
}
|
||||
return best < double.MaxValue;
|
||||
}
|
||||
|
||||
/// <summary>True when (x, y) stands on walkable floor (any cell) about height z.</summary>
|
||||
public bool OnWalkableFloor(double x, double y, double z)
|
||||
=> FloorUnder(x, y, z, FloorAbove, FloorBelow, out _, out bool w) && w;
|
||||
|
||||
/// <summary>
|
||||
/// How far (metres, up to <paramref name="maxR"/>) a character at (x, y), floor height about
|
||||
/// z, is from the nearest wall or edge of the walkable floor. 0 when the point is off the
|
||||
/// floor (in or behind a wall, on a slope too steep to stand on). Where the landblock has no
|
||||
/// floor data near the point, only walls are measured.
|
||||
/// </summary>
|
||||
public double Clearance(double x, double y, double z, double maxR = 3.0)
|
||||
{
|
||||
bool floorKnown = FloorUnder(x, y, z, FloorAbove, FloorBelow, out double h0, out bool walk);
|
||||
if (floorKnown && !walk) return 0;
|
||||
if (!floorKnown)
|
||||
{
|
||||
if (FloorNear(x, y, z)) return 0; // past the floor's edge: in or behind a wall
|
||||
h0 = z;
|
||||
}
|
||||
double best = maxR;
|
||||
for (int k = 0; k < ProbeDirs && best > 0; k++)
|
||||
{
|
||||
double a = k * (2 * Math.PI / ProbeDirs);
|
||||
best = Math.Min(best, FreeRun(x, y, h0, Math.Cos(a), Math.Sin(a), best, floorKnown));
|
||||
}
|
||||
return Math.Min(best, WallDistance(x, y, h0 + ClearWallLow, h0 + ClearWallHigh, best));
|
||||
}
|
||||
|
||||
// Clearance is asked again and again for the same spots (a patrol passes a doorway several
|
||||
// times a lap; every standoff is tried in turn): remembered to the centimetre.
|
||||
private readonly Dictionary<(long, long, long, int), double> _clearanceMemo = new();
|
||||
|
||||
internal double ClearanceMemo(double x, double y, double z, double maxR)
|
||||
{
|
||||
var key = ((long)Math.Round(x * 100), (long)Math.Round(y * 100), (long)Math.Round(z * 10), (int)Math.Round(maxR * 100));
|
||||
if (_clearanceMemo.TryGetValue(key, out double c)) return c;
|
||||
if (_clearanceMemo.Count > 200_000) _clearanceMemo.Clear();
|
||||
return _clearanceMemo[key] = Clearance(x, y, z, maxR);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves (x, y) to where a character has <paramref name="want"/> clearance, at most
|
||||
/// <paramref name="maxMove"/> from where it started, staying on walkable floor (and on the
|
||||
/// floor of <paramref name="cells"/> when given): away from the walls and floor edges it is
|
||||
/// too close to, each probe direction that hits something within reach pushing the other
|
||||
/// way. Between two walls closer than 2 x want it ends on the middle line. A point off the
|
||||
/// floor (a dead end's cell origin inside its end cap) first goes to the nearest floor.
|
||||
/// Returns the clearance where it ends; the point is left alone when nothing is better.
|
||||
/// </summary>
|
||||
public double PushClear(ref double x, ref double y, double z, double want, double maxMove, IReadOnlyCollection<uint>? cells = null)
|
||||
{
|
||||
double reach = want + 0.5;
|
||||
double ox = x, oy = y;
|
||||
double c = ClearanceMemo(x, y, z, reach);
|
||||
if (c >= want) return c;
|
||||
|
||||
bool Allowed(double px, double py)
|
||||
=> (px - ox) * (px - ox) + (py - oy) * (py - oy) <= maxMove * maxMove + 1e-9
|
||||
&& OnWalkableFloor(px, py, z)
|
||||
&& (cells == null || OnFloorOfAny(cells, px, py, z));
|
||||
|
||||
if (c <= 0 && !OnWalkableFloor(x, y, z))
|
||||
{
|
||||
// Off the floor: the ring nearest the point that has floor with any room, its best spot.
|
||||
bool found = false;
|
||||
for (double r = 0.1; r <= maxMove + 1e-9 && !found; r += 0.1)
|
||||
{
|
||||
double bx = 0, by = 0, bc = 0;
|
||||
for (int k = 0; k < ProbeDirs; k++)
|
||||
{
|
||||
double a = k * (2 * Math.PI / ProbeDirs);
|
||||
double px = ox + Math.Cos(a) * r, py = oy + Math.Sin(a) * r;
|
||||
if (!Allowed(px, py)) continue;
|
||||
double pc = ClearanceMemo(px, py, z, reach);
|
||||
if (pc > bc) { bc = pc; bx = px; by = py; }
|
||||
}
|
||||
if (bc > 0) { x = bx; y = by; c = bc; found = true; }
|
||||
}
|
||||
if (!found) return c;
|
||||
}
|
||||
|
||||
for (int iter = 0; iter < 16 && c < want; iter++)
|
||||
{
|
||||
var runs = ProbeRuns(x, y, z, reach);
|
||||
double vx = 0, vy = 0;
|
||||
for (int k = 0; k < ProbeDirs; k++)
|
||||
{
|
||||
double push = want - runs[k];
|
||||
if (push <= 0) continue;
|
||||
double a = k * (2 * Math.PI / ProbeDirs);
|
||||
vx -= Math.Cos(a) * push;
|
||||
vy -= Math.Sin(a) * push;
|
||||
}
|
||||
double vl = Math.Sqrt(vx * vx + vy * vy);
|
||||
if (vl < 1e-9) break;
|
||||
vx /= vl; vy /= vl;
|
||||
bool moved = false;
|
||||
for (double step = Math.Max(0.05, want - c); step >= 0.02 && !moved; step *= 0.5)
|
||||
{
|
||||
double px = x + vx * step, py = y + vy * step;
|
||||
if (!Allowed(px, py)) continue;
|
||||
double pc = ClearanceMemo(px, py, z, reach);
|
||||
if (pc > c + 0.01) { x = px; y = py; c = pc; moved = true; }
|
||||
}
|
||||
if (!moved) break;
|
||||
}
|
||||
if (c >= want) return c;
|
||||
|
||||
// The push found no way out (the point sits right on a wall line or a floor corner, where
|
||||
// every probe stops at once): the nearest spot round it that has the clearance, else the
|
||||
// clearest spot within reach.
|
||||
double rx = x, ry = y, rc = c;
|
||||
for (double r = 0.1; r <= maxMove + 1e-9 && rc < want; r += 0.1)
|
||||
for (int k = 0; k < ProbeDirs; k++)
|
||||
{
|
||||
double a = k * (2 * Math.PI / ProbeDirs);
|
||||
double px = x + Math.Cos(a) * r, py = y + Math.Sin(a) * r;
|
||||
if (!Allowed(px, py)) continue;
|
||||
double pc = ClearanceMemo(px, py, z, reach);
|
||||
if (pc > rc + 0.02) { rx = px; ry = py; rc = pc; }
|
||||
}
|
||||
if (rc > c) { x = rx; y = ry; c = rc; }
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The least clearance (up to maxR) along the straight walk from p0 to p1, leaving out
|
||||
/// <paramref name="skipEnds"/> at each end (the end points are judged on their own),
|
||||
/// sampled every 0.4 m following the floor up and down ramps; where it is least in
|
||||
/// (wx, wy, wz). maxR when the walk is shorter than the two ends.
|
||||
/// </summary>
|
||||
public double LegClearance(double x0, double y0, double z0, double x1, double y1, double z1,
|
||||
double maxR, double skipEnds, out double wx, out double wy, out double wz)
|
||||
{
|
||||
wx = (x0 + x1) * 0.5; wy = (y0 + y1) * 0.5; wz = (z0 + z1) * 0.5;
|
||||
double dx = x1 - x0, dy = y1 - y0, len = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (len <= 2 * skipEnds) return maxR;
|
||||
int steps = Math.Max(1, (int)Math.Ceiling((len - 2 * skipEnds) / 0.4));
|
||||
double best = maxR, zf = z0;
|
||||
for (int i = 0; i <= steps; i++)
|
||||
{
|
||||
double d = skipEnds + (len - 2 * skipEnds) * i / steps, t = d / len;
|
||||
double x = x0 + dx * t, y = y0 + dy * t, zl = z0 + (z1 - z0) * t;
|
||||
if (TryFloorHeight(x, y, zf, 0.6, out double h)) zf = h;
|
||||
else if (TryFloorHeight(x, y, zl, 0.6, out h)) zf = h;
|
||||
else zf = zl;
|
||||
double c = ClearanceMemo(x, y, zf, maxR);
|
||||
if (c < best) { best = c; wx = x; wy = y; wz = zf; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Distances (metres, up to maxR) from (x, y) to the first wall or floor edge along
|
||||
/// each of the 16 probe directions (k * 22.5 degrees from east, counter-clockwise).</summary>
|
||||
internal double[] ProbeRuns(double x, double y, double z, double maxR)
|
||||
{
|
||||
var runs = new double[ProbeDirs];
|
||||
bool floorKnown = FloorUnder(x, y, z, FloorAbove, FloorBelow, out double h0, out bool walk);
|
||||
if (floorKnown && !walk) return runs;
|
||||
if (!floorKnown) h0 = z;
|
||||
for (int k = 0; k < ProbeDirs; k++)
|
||||
{
|
||||
double a = k * (2 * Math.PI / ProbeDirs);
|
||||
runs[k] = FreeRun(x, y, h0, Math.Cos(a), Math.Sin(a), maxR, floorKnown);
|
||||
}
|
||||
return runs;
|
||||
}
|
||||
|
||||
// Any floor (steep or not) at about the point's height within 2 m of a point that has none
|
||||
// under it: the point is past the floor's edge (a dead end's cell origin is inside its end
|
||||
// cap), not in a cell whose floor the dats don't give (0x0174 has such cells above others).
|
||||
private bool FloorNear(double x, double y, double z)
|
||||
{
|
||||
for (double r = 0.5; r <= 2.0 + 1e-9; r += 0.5)
|
||||
for (int k = 0; k < 8; k++)
|
||||
{
|
||||
double a = k * Math.PI / 4;
|
||||
if (FloorUnder(x + Math.Cos(a) * r, y + Math.Sin(a) * r, z, FloorAbove, 1.5, out _, out _)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The height of the floor (any cell) under (x, y) nearest zRef, within
|
||||
/// <paramref name="band"/> above or below it.</summary>
|
||||
internal bool TryFloorHeight(double x, double y, double zRef, double band, out double h)
|
||||
=> FloorUnder(x, y, zRef, band, band, out h, out _);
|
||||
|
||||
// Distance along (dx, dy) from (x, y) to the first wall crossed or the first step off the
|
||||
// walkable floor, following the floor's height; maxR when nothing is hit.
|
||||
private double FreeRun(double x, double y, double h0, double dx, double dy, double maxR, bool checkFloor)
|
||||
{
|
||||
double px = x, py = y, ph = h0, prevR = 0;
|
||||
int n = (int)Math.Ceiling(maxR / ProbeStep - 1e-9);
|
||||
for (int i = 1; i <= n; i++)
|
||||
{
|
||||
double r = Math.Min(i * ProbeStep, maxR);
|
||||
double qx = x + dx * r, qy = y + dy * r, qh = ph;
|
||||
if (checkFloor && (!FloorUnder(qx, qy, ph, ProbeMaxRise, ProbeMaxRise, out qh, out bool w) || !w))
|
||||
return prevR + (r - prevR) * 0.5;
|
||||
if (WallHit(px, py, qx, qy, Math.Min(ph, qh) + ClearWallLow, Math.Max(ph, qh) + ClearWallHigh, out double t))
|
||||
return prevR + (r - prevR) * t;
|
||||
px = qx; py = qy; ph = qh; prevR = r;
|
||||
}
|
||||
return maxR;
|
||||
}
|
||||
|
||||
// The first wall (reaching into zLo..zHi) the segment p0-p1 crosses, as a fraction along it.
|
||||
private bool WallHit(double x0, double y0, double x1, double y1, double zLo, double zHi, out double t)
|
||||
{
|
||||
t = 1;
|
||||
bool hit = false;
|
||||
// Every bucket the step touches (a wall is in every bucket its own box touches).
|
||||
for (int gx = GridOf(Math.Min(x0, x1)); gx <= GridOf(Math.Max(x0, x1)); gx++)
|
||||
for (int gy = GridOf(Math.Min(y0, y1)); gy <= GridOf(Math.Max(y0, y1)); gy++)
|
||||
{
|
||||
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
var w = _wallAll[i];
|
||||
if (w.ZMax < zLo || w.ZMin > zHi) continue;
|
||||
if (!SegmentParam(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1, out double s) || s >= t) continue;
|
||||
var (lo, hi) = w.ZRangeAt(x0 + (x1 - x0) * s, y0 + (y1 - y0) * s);
|
||||
if (hi < zLo || lo > zHi) continue;
|
||||
t = s; hit = true;
|
||||
}
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
/// <summary>Walls (footprint and height range) within r of (x, y), for offline inspection.</summary>
|
||||
internal List<(double X0, double Y0, double X1, double Y1, double ZMin, double ZMax, double Dist)> WallsNear(double x, double y, double r)
|
||||
{
|
||||
var res = new List<(double, double, double, double, double, double, double)>();
|
||||
var seen = new HashSet<int>();
|
||||
for (int gx = GridOf(x - r); gx <= GridOf(x + r); gx++)
|
||||
for (int gy = GridOf(y - r); gy <= GridOf(y + r); gy++)
|
||||
{
|
||||
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
if (!seen.Add(i)) continue;
|
||||
var w = _wallAll[i];
|
||||
double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
|
||||
var (lo, hi) = w.ZRangeAt(cx, cy); // its height range at the nearest point
|
||||
if (d <= r) res.Add((w.X0, w.Y0, w.X1, w.Y1, lo, hi, d));
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// Exact distance from (x, y) to the nearest wall reaching into zLo..zHi, up to maxR.
|
||||
private double WallDistance(double x, double y, double zLo, double zHi, double maxR)
|
||||
{
|
||||
double best = maxR;
|
||||
for (int gx = GridOf(x - maxR); gx <= GridOf(x + maxR); gx++)
|
||||
for (int gy = GridOf(y - maxR); gy <= GridOf(y + maxR); gy++)
|
||||
{
|
||||
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
|
||||
foreach (int i in list)
|
||||
{
|
||||
var w = _wallAll[i];
|
||||
if (w.ZMax < zLo || w.ZMin > zHi) continue;
|
||||
double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
|
||||
if (d >= best) continue;
|
||||
var (lo, hi) = w.ZRangeAt(cx, cy);
|
||||
if (hi < zLo || lo > zHi) continue;
|
||||
best = d;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static double PointSegDist(double px, double py, double ax, double ay, double bx, double by)
|
||||
=> PointSegDist(px, py, ax, ay, bx, by, out _, out _);
|
||||
|
||||
private static double PointSegDist(double px, double py, double ax, double ay, double bx, double by, out double cx, out double cy)
|
||||
{
|
||||
double dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy;
|
||||
double t = len2 < 1e-12 ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / len2, 0, 1);
|
||||
cx = ax + dx * t; cy = ay + dy * t;
|
||||
return Math.Sqrt((cx - px) * (cx - px) + (cy - py) * (cy - py));
|
||||
}
|
||||
|
||||
// Where segment a-b meets segment c-d, as a fraction along a-b (touching counts).
|
||||
private static bool SegmentParam(double ax, double ay, double bx, double by,
|
||||
double cx, double cy, double dx, double dy, out double t)
|
||||
{
|
||||
t = 0;
|
||||
double rx = bx - ax, ry = by - ay, sx = dx - cx, sy = dy - cy;
|
||||
double den = rx * sy - ry * sx;
|
||||
if (Math.Abs(den) < 1e-12) return false;
|
||||
double qx = cx - ax, qy = cy - ay;
|
||||
t = (qx * sy - qy * sx) / den;
|
||||
double u = (qx * ry - qy * rx) / den;
|
||||
return t >= 0 && t <= 1 && u >= 0 && u <= 1;
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
internal static ulong EdgeKey(uint a, uint b)
|
||||
|
|
|
|||
|
|
@ -40,11 +40,27 @@ internal sealed class DungeonRooms
|
|||
internal static partial class DungeonPathfinder
|
||||
{
|
||||
// Approach / exit points: this far in front of / beyond the opening's centre, shortened
|
||||
// (down to the last value) until the point is on the cell's floor.
|
||||
// (in DoorwayStandoffStep steps, down to the shortest) until the point is on the cell's
|
||||
// floor AND clear of walls (WallClearance).
|
||||
// 4 m (was 2.5): at 2.5 the turn into the opening still began close enough to climb the
|
||||
// raised sides of a hallway mouth (Tom, 2026-10-04: "plenty of room to get into the hallway").
|
||||
private static readonly double[] DoorwayStandoffs = { 4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0 };
|
||||
// Room crossings must keep this much room either side of the walking line.
|
||||
private const double DoorwayStandoffLongest = 4.0, DoorwayStandoffShortest = 1.0, DoorwayStandoffStep = 0.25;
|
||||
|
||||
// Every point laid keeps at least this far from walls and floor edges where the space
|
||||
// allows. The character is a 0.48 m sphere stack (human Setup 0x02000001, PatrolProof
|
||||
// "human"); the other half metre is steering slack: the arrival ring, the arc of a turn
|
||||
// begun at speed, the sweep pass. Points closer than this put the character's body on the
|
||||
// wall when it arrives and it stuck there (Tom, 2026-10-04, testing 2026.10.4.x: "nav
|
||||
// points ... almost in the wall"). Measured with PatrolProof "clear": in crypts and
|
||||
// castles most approach/exit points in short bend and junction cells sat on the bend's
|
||||
// outer wall (Rithwic Crypt: 440 of 488 under 0.25 m), and a dead end's look-in point is
|
||||
// its cell origin, which is inside the end cap.
|
||||
internal const double WallClearance = 1.0;
|
||||
// How far a point may be pushed off where its rule put it to get that clearance.
|
||||
private const double DoorwayPushMax = 2.0, CornerPushMax = 1.5, MiddlePushMax = 4.5;
|
||||
|
||||
// Room crossings keep WallClearance either side of the walking line where the room allows,
|
||||
// else at least this much (the crossing as it was before the clearance work).
|
||||
private const double CrossingClearance = 0.5;
|
||||
// Emitted points closer than this to the previous one are dropped.
|
||||
private const double MinPointSpacing = 0.3;
|
||||
|
|
@ -393,9 +409,108 @@ internal static partial class DungeonPathfinder
|
|||
CrossRoom(pts, graph, geo, rooms, rd, prev, prevCell, dest, destCell, revisit: false);
|
||||
|
||||
DropCollinear(pts, closed);
|
||||
KeepLegsOffWalls(geo, pts, closed);
|
||||
return pts;
|
||||
}
|
||||
|
||||
// A leg brushing a wall: its least clearance (away from its end points) under this, or under
|
||||
// its end points' own when they are tighter (a narrow opening's centre).
|
||||
private const double LegMinClearance = 0.6;
|
||||
private const double LegEndSkip = 0.5, LegCornerPushMax = 2.5, LegCornerSearch = 4.0;
|
||||
|
||||
/// <summary>
|
||||
/// Every leg between consecutive points is walked along (DungeonGeometry.LegClearance) and
|
||||
/// where it passes closer to a wall than LegMinClearance (cutting an inside corner after
|
||||
/// the points were pushed, a run of openings that jogs sideways, a turning run's diagonal
|
||||
/// across a corner), a corner is put in: the leg's tightest spot, pushed off the wall,
|
||||
/// kept only when both new legs are clearer than the old one.
|
||||
/// </summary>
|
||||
internal static void KeepLegsOffWalls(DungeonGeometry geo, List<NavPoint> pts, bool closed)
|
||||
{
|
||||
int budget = pts.Count / 2 + 8, perLeg = 0;
|
||||
int i = 0;
|
||||
while (i < (closed ? pts.Count : pts.Count - 1) && pts.Count >= 2)
|
||||
{
|
||||
var a = pts[i]; var b = pts[(i + 1) % pts.Count];
|
||||
double least = LegLeast(geo, a, b, out double wx, out double wy, out double wz);
|
||||
double target = Math.Min(LegMinClearance, Math.Min(PointClearance(geo, a), PointClearance(geo, b)));
|
||||
if (least >= target - 0.05 || budget <= 0 || perLeg >= 3) { i++; perLeg = 0; continue; }
|
||||
|
||||
// The corner leaving both new legs clearest, if that is clearly better.
|
||||
NavPoint? best = BestCorner(geo, a, b, wx, wy, wz, least + 0.1, out _);
|
||||
if (best != null)
|
||||
{
|
||||
pts.Insert(i + 1, Tag(best, "leg-corner"));
|
||||
budget--; perLeg++;
|
||||
continue; // check the first new leg next
|
||||
}
|
||||
// No one corner does it (a jog round two corners): a first corner the walk reaches
|
||||
// clear, then the best corner for the rest.
|
||||
bool two = false;
|
||||
foreach (var first in CornerCandidates(geo, wx, wy, wz))
|
||||
{
|
||||
if (LegLeast(geo, a, first, out _, out _, out _) < target - 0.05 || TurnsBack(a, first, b)) continue;
|
||||
double rest = LegLeast(geo, first, b, out double rx, out double ry, out double rz);
|
||||
var second = BestCorner(geo, first, b, rx, ry, rz, Math.Max(rest, least) + 0.1, out double m2);
|
||||
if (second == null || m2 <= least + 0.1) continue;
|
||||
pts.Insert(i + 1, Tag(first, "leg-corner"));
|
||||
pts.Insert(i + 2, Tag(second, "leg-corner"));
|
||||
budget -= 2; perLeg += 2;
|
||||
two = true;
|
||||
break;
|
||||
}
|
||||
if (two) continue;
|
||||
i++; perLeg = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Corners to try for a leg whose tightest spot is (wx, wy, wz): that spot pushed off the
|
||||
// wall, and the centres of the openings near it (a leg that jogs through the wrong side of a
|
||||
// junction needs the opening it skipped).
|
||||
private static List<NavPoint> CornerCandidates(DungeonGeometry geo, double wx, double wy, double wz)
|
||||
{
|
||||
double cx = wx, cy = wy;
|
||||
geo.PushClear(ref cx, ref cy, wz, WallClearance, LegCornerPushMax);
|
||||
var list = new List<NavPoint> { WorldPoint(cx, cy, wz, false) };
|
||||
foreach (var d in geo.DoorwaysNear(wx, wy, wz, LegCornerSearch)) list.Add(WorldPoint(d.X, d.Y, d.Z, false));
|
||||
return list;
|
||||
}
|
||||
|
||||
// The candidate leaving both new legs a-corner-b clearest, if better than mustBeat.
|
||||
private static NavPoint? BestCorner(DungeonGeometry geo, NavPoint a, NavPoint b, double wx, double wy, double wz,
|
||||
double mustBeat, out double bestMin)
|
||||
{
|
||||
NavPoint? best = null;
|
||||
bestMin = mustBeat;
|
||||
foreach (var corner in CornerCandidates(geo, wx, wy, wz))
|
||||
{
|
||||
if (PointClearance(geo, corner) <= mustBeat) continue;
|
||||
if (TurnsBack(a, corner, b)) continue;
|
||||
double m = Math.Min(LegLeast(geo, a, corner, out _, out _, out _), LegLeast(geo, corner, b, out _, out _, out _));
|
||||
if (m > bestMin) { bestMin = m; best = corner; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// A corner that sends the walk back more than 120 degrees: a detour round something the
|
||||
// map draws but the character walks through (render faces across a ramp at 0x6544), not a
|
||||
// way round a corner.
|
||||
private static bool TurnsBack(NavPoint a, NavPoint corner, NavPoint b)
|
||||
{
|
||||
double ux = corner.EW - a.EW, uy = corner.NS - a.NS, vx = b.EW - corner.EW, vy = b.NS - corner.NS;
|
||||
double lu = Math.Sqrt(ux * ux + uy * uy), lv = Math.Sqrt(vx * vx + vy * vy);
|
||||
if (lu < 1e-12 || lv < 1e-12) return false;
|
||||
return (ux * vx + uy * vy) / (lu * lv) < Math.Cos(120.0 * Math.PI / 180.0);
|
||||
}
|
||||
|
||||
private static double LegLeast(DungeonGeometry geo, NavPoint a, NavPoint b, out double wx, out double wy, out double wz)
|
||||
=> geo.LegClearance(DungeonGeometry.NavToWorld(a.EW), DungeonGeometry.NavToWorld(a.NS), a.Z * 240.0,
|
||||
DungeonGeometry.NavToWorld(b.EW), DungeonGeometry.NavToWorld(b.NS), b.Z * 240.0,
|
||||
WallClearance, LegEndSkip, out wx, out wy, out wz);
|
||||
|
||||
private static double PointClearance(DungeonGeometry geo, NavPoint p)
|
||||
=> geo.ClearanceMemo(DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS), p.Z * 240.0, WallClearance + 0.5);
|
||||
|
||||
// A big room (its cells spread over 10 m or more) left again close to where it was entered is looked into: a
|
||||
// walk to its middle and back. A straight crossing to a nearby opening would only skirt
|
||||
// it (the patrol hunts; the old cell walk went all round such rooms). Also any room left
|
||||
|
|
@ -464,11 +579,11 @@ internal static partial class DungeonPathfinder
|
|||
DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, out approach, out _, out bool n0);
|
||||
DoorwayPoints(graph, geo, rooms, steps[j].From, steps[j].To, out _, out exit, out bool n1);
|
||||
narrow = n0 || n1;
|
||||
var doors = new List<(DungeonDoorway Door, uint From)>();
|
||||
var doors = new List<(DungeonDoorway Door, uint From, int Step)>();
|
||||
for (int k = i; k <= j; k++)
|
||||
{
|
||||
if (!geo.TryGetDoorway(steps[k].From, steps[k].To, out var d)) continue;
|
||||
doors.Add((d, steps[k].From));
|
||||
doors.Add((d, steps[k].From, k));
|
||||
narrow |= !d.IsWide;
|
||||
}
|
||||
bool turns = false;
|
||||
|
|
@ -479,7 +594,23 @@ internal static partial class DungeonPathfinder
|
|||
turns = ax * bx + ay * by < Math.Cos(25.0 * Math.PI / 180.0);
|
||||
}
|
||||
if (turns)
|
||||
foreach (var (d, _) in doors) middle.Add(WorldPoint(d.X, d.Y, d.Z, !d.IsWide));
|
||||
{
|
||||
// The openings' centres, and between two of them the way through the room they
|
||||
// share: the straight line from one centre to the next cut the inside corner of a
|
||||
// bend (crypt corners: an L of two junction pieces, the line through its wall).
|
||||
NavPoint? prevM = null;
|
||||
int prevStep = -1;
|
||||
foreach (var (d, _, k) in doors)
|
||||
{
|
||||
var m = Tag(WorldPoint(d.X, d.Y, d.Z, !d.IsWide), "run-opening");
|
||||
if (prevM != null && k == prevStep + 1
|
||||
&& rooms.RoomOf.TryGetValue(steps[prevStep].To, out int ra) && rooms.RoomOf.TryGetValue(steps[k].From, out int rb) && ra == rb)
|
||||
PullThrough(middle, graph, geo, rooms, rooms.Cells[ra], prevM, steps[prevStep].To, m, steps[k].From);
|
||||
Append(middle, m);
|
||||
prevM = m;
|
||||
prevStep = k;
|
||||
}
|
||||
}
|
||||
if (narrow) { approach.Doorway = true; exit.Doorway = true; }
|
||||
}
|
||||
|
||||
|
|
@ -499,27 +630,68 @@ internal static partial class DungeonPathfinder
|
|||
{
|
||||
var (nx, ny) = d.NormalFrom(a);
|
||||
narrow = !d.IsWide;
|
||||
double sa = PickStandoff(geo, rooms, a, d, -nx, -ny);
|
||||
double sb = PickStandoff(geo, rooms, b, d, nx, ny);
|
||||
approach = WorldPoint(d.X - nx * sa, d.Y - ny * sa, d.Z, narrow);
|
||||
exit = WorldPoint(d.X + nx * sb, d.Y + ny * sb, d.Z, narrow);
|
||||
approach = Tag(DoorwayPoint(geo, rooms, a, d, -nx, -ny, narrow), "approach");
|
||||
exit = Tag(DoorwayPoint(geo, rooms, b, d, nx, ny, narrow), "exit");
|
||||
return true;
|
||||
}
|
||||
|
||||
var na = graph[a]; var nb = graph[b];
|
||||
double dNS = nb.NS - na.NS, dEW = nb.EW - na.EW, dZ = nb.Z - na.Z;
|
||||
approach = new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.3, EW = na.EW + dEW * 0.3, Z = (na.Z + dZ * 0.3) / 240.0 };
|
||||
exit = new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.5, EW = na.EW + dEW * 0.5, Z = (na.Z + dZ * 0.5) / 240.0 };
|
||||
approach = Tag(new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.3, EW = na.EW + dEW * 0.3, Z = (na.Z + dZ * 0.3) / 240.0 }, "cell-fallback");
|
||||
exit = Tag(new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.5, EW = na.EW + dEW * 0.5, Z = (na.Z + dZ * 0.5) / 240.0 }, "cell-fallback");
|
||||
PushOffWalls(geo, approach, RoomCells(rooms, a), CornerPushMax);
|
||||
PushOffWalls(geo, exit, null, CornerPushMax); // on the line between the two rooms
|
||||
return false;
|
||||
}
|
||||
|
||||
// The longest standoff whose point is on the floor of the cell's room (or the shortest).
|
||||
private static double PickStandoff(DungeonGeometry geo, DungeonRooms rooms, uint cell, DungeonDoorway d, double dirX, double dirY)
|
||||
/// <summary>
|
||||
/// The doorway point on <paramref name="cell"/>'s side of the opening: on its centre line,
|
||||
/// at the longest standoff (4 m down to 1 m) that is on the room's floor and keeps
|
||||
/// WallClearance from every wall. Where no standoff does (a short bend or junction cell:
|
||||
/// the centre line runs into the bend's outer wall), the clearest one, pushed off the walls
|
||||
/// (in a corridor too narrow for the clearance, onto its middle).
|
||||
/// </summary>
|
||||
private static NavPoint DoorwayPoint(DungeonGeometry geo, DungeonRooms rooms, uint cell, DungeonDoorway d,
|
||||
double dirX, double dirY, bool narrow)
|
||||
{
|
||||
var cells = rooms.RoomOf.TryGetValue(cell, out int r) ? (IEnumerable<uint>)rooms.Cells[r] : new[] { cell };
|
||||
foreach (double s in DoorwayStandoffs)
|
||||
if (geo.OnFloorOfAny(cells, d.X + dirX * s, d.Y + dirY * s, d.Z)) return s;
|
||||
return DoorwayStandoffs[DoorwayStandoffs.Length - 1];
|
||||
var cells = RoomCells(rooms, cell);
|
||||
double s = PickStandoff(geo, cells, d, dirX, dirY, out double clearance);
|
||||
var p = WorldPoint(d.X + dirX * s, d.Y + dirY * s, d.Z, narrow);
|
||||
if (clearance < WallClearance) PushOffWalls(geo, p, cells, DoorwayPushMax);
|
||||
return p;
|
||||
}
|
||||
|
||||
private static IReadOnlyCollection<uint> RoomCells(DungeonRooms rooms, uint cell)
|
||||
=> rooms.RoomOf.TryGetValue(cell, out int r) ? rooms.Cells[r] : new[] { cell };
|
||||
|
||||
// The longest standoff whose point is on the floor of the cell's room with WallClearance;
|
||||
// else the one with the most clearance (the longer of near ties); else the shortest.
|
||||
internal static double PickStandoff(DungeonGeometry geo, IReadOnlyCollection<uint> cells, DungeonDoorway d,
|
||||
double dirX, double dirY, out double clearance)
|
||||
{
|
||||
double bestS = -1;
|
||||
clearance = 0;
|
||||
for (double s = DoorwayStandoffLongest; s >= DoorwayStandoffShortest - 1e-9; s -= DoorwayStandoffStep)
|
||||
{
|
||||
double px = d.X + dirX * s, py = d.Y + dirY * s;
|
||||
if (!geo.OnFloorOfAny(cells, px, py, d.Z)) continue;
|
||||
double c = geo.ClearanceMemo(px, py, d.Z, WallClearance + 0.5);
|
||||
if (c >= WallClearance) { clearance = c; return s; }
|
||||
if (bestS < 0 || c > clearance + 0.05) { bestS = s; clearance = c; }
|
||||
}
|
||||
return bestS > 0 ? bestS : DoorwayStandoffShortest;
|
||||
}
|
||||
|
||||
/// <summary>Moves a point (in place) to WallClearance from walls and floor edges, at most
|
||||
/// <paramref name="maxMove"/>, staying on the floor of <paramref name="cells"/> when given.</summary>
|
||||
private static void PushOffWalls(DungeonGeometry geo, NavPoint p, IReadOnlyCollection<uint>? cells, double maxMove)
|
||||
{
|
||||
double x = DungeonGeometry.NavToWorld(p.EW), y = DungeonGeometry.NavToWorld(p.NS);
|
||||
double ox = x, oy = y;
|
||||
geo.PushClear(ref x, ref y, p.Z * 240.0, WallClearance, maxMove, cells);
|
||||
if (x == ox && y == oy) return;
|
||||
p.EW = DungeonGeometry.WorldToNav(x);
|
||||
p.NS = DungeonGeometry.WorldToNav(y);
|
||||
}
|
||||
|
||||
// ── Crossing a room ──────────────────────────────────────────────────────
|
||||
|
|
@ -552,48 +724,76 @@ internal static partial class DungeonPathfinder
|
|||
|
||||
internal static Action<string>? Trace;
|
||||
|
||||
// Legs across a room keep WallClearance either side where the room allows: the straight
|
||||
// line, else the room's cells string-pulled with every leg that clear. Where the room is
|
||||
// too tight for that, the crossing as before (0.5 m either side).
|
||||
private static void PullThrough(List<NavPoint> pts, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
|
||||
DungeonRooms rooms, List<uint> cells, NavPoint from, uint fromCell, NavPoint to, uint toCell)
|
||||
{
|
||||
if (Clear(geo, cells, from, to)) return;
|
||||
if (Clear(geo, cells, from, to, WallClearance)) return;
|
||||
|
||||
// Through the room's own cells: the openings between them (or cell-centre midpoints).
|
||||
// Through the room's own cells: the openings between them (or cell-centre midpoints),
|
||||
// pushed off the walls like every other point.
|
||||
var cellPath = CellBfs(graph, rooms, fromCell, toCell);
|
||||
var corners = new List<NavPoint>();
|
||||
for (int i = 0; i + 1 < cellPath.Count; i++)
|
||||
{
|
||||
uint a = cellPath[i], b = cellPath[i + 1];
|
||||
if (geo.TryGetDoorway(a, b, out var d)) corners.Add(WorldPoint(d.X, d.Y, d.Z, false));
|
||||
NavPoint corner;
|
||||
if (geo.TryGetDoorway(a, b, out var d)) corner = Tag(WorldPoint(d.X, d.Y, d.Z, false), "pull-opening");
|
||||
else
|
||||
{
|
||||
var na = graph[a]; var nb = graph[b];
|
||||
corners.Add(new NavPoint { Type = NavPointType.Point, NS = (na.NS + nb.NS) * 0.5, EW = (na.EW + nb.EW) * 0.5, Z = (na.Z + nb.Z) * 0.5 / 240.0 });
|
||||
corner = Tag(new NavPoint { Type = NavPointType.Point, NS = (na.NS + nb.NS) * 0.5, EW = (na.EW + nb.EW) * 0.5, Z = (na.Z + nb.Z) * 0.5 / 240.0 }, "pull-midpoint");
|
||||
}
|
||||
PushOffWalls(geo, corner, cells, CornerPushMax);
|
||||
corners.Add(corner);
|
||||
}
|
||||
corners.Add(to);
|
||||
|
||||
// String-pull: from the anchor, the farthest corner in a clear straight line.
|
||||
var strict = new List<NavPoint>();
|
||||
if (StringPull(strict, geo, cells, from, corners, WallClearance))
|
||||
{
|
||||
foreach (var p in strict) Append(pts, p);
|
||||
return;
|
||||
}
|
||||
if (Clear(geo, cells, from, to, CrossingClearance)) return;
|
||||
var loose = new List<NavPoint>();
|
||||
StringPull(loose, geo, cells, from, corners, CrossingClearance);
|
||||
foreach (var p in loose) Append(pts, p);
|
||||
}
|
||||
|
||||
// From the anchor, the farthest corner in a clear straight line, and on; the last corner
|
||||
// (the end) not included. True when every leg of the result is clear.
|
||||
private static bool StringPull(List<NavPoint> outPts, DungeonGeometry geo, List<uint> cells, NavPoint from,
|
||||
List<NavPoint> corners, double clearance)
|
||||
{
|
||||
var to = corners[corners.Count - 1];
|
||||
if (Clear(geo, cells, from, to, clearance)) return true;
|
||||
NavPoint anchor = from;
|
||||
int at = 0;
|
||||
bool allClear = true;
|
||||
int guard = corners.Count + 2;
|
||||
while (at < corners.Count - 1 && guard-- > 0)
|
||||
{
|
||||
int pick = at; // always move on at least one corner
|
||||
for (int k = corners.Count - 1; k > at; k--)
|
||||
if (Clear(geo, cells, anchor, corners[k])) { pick = k; break; }
|
||||
if (pick == corners.Count - 1) break; // the end is in sight
|
||||
Append(pts, corners[pick]);
|
||||
int pick = -1;
|
||||
for (int k = corners.Count - 1; k >= at; k--)
|
||||
if (Clear(geo, cells, anchor, corners[k], clearance)) { pick = k; break; }
|
||||
if (pick < 0) { pick = at; allClear = false; } // always move on at least one corner
|
||||
if (pick == corners.Count - 1) return allClear; // the end is in sight
|
||||
outPts.Add(corners[pick]);
|
||||
anchor = corners[pick];
|
||||
at = pick + 1;
|
||||
if (Clear(geo, cells, anchor, to)) break;
|
||||
if (Clear(geo, cells, anchor, to, clearance)) return allClear;
|
||||
}
|
||||
return allClear && Clear(geo, cells, anchor, to, clearance);
|
||||
}
|
||||
|
||||
private static bool Clear(DungeonGeometry geo, List<uint> cells, NavPoint a, NavPoint b)
|
||||
private static bool Clear(DungeonGeometry geo, List<uint> cells, NavPoint a, NavPoint b, double clearance)
|
||||
=> geo.SegmentClear(cells,
|
||||
DungeonGeometry.NavToWorld(a.EW), DungeonGeometry.NavToWorld(a.NS), a.Z * 240.0,
|
||||
DungeonGeometry.NavToWorld(b.EW), DungeonGeometry.NavToWorld(b.NS), b.Z * 240.0,
|
||||
CrossingClearance);
|
||||
clearance);
|
||||
|
||||
// Shortest cell path inside one room (inclusive), or just [from, to] when there is none.
|
||||
private static List<uint> CellBfs(Dictionary<uint, DungeonNavNode> graph, DungeonRooms rooms, uint from, uint to)
|
||||
|
|
@ -621,7 +821,7 @@ internal static partial class DungeonPathfinder
|
|||
}
|
||||
|
||||
// The point a patrol visits to look into a room: the middle of its cell centres when that
|
||||
// is on its floor, else the cell centre nearest that middle.
|
||||
// is on its floor, else the cell centre nearest that middle; then pushed off the walls.
|
||||
private static NavPoint? RoomMiddle(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, List<uint> cells, out uint midCell)
|
||||
{
|
||||
midCell = 0;
|
||||
|
|
@ -646,13 +846,27 @@ internal static partial class DungeonPathfinder
|
|||
}
|
||||
if (nearest == null) return null;
|
||||
midCell = nearest.CellId;
|
||||
if (geo.OnCellFloor(nearest.CellId, sx, sy, sz) || geo.OnFloorOfAny(cells, sx, sy, sz) && !geo.HasFloor(nearest.CellId))
|
||||
return WorldPoint(sx, sy, sz, false);
|
||||
return WorldPoint(DungeonGeometry.NavToWorld(nearest.EW), DungeonGeometry.NavToWorld(nearest.NS), nearest.Z, false);
|
||||
NavPoint mid = geo.OnCellFloor(nearest.CellId, sx, sy, sz) || geo.OnFloorOfAny(cells, sx, sy, sz) && !geo.HasFloor(nearest.CellId)
|
||||
? Tag(WorldPoint(sx, sy, sz, false), "room-middle")
|
||||
: Tag(WorldPoint(DungeonGeometry.NavToWorld(nearest.EW), DungeonGeometry.NavToWorld(nearest.NS), nearest.Z, false), "room-middle-cell");
|
||||
// A one-cell dead end's origin is inside its end cap; a big room's middle can be a pillar.
|
||||
PushOffWalls(geo, mid, cells, MiddlePushMax);
|
||||
return mid;
|
||||
}
|
||||
|
||||
// ── Point list helpers ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Offline tools (PatrolProof) set this to learn which rule laid each point:
|
||||
/// approach, exit, run-opening, pull-opening, pull-midpoint, room-middle, room-middle-cell,
|
||||
/// cell-fallback.</summary>
|
||||
internal static Dictionary<NavPoint, string>? KindLog;
|
||||
|
||||
private static NavPoint Tag(NavPoint p, string kind)
|
||||
{
|
||||
if (KindLog != null) KindLog[p] = kind;
|
||||
return p;
|
||||
}
|
||||
|
||||
private static NavPoint WorldPoint(double wx, double wy, double wz, bool doorway) => new()
|
||||
{
|
||||
Type = NavPointType.Point,
|
||||
|
|
|
|||
|
|
@ -634,6 +634,11 @@ internal static partial class DungeonPathfinder
|
|||
}
|
||||
|
||||
SimplifyRoute(route);
|
||||
// The map geometry is there but the room patrol found nothing to walk (the start is cut
|
||||
// off from every doorway): the cell walk's points still keep off the walls.
|
||||
if (geo != null)
|
||||
foreach (var p in route.Points)
|
||||
PushOffWalls(geo, Tag(p, "cell-walk"), null, CornerPushMax);
|
||||
return route;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ using System.Collections.Generic;
|
|||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Loot.VTank;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
|
|
@ -13,7 +15,8 @@ namespace RynthCore.Plugin.RynthAi.Loot;
|
|||
/// hot reload after a save. The engine calls the exports (PluginExports, "Loot
|
||||
/// editor bridge") from its UI data hub on the plugin pump thread, the same
|
||||
/// thread as the plugin tick; the lock only guards against any other caller.
|
||||
/// Nothing here touches AC.
|
||||
/// Nothing here touches AC: what it needs about items (the "Add to loot
|
||||
/// profile" popup, /ra loot add) comes through <see cref="Items"/>.
|
||||
/// </summary>
|
||||
internal sealed class LootEditorBridge
|
||||
{
|
||||
|
|
@ -30,6 +33,15 @@ internal sealed class LootEditorBridge
|
|||
private long _nextDiskCheck;
|
||||
private string? _vocabJson;
|
||||
|
||||
// "Add to loot profile": the popup's current rule, and a second session for a
|
||||
// target profile the editor doesn't have open (so the editor's view never changes).
|
||||
private LootEditItemDraft? _draft;
|
||||
private long _draftRevision;
|
||||
private LootEditSession? _other;
|
||||
|
||||
/// <summary>RynthAi's item lookups for "Add to loot profile". Set once by the plugin.</summary>
|
||||
public LootItemHooks Items { get; set; } = new();
|
||||
|
||||
public LootEditorBridge(Func<string> inUsePath, Action<string> onSaved, params string[] vendorFolders)
|
||||
{
|
||||
_inUsePath = inUsePath;
|
||||
|
|
@ -56,10 +68,13 @@ internal sealed class LootEditorBridge
|
|||
if (_followInUse && !_session.IsDirty && inUse.Length > 0 && !LootEditSession.SamePath(inUse, _session.Path))
|
||||
_session.Open(inUse);
|
||||
}
|
||||
return unchecked((int)_session.Revision);
|
||||
return unchecked((int)StateRevision);
|
||||
}
|
||||
}
|
||||
|
||||
// The session's revision plus the popup draft's: both only grow, so the sum moves when either does.
|
||||
private long StateRevision => _session.Revision + _draftRevision;
|
||||
|
||||
public string StateJson()
|
||||
{
|
||||
lock (_sync)
|
||||
|
|
@ -67,6 +82,8 @@ internal sealed class LootEditorBridge
|
|||
string inUse = InUse;
|
||||
if (!_session.IsOpen && _followInUse && inUse.Length > 0) _session.Open(inUse);
|
||||
LootEditState state = _session.BuildState(inUse, ListFiles());
|
||||
state.Revision = StateRevision;
|
||||
state.ItemDraft = _draft;
|
||||
return JsonSerializer.Serialize(state, LootEditJsonContext.Default.LootEditState);
|
||||
}
|
||||
}
|
||||
|
|
@ -87,6 +104,11 @@ internal sealed class LootEditorBridge
|
|||
{
|
||||
LootEditCommand? cmd = JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditCommand);
|
||||
if (cmd == null) return;
|
||||
if (cmd.Op is "item_preview" or "item_add" or "item_close")
|
||||
{
|
||||
ItemCommand(cmd);
|
||||
return;
|
||||
}
|
||||
string? saved = null;
|
||||
lock (_sync)
|
||||
{
|
||||
|
|
@ -115,6 +137,147 @@ internal sealed class LootEditorBridge
|
|||
if (saved != null) _onSaved(saved);
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Add to loot profile (a clicked item)
|
||||
// =====================================================================
|
||||
|
||||
private void ItemCommand(LootEditCommand cmd)
|
||||
{
|
||||
LootEditItemDraft? added = null;
|
||||
lock (_sync)
|
||||
{
|
||||
if (cmd.Op == "item_close")
|
||||
{
|
||||
if (_draft == null) return;
|
||||
_draft = null;
|
||||
_draftRevision++;
|
||||
return;
|
||||
}
|
||||
LootEditItemDraft d = BuildDraft(cmd.Item ?? new LootEditItemRequest(), cmd.Op == "item_add");
|
||||
_draft = d;
|
||||
_draftRevision++;
|
||||
if (d.Added) added = d;
|
||||
}
|
||||
if (added != null) Items.Added(added);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra loot add: the popup's preview (<paramref name="add"/> false) or Add,
|
||||
/// without touching the popup's draft. After an add, Items.Added has run
|
||||
/// (chat line, reload) before this returns.
|
||||
/// </summary>
|
||||
public LootEditItemDraft AddItem(LootEditItemRequest request, bool add)
|
||||
{
|
||||
LootEditItemDraft d;
|
||||
lock (_sync) d = BuildDraft(request, add);
|
||||
if (d.Added) Items.Added(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>The rule the item makes, where it goes, and (add) the insert and save. Under the lock.</summary>
|
||||
private LootEditItemDraft BuildDraft(LootEditItemRequest req, bool add)
|
||||
{
|
||||
var d = new LootEditItemDraft { Seq = req.Seq };
|
||||
uint id = req.ItemId != 0 ? req.ItemId : Items.SelectedItemId();
|
||||
if (id == 0) return Refuse(d, "No item selected. Click an item first.");
|
||||
d.ItemId = id;
|
||||
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
|
||||
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like);
|
||||
if (facts == null) return Refuse(d, $"RynthAi doesn't know item 0x{id:X8} yet. Select it again in a moment.");
|
||||
d.ItemName = facts.Name;
|
||||
d.ClassName = LootItemRules.ClassName(facts.ObjectClass);
|
||||
d.Stackable = facts.Stackable;
|
||||
|
||||
string inUse = InUse;
|
||||
string target = req.ToOpenProfile && _session.IsOpen ? _session.Path : inUse;
|
||||
if (target.Length == 0) return Refuse(d, "No loot profile selected. Pick one in RynthAi first.");
|
||||
d.TargetPath = target;
|
||||
d.TargetFile = Path.GetFileName(target);
|
||||
d.TargetInUse = LootEditSession.SamePath(target, inUse);
|
||||
if (!File.Exists(target)) return Refuse(d, $"Loot profile not found: {target}");
|
||||
LootEditSession s = SessionFor(target);
|
||||
if (!s.IsOpen || !LootEditSession.SamePath(s.Path, target)) return Refuse(d, s.Message);
|
||||
d.Format = s.Format;
|
||||
if (!s.CanInsert) return Refuse(d, $"{d.TargetFile} is read-only here: {s.ReadOnlyReason}");
|
||||
|
||||
var options = new LootItemRuleOptions
|
||||
{
|
||||
Match = match,
|
||||
Action = req.Action == 0 ? null : (VTankLootAction)req.Action,
|
||||
KeepCount = req.KeepCount < 0 ? null : req.KeepCount,
|
||||
RuleName = req.RuleName,
|
||||
};
|
||||
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
|
||||
if (draft == null) return Refuse(d, error);
|
||||
d.Match = (int)draft.Match;
|
||||
d.Action = (int)draft.Action;
|
||||
d.KeepCount = draft.KeepCount;
|
||||
d.RuleName = draft.Rule.Name;
|
||||
d.DefaultRuleName = draft.DefaultName;
|
||||
d.Preview = LootItemRules.PreviewLines(draft.Rule);
|
||||
d.Notes.AddRange(draft.Notes);
|
||||
|
||||
bool json = s.Format == "json";
|
||||
LootRule? native = null;
|
||||
if (json)
|
||||
{
|
||||
var dropped = new List<string>();
|
||||
native = LootItemRules.ToNative(draft.Rule, dropped);
|
||||
foreach (string c in dropped) d.Notes.Add($"Left out (the native format has no such condition): {c}");
|
||||
if (native == null) return Refuse(d, "The native format can't hold any of this rule's conditions.");
|
||||
}
|
||||
|
||||
// Just before the first rule that decides this item now (first match wins), else the end.
|
||||
int count = s.RuleCount;
|
||||
int first = json ? Items.FirstMatchNative(id, s.JsonProfile!) : Items.FirstMatchUtl(id, s.Profile!);
|
||||
if (first >= count) first = -1;
|
||||
int at = first >= 0 ? first : count;
|
||||
d.InsertAt = at;
|
||||
d.RuleCount = count;
|
||||
if (first >= 0)
|
||||
{
|
||||
string name = json ? s.JsonProfile!.Rules[first].Name : s.Profile!.Rules[first].Name;
|
||||
name = string.IsNullOrWhiteSpace(name) ? $"#{first + 1}" : name.Trim();
|
||||
string action = json ? s.JsonProfile!.Rules[first].Action.ToString() : LootRuleText.ActionName(s.Profile!.Rules[first].Action);
|
||||
bool same = json ? LootItemRules.SameRule(native!, s.JsonProfile!.Rules[first]) : LootItemRules.SameRule(draft.Rule, s.Profile!.Rules[first]);
|
||||
if (same) return Refuse(d, $"Already there: rule {first + 1} '{name}' does exactly this.");
|
||||
d.OrderNote = $"Goes in at {at + 1} of {count + 1}, just before rule {first + 1} '{name}' ({action}), which takes this item now. "
|
||||
+ "Rules are checked top to bottom and the first match wins, so this is the lowest spot where the new rule still decides; the rules above it are untouched.";
|
||||
}
|
||||
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.";
|
||||
|
||||
if (s.IsDirty) return Refuse(d, $"The Loot Editor has unsaved changes in {d.TargetFile}. Save or discard them first.");
|
||||
d.Ok = true;
|
||||
if (!add) return d;
|
||||
|
||||
if (!s.InsertAndSave(draft.Rule, native, at)) return Refuse(d, s.Message);
|
||||
d.Added = true;
|
||||
d.Message = $"Added loot rule '{draft.Rule.Name}' to {d.TargetFile}";
|
||||
return d;
|
||||
}
|
||||
|
||||
private static LootEditItemDraft Refuse(LootEditItemDraft d, string error)
|
||||
{
|
||||
d.Ok = false;
|
||||
d.Error = error;
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (_session.IsOpen && LootEditSession.SamePath(_session.Path, target))
|
||||
{
|
||||
_session.CheckDisk();
|
||||
return _session;
|
||||
}
|
||||
_other ??= new LootEditSession();
|
||||
if (_other.IsOpen && LootEditSession.SamePath(_other.Path, target)) _other.CheckDisk();
|
||||
else _other.Open(target, force: true);
|
||||
return _other;
|
||||
}
|
||||
|
||||
/// <summary>LootProfiles (*.utl, *.json), then AutoVendor profiles, then the open file if it is elsewhere.</summary>
|
||||
private List<LootEditFile> ListFiles()
|
||||
{
|
||||
|
|
@ -144,3 +307,18 @@ internal sealed class LootEditorBridge
|
|||
return files;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the loot editor bridge asks RynthAi about items (the plugin fills these in).</summary>
|
||||
internal sealed class LootItemHooks
|
||||
{
|
||||
/// <summary>The item selected in the game, or 0.</summary>
|
||||
public Func<uint> SelectedItemId { get; set; } = () => 0;
|
||||
/// <summary>The item's facts from the object cache, or null. The bool: "items like this" (ask for an ID if it isn't identified).</summary>
|
||||
public Func<uint, bool, LootItemFacts?> Facts { get; set; } = (_, _) => null;
|
||||
/// <summary>The first rule of the .utl profile that matches the item now, or -1.</summary>
|
||||
public Func<uint, VTankLootProfile, int> FirstMatchUtl { get; set; } = (_, _) => -1;
|
||||
/// <summary>The first rule of the native profile that matches the item now, or -1.</summary>
|
||||
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; } = _ => { };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -219,7 +219,10 @@ internal sealed class NavigationEngine
|
|||
private const double DoorwayTurnEnter = 8.0, DoorwayTurnExit = 3.0;
|
||||
private bool _steerDoorway;
|
||||
private double TurnEnterNow => _steerDoorway ? Math.Min(BigTurnEnter, DoorwayTurnEnter) : BigTurnEnter;
|
||||
private double TurnExitNow => _steerDoorway ? Math.Min(BigTurnExit, DoorwayTurnExit) : BigTurnExit;
|
||||
// Never tighter than the turn dead zone (+0.5): the servo stops turning inside DeadZone, so an
|
||||
// exit below it left the error between the two, no turn and no run: nav stood still until the
|
||||
// player tapped forward (doorway exit 3 vs dead zone 4, 2026-10-04).
|
||||
private double TurnExitNow => Math.Max(DeadZone + 0.5, _steerDoorway ? Math.Min(BigTurnExit, DoorwayTurnExit) : BigTurnExit);
|
||||
private double SweepMult => Math.Max(1.0, _settings.NavSweepMult);
|
||||
// Nav point reach (FollowNavMin, VTank's "Follow/Nav Min Distance"): how close to get to
|
||||
// each nav point before moving on. Floored at the Settings minimum (0.5); it used to be
|
||||
|
|
@ -2752,12 +2755,21 @@ internal sealed class NavigationEngine
|
|||
// MOVEMENT HELPERS
|
||||
// ══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
// Auto-run re-sent this often while nav wants to move. The flag alone trusted that auto-run
|
||||
// stayed on; a cast, a stance change, a corpse use or a server stop turns it off without
|
||||
// telling nav, and nav sat still until the player tapped forward (2026-10-04). Setting it
|
||||
// on when it already is costs nothing; nav only ticks while it's the active activity.
|
||||
private const long ForwardReassertMs = 1000;
|
||||
private long _lastForwardAssertMs;
|
||||
|
||||
private void StartForward()
|
||||
{
|
||||
if (!_isMovingForward)
|
||||
long now = Environment.TickCount64;
|
||||
if (!_isMovingForward || now - _lastForwardAssertMs >= ForwardReassertMs)
|
||||
{
|
||||
_host.SetAutoRun(true);
|
||||
_isMovingForward = true;
|
||||
_lastForwardAssertMs = now;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra lootparse — inspect the selected loot profile");
|
||||
ChatLine("[RynthAi] /ra lootcheckinv — test the loot profile against inventory");
|
||||
ChatLine("[RynthAi] /ra lootcheck — classify selected item (on|off = auto on click)");
|
||||
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item");
|
||||
ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)");
|
||||
ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot");
|
||||
ChatLine("[RynthAi] /ra why — one-glance diagnosis of why the bot is idle/attacking");
|
||||
|
|
@ -1507,7 +1508,17 @@ public sealed partial class RynthAiPlugin
|
|||
internal LootEditorBridge LootEditor => _lootEditor ??= new LootEditorBridge(
|
||||
() => _dashboard?.Settings?.CurrentLootPath ?? string.Empty,
|
||||
OnLootProfileEdited,
|
||||
Vendor.AutoVendorManager.MainProfileDir);
|
||||
Vendor.AutoVendorManager.MainProfileDir)
|
||||
{
|
||||
Items = new LootItemHooks
|
||||
{
|
||||
SelectedItemId = () => Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0,
|
||||
Facts = BuildLootItemFacts,
|
||||
FirstMatchUtl = FirstLootRuleFor,
|
||||
FirstMatchNative = FirstLootRuleFor,
|
||||
Added = OnLootRuleAdded,
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The Loot Editor saved <paramref name="path"/>: drop the cached copies and,
|
||||
|
|
@ -1515,6 +1526,19 @@ public sealed partial class RynthAiPlugin
|
|||
/// Plugin pump thread (the editor's export), the same thread as the tick.
|
||||
/// </summary>
|
||||
private void OnLootProfileEdited(string path)
|
||||
{
|
||||
string name = System.IO.Path.GetFileName(path);
|
||||
if (!ForgetLootProfile(path))
|
||||
{
|
||||
ChatLine($"[RynthAi] Loot Editor saved {name}.");
|
||||
return;
|
||||
}
|
||||
ChatLine($"[RynthAi] Loot Editor saved {name}; reloading it.");
|
||||
ReloadLootProfileInUse(path);
|
||||
}
|
||||
|
||||
/// <summary>Drops the cached copies of <paramref name="path"/>. True when it is the loot profile in use.</summary>
|
||||
private bool ForgetLootProfile(string path)
|
||||
{
|
||||
bool Same(string a) => RynthCore.Loot.Editing.LootEditSession.SamePath(a, path);
|
||||
if (Same(_loadedLootProfilePath))
|
||||
|
|
@ -1527,17 +1551,136 @@ public sealed partial class RynthAiPlugin
|
|||
_nativeLootProfile = null;
|
||||
_nativeLootProfileTime = DateTime.MinValue;
|
||||
}
|
||||
string name = System.IO.Path.GetFileName(path);
|
||||
if (!Same(_dashboard?.Settings?.CurrentLootPath ?? string.Empty))
|
||||
{
|
||||
ChatLine($"[RynthAi] Loot Editor saved {name}.");
|
||||
return;
|
||||
}
|
||||
ChatLine($"[RynthAi] Loot Editor saved {name}; reloading it.");
|
||||
return Same(_dashboard?.Settings?.CurrentLootPath ?? string.Empty);
|
||||
}
|
||||
|
||||
private void ReloadLootProfileInUse(string path)
|
||||
{
|
||||
if (path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) TryLoadNativeLootProfile(out _, out _);
|
||||
else TryLoadLootProfile(string.Empty, out _, out _);
|
||||
}
|
||||
|
||||
// ── Add to loot profile (a clicked item; /ra loot add, the engine's popup) ──
|
||||
|
||||
/// <summary>A rule from "Add to loot profile" was saved: say so, and reload the profile when it is the one in use.</summary>
|
||||
private void OnLootRuleAdded(RynthCore.Loot.Editing.LootEditItemDraft d)
|
||||
{
|
||||
bool inUse = ForgetLootProfile(d.TargetPath);
|
||||
ChatLine($"[RynthAi] {d.Message}{(inUse ? "" : " (not the profile RynthAi loots with)")}.");
|
||||
if (inUse) ReloadLootProfileInUse(d.TargetPath);
|
||||
}
|
||||
|
||||
/// <summary>What a loot rule can be built from: the item's name, class, stack and key properties, from the object cache.</summary>
|
||||
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like)
|
||||
{
|
||||
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
|
||||
if (wo == null) return null;
|
||||
var f = new RynthCore.Loot.Editing.LootItemFacts
|
||||
{
|
||||
Id = wo.Id,
|
||||
Name = wo.Name,
|
||||
ObjectClass = (int)wo.ObjectClass,
|
||||
StackSize = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)),
|
||||
MaxStackSize = Math.Max(1, wo.Values(LongValueKey.MaxStackSize, 1)),
|
||||
};
|
||||
foreach (int key in RynthCore.Loot.Editing.LootItemRules.IntKeys)
|
||||
{
|
||||
int v = wo.Values(key, 0);
|
||||
if (v != 0) f.Ints[key] = v;
|
||||
}
|
||||
foreach (int key in RynthCore.Loot.Editing.LootItemRules.DoubleKeys)
|
||||
{
|
||||
double v = wo.Values((DoubleValueKey)key, 0.0);
|
||||
if (v != 0) f.Doubles[key] = v;
|
||||
}
|
||||
if (like)
|
||||
{
|
||||
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
|
||||
foreach (string n in ctx.GetItemSpellNames(itemId))
|
||||
if (!string.IsNullOrEmpty(n)) f.Spells.Add(n);
|
||||
// Material, workmanship and spells need an ID: ask for one, so the next preview has them.
|
||||
if (Host.HasRequestId && Host.HasHasAppraisalData && !Host.HasAppraisalData(itemId)) Host.RequestId(itemId);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>The first rule of <paramref name="profile"/> that takes the item now (the corpse looter's order), or -1.</summary>
|
||||
private int FirstLootRuleFor(uint itemId, VTankLootProfile profile)
|
||||
{
|
||||
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
|
||||
if (wo == null) return -1;
|
||||
VTankLootEvaluator.FirstMatch(profile, wo, new VTankLootContext(Host, _playerId) { Cache = _objectCache }, out int index);
|
||||
return index;
|
||||
}
|
||||
|
||||
private int FirstLootRuleFor(uint itemId, RynthCore.Loot.LootProfile profile)
|
||||
{
|
||||
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
|
||||
if (wo == null) return -1;
|
||||
for (int i = 0; i < profile.Rules.Count; i++)
|
||||
if (Loot.LootEvaluator.Matches(profile.Rules[i], wo, _charSkills)) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview]: a rule for
|
||||
/// the selected item, straight into the loot profile in use (the defaults: exact
|
||||
/// name and class; Read for scrolls, Keep # one full stack for stacks, else Keep).
|
||||
/// </summary>
|
||||
private void HandleLootCommand(string[] parts)
|
||||
{
|
||||
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
|
||||
if (sub != "add")
|
||||
{
|
||||
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item to the loot profile in use");
|
||||
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. preview = show it, add nothing.");
|
||||
ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor.");
|
||||
return;
|
||||
}
|
||||
|
||||
var req = new RynthCore.Loot.Editing.LootEditItemRequest();
|
||||
bool preview = false;
|
||||
for (int i = 3; i < parts.Length; i++)
|
||||
{
|
||||
string w = parts[i].ToLowerInvariant();
|
||||
switch (w)
|
||||
{
|
||||
case "keep": req.Action = (int)VTankLootAction.Keep; break;
|
||||
case "keep#": req.Action = (int)VTankLootAction.KeepUpTo; break;
|
||||
case "salvage": req.Action = (int)VTankLootAction.Salvage; break;
|
||||
case "sell": req.Action = (int)VTankLootAction.Sell; break;
|
||||
case "read": req.Action = (int)VTankLootAction.Read; break;
|
||||
case "name": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Name; break;
|
||||
case "like": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Like; break;
|
||||
case "exact": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.NameAndClass; break;
|
||||
case "preview":
|
||||
case "?": preview = true; break;
|
||||
default:
|
||||
if (int.TryParse(w.TrimStart('#'), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int n) && n >= 0)
|
||||
{
|
||||
req.Action = (int)VTankLootAction.KeepUpTo;
|
||||
req.KeepCount = n;
|
||||
break;
|
||||
}
|
||||
ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like or preview.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
RynthCore.Loot.Editing.LootEditItemDraft d = LootEditor.AddItem(req, add: !preview);
|
||||
if (d.Preview.Count > 0 && (preview || !d.Ok))
|
||||
{
|
||||
ChatLine($"[RynthAi] {d.ItemName} -> {d.TargetFile}:");
|
||||
foreach (string line in d.Preview) ChatLine("[RynthAi] " + line);
|
||||
if (d.OrderNote.Length > 0) ChatLine("[RynthAi] " + d.OrderNote);
|
||||
}
|
||||
foreach (string note in d.Notes) ChatLine("[RynthAi] Note: " + note);
|
||||
if (!d.Ok) ChatLine("[RynthAi] Loot rule not added: " + d.Error);
|
||||
else if (preview) ChatLine("[RynthAi] (preview only; /ra loot add without 'preview' adds it)");
|
||||
else if (d.Added && d.OrderNote.Length > 0) ChatLine("[RynthAi] " + d.OrderNote);
|
||||
// An add's own chat line comes from OnLootRuleAdded.
|
||||
}
|
||||
|
||||
private bool TryLoadNativeLootProfile(out RynthCore.Loot.LootProfile profile, out string loadedPath)
|
||||
{
|
||||
string candidatePath = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"');
|
||||
|
|
|
|||
|
|
@ -524,6 +524,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
|
||||
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
|
||||
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
|
||||
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
|
||||
if (_buffManager != null)
|
||||
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
|
||||
_combatManager.SetCharacterSkills(_charSkills);
|
||||
|
|
@ -1362,6 +1363,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// while nav owns the tick, so it never got to clear these itself.
|
||||
_doorRequestedId = 0;
|
||||
ResetDoorState();
|
||||
// A corpse left open mid-loot is closed, as a player would close its window.
|
||||
try { CloseOpenCorpseOnMacroStop(); }
|
||||
catch (Exception ex) { Host.Log($"[RynthAi] Macro-stop corpse close failed: {ex.Message}"); }
|
||||
try
|
||||
{
|
||||
int busyBefore = Host.HasGetBusyState ? Host.GetBusyState() : -1;
|
||||
|
|
@ -2918,6 +2922,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "lootparse": HandleLootParseCommand(trimmed); break;
|
||||
case "lootcheckinv": HandleLootCheckInventoryCommand(trimmed); break;
|
||||
case "lootcheck": HandleLootCheckSelectedCommand(parts); break;
|
||||
case "loot": HandleLootCommand(parts); break;
|
||||
case "corpseinfo": HandleCorpseInfoCommand(); break;
|
||||
case "corpsecheck": HandleCorpseCheckCommand(parts); break;
|
||||
case "corpseopen": HandleCorpseOpenCommand(); break;
|
||||
|
|
|
|||
|
|
@ -81,6 +81,8 @@ internal static class AutoVendorRules
|
|||
|
||||
// Decal's synthetic LongValueKey ids start at 0x0D000000; RynthAi reads STypes only.
|
||||
internal const int MaxStandardKey = 0xFFFF;
|
||||
// Except Decal's "Type" (0x0D000000), the weenie class id, which RynthAi reads too.
|
||||
internal const int DecalTypeKey = 0x0D000000;
|
||||
|
||||
// RynthAi derives ObjectClass from ITEM_TYPE alone. Decal splits these further
|
||||
// (Misc -> HealingKit/Lockpick, Book -> Scroll/Journal/Sign, Container -> Foci,
|
||||
|
|
@ -126,6 +128,7 @@ internal static class AutoVendorRules
|
|||
case VTankNodeTypes.LongValKeyNE:
|
||||
case VTankNodeTypes.LongValKeyFlagExists:
|
||||
{
|
||||
if (TryKey(d, 1, out int wkey) && wkey == DecalTypeKey) return true; // the WCID: always known
|
||||
if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false;
|
||||
if (f.IsVendorListing) return ListingIntKeys.Contains(key);
|
||||
return f.Appraised || PwdIntKeys.Contains(key);
|
||||
|
|
|
|||
Loading…
Reference in a new issue