RynthSuite as of 2026-09-27 (internal 1816d05): AutoVendor (UtilityBelt port), missile/magic facing and arc line of sight, nav waypoint skipping, rebuff batch and item-enchant fixes, crafting fallback, Loot Editor AutoVendor folder and command-line open, release 2026.9.27.2

This commit is contained in:
Tom Bohar 2026-09-27 20:25:46 -04:00
commit d55ffda4ed
33 changed files with 4364 additions and 207 deletions

View file

@ -54,6 +54,7 @@ public enum DoubleValueKey
DamageVariance = 22,
CurrentPowerMod = 23,
AccuracyMod = 24,
MaximumVelocity = 26, // missile launcher launch speed (m/s); known once appraised
WeaponDefense = 29,
UseRadius = 54,
WeaponOffense = 61,
@ -106,17 +107,59 @@ public class WorldObject
// Set by WorldObjectCache when it creates/updates this object
internal WorldObjectCache? Cache { get; set; }
public int Values(LongValueKey key, int defaultValue)
=> Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
/// <summary>
/// Values that answer Values() before any live read (AutoVendor: a vendor-list item
/// built from the engine's vendor snapshot, or an item's known name). Null = live only.
/// </summary>
internal ItemPropertyOverlay? Overlay { get; set; }
public int Values(LongValueKey key, int defaultValue) => Values((int)key, defaultValue);
public int Values(int key, int defaultValue)
=> Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
{
var o = Overlay;
if (o != null)
{
if (o.Ints.TryGetValue(unchecked((uint)key), out int v)) return v;
if (!o.LiveFallback) return defaultValue;
}
return Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
}
public string Values(StringValueKey key, string defaultValue)
=> Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue;
{
var o = Overlay;
if (o != null)
{
if (o.Strings.TryGetValue((uint)key, out string? v)) return v;
if (!o.LiveFallback) return defaultValue;
}
return Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue;
}
public double Values(DoubleValueKey key, double defaultValue)
=> Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue;
{
var o = Overlay;
if (o != null)
{
if (o.Doubles.TryGetValue((uint)key, out double v)) return v;
if (!o.LiveFallback) return defaultValue;
}
return Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue;
}
}
/// <summary>
/// Fixed property values for a <see cref="WorldObject"/>. With LiveFallback off, a key
/// that isn't here reads as the caller's default instead of the client object's value
/// (a vendor-list item carries only what the vendor snapshot holds).
/// </summary>
internal sealed class ItemPropertyOverlay
{
public Dictionary<uint, int> Ints { get; } = new();
public Dictionary<uint, string> Strings { get; } = new();
public Dictionary<uint, double> Doubles { get; } = new();
public bool LiveFallback { get; init; }
}
// ── SpellInfo stub ────────────────────────────────────────────────────────

View file

@ -36,6 +36,10 @@ public class BuffManager : IDisposable
private DateTime _lastBuffStanceAttempt = DateTime.MinValue;
private int _buffStanceConsecutiveFails = 0;
private bool _isForceRebuffing = false;
// Set with _isForceRebuffing when the pass is the automatic batch (one buff fell
// under RebuffSecondsRemaining), not the Force Rebuff button. The batch only tops
// off buffs under RebuffTopOffSecondsRemaining; Force Rebuff recasts everything.
private bool _isAutoBatchRebuff = false;
private int _pendingSpellId = 0;
private Action<string>? _onCastResolved;
@ -475,6 +479,7 @@ public class BuffManager : IDisposable
public void ForceFullRebuff()
{
_isForceRebuffing = true;
_isAutoBatchRebuff = false;
_forceRebuffCastFamilies.Clear();
_buffFailCooldownUntil.Clear(); // explicit recast-all must not be blocked by stale cooldowns
_silentNoShowCounts.Clear(); // give parked families a fresh shot on FR too
@ -496,6 +501,7 @@ public class BuffManager : IDisposable
public void CancelBuffing()
{
_isForceRebuffing = false;
_isAutoBatchRebuff = false;
_isRechargingMana = false;
_isRechargingStamina = false;
_isHealingSelf = false;
@ -810,15 +816,17 @@ public class BuffManager : IDisposable
if (_isForceRebuffing)
{
bool wasAutoBatch = _isAutoBatchRebuff;
_isForceRebuffing = false;
_host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families");
_isAutoBatchRebuff = false;
_host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families{(wasAutoBatch ? " (auto batch)" : "")}");
// Order matters: the flag must already be false (IsBuffActive
// short-circuits on _forceRebuffCastFamilies while it is set, so
// every family would read "active"), and the set must still be
// populated — it is what the audit iterates.
AuditBatchSatisfied();
_forceRebuffCastFamilies.Clear();
_host.WriteToChat("[RynthAi] Force Rebuff Complete.", 1);
_host.WriteToChat(wasAutoBatch ? "[RynthAi] Rebuff complete." : "[RynthAi] Force Rebuff Complete.", 1);
}
}
}
@ -1066,6 +1074,7 @@ public class BuffManager : IDisposable
// no-show → re-park → another auto-batch → loop. Hard-reject
// cooldowns are short-lived (120s) so they expire on their own.
_isForceRebuffing = true;
_isAutoBatchRebuff = true;
_forceRebuffCastFamilies.Clear();
}
@ -1377,13 +1386,23 @@ public class BuffManager : IDisposable
// Force Rebuff: ignore live timers entirely — only spells we've already
// cast THIS rebuff cycle count as "active". The whole point of FR is to
// recast every spell so all timers align to the same start time.
// The automatic batch shares FR's bookkeeping but must NOT recast
// everything: one buff under the threshold used to refresh every buff,
// even ones with 30+ minutes left (2026-09-27). It tops off only buffs
// under RebuffTopOffSecondsRemaining (never less than RebuffSecondsRemaining,
// so the buff that started the batch is always in it) and leaves the rest
// to their own timers.
if (_isForceRebuffing)
return _forceRebuffCastFamilies.Contains(targetSpell.Family);
{
if (_forceRebuffCastFamilies.Contains(targetSpell.Family)) return true;
if (!_isAutoBatchRebuff) return false;
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
}
int targetLevel = GetSpellLevel(targetSpell);
// Recast when remaining duration drops below this many seconds.
// User-configurable via Advanced Settings → Buffing; overridden during
// batch-rebuff passes (CheckAndCastSelfBuffs) to 1200s (20 min).
// batch-rebuff passes (CheckAndCastSelfBuffs) by RebuffTopOffSecondsRemaining.
int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining);
// Tier-upgrade rule (applies to both item enchantments and player buffs):
@ -1664,10 +1683,16 @@ public class BuffManager : IDisposable
// Learn the real ceiling this family lands at (Incantations cap below
// their nominal tier) so IsBuffActive stops chasing an unreachable tier.
// Recorded for EVERY entry read, including one the merge above
// Recorded for every timed entry read, including one the merge above
// discarded — the ceiling is about what this character can land, not
// about which entry currently wins the family slot.
RecordAchievedTier(spellInfo.Family, level);
// about which entry currently wins the family slot. NOT for permanent
// entries: those are item-granted ("Willpower Other I" on gear), not
// something this character cast, and learning their tier as the
// ceiling made a permanent level-1 enchant satisfy the family forever
// (effective target 1, never expires): after a relog with the real
// buff gone, Lucy went 17 minutes without Willpower (2026-09-27).
if (!isPermanent)
RecordAchievedTier(spellInfo.Family, level);
if (isPermanent && _loggedPermanentFamilies.Add(spellInfo.Family))
_host.Log($"[BuffDiag] permanent player enchant tracked: id={spellInfo.Id} '{spellInfo.Name}' (fam={spellInfo.Family}, lvl={level}) — presence-only, not persisted" +

View file

@ -160,7 +160,7 @@ public class CombatManager : IDisposable
// a perfectly good target in ~3 ticks (~1.2s at SpellCastIntervalMs=400).
private bool _offensiveCastThisCycle;
private DateTime _faceStartTime = DateTime.MinValue;
private const double FACE_TIMEOUT_MS = 1000.0; // give up waiting and fire anyway (MISSILE only)
private const double FACE_TIMEOUT_MS = 1000.0; // give up waiting and swing anyway (non-native MELEE only)
private const double FACE_TOLERANCE_DEG = 15.0; // heading error threshold to fire
// ── Magic targeted-cast settle gate (root-cause fix 2026-06-19) ──────────
@ -168,11 +168,11 @@ public class CombatManager : IDisposable
// turn-to-face; a turn/stop MoveToState that lands during that deferred
// windup ORPHANS the cast (DoSpellWords/CreatePlayerSpell never runs) → the
// gesture animates but 0 damage / "You're too busy!" forever. Self-buffs are
// immune (untargeted → synchronous, no turn). Fix: for MAGIC, never cast
// mid-turn — keep turning until actually within angle, then release the turn
// motions and let the stop reach the server (settle tick) BEFORE the cast.
// immune (untargeted → synchronous, no turn). The 2026-06-19 fix turned the
// bot itself until within angle, then released and settled before the cast;
// since 2026-09-27 the bot doesn't turn for magic at all (the server's own
// Rotate does it), and this only settles after releasing a turn melee left held.
private DateTime _faceSettledAt = DateTime.MinValue;
private const double FACE_MAX_WAIT_MS = 2500.0; // safety: heading never converges (jittery point-blank pose) → cast anyway rather than wedge
private const double FACE_SETTLE_MS = 140.0; // let the turn-stop reach the server (≥ one 30Hz tick) before the cast packet
// ── Magic cast cadence guard ────────────────────────────────────────────
@ -665,7 +665,9 @@ public class CombatManager : IDisposable
double maxDist = _settings.MonsterRange;
TargetingFSM.AttackType attackType = TargetingFSM.AttackType.Linear;
if (RaycastInitialized && _raycastSystem?.TargetingFSM != null)
attackType = _raycastSystem.GetAttackType(CurrentCombatMode, "");
attackType = DetermineAttackTypeForLOS();
bool losDebug = _settings.LosDebugLog;
if (losDebug) LogLosDebugWeapon();
foreach (var wo in _worldFilter.GetLandscape())
{
@ -721,14 +723,12 @@ public class CombatManager : IDisposable
if (dist > (isEngaged ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue;
bool losBlocked = false;
if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem != null)
if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem?.TargetingFSM != null)
{
RaycastCheckCount++;
if (_raycastSystem.IsTargetBlocked(_host, (uint)wo.Id, attackType))
{
RaycastBlockCount++;
losBlocked = true;
}
losBlocked = _raycastSystem.TargetingFSM.IsTargetBlocked(_host, (uint)wo.Id, attackType, out var losDetail);
if (losBlocked) RaycastBlockCount++;
if (losDebug) LogLosDebug(wo, losBlocked, losDetail);
}
// Don't blacklist from scan — just exclude from this result.
@ -1337,9 +1337,12 @@ public class CombatManager : IDisposable
private void DropTarget(string reason)
{
if (activeTargetId != 0)
_host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason}");
_host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason} [{DescribeTargetPos(activeTargetId)}]");
activeTargetId = 0;
_lockedTargetId = 0;
// A turn held toward the dropped target must be let go, or the character keeps
// spinning until something else happens to release it.
if (_facingTarget) ClearCombatTurnMotions();
_facingTarget = false;
_returnToPhysicalCombat = false;
_targetLockedAt = DateTime.MinValue;
@ -1775,6 +1778,7 @@ public class CombatManager : IDisposable
fsm.CrossbowArcVelocity = _settings.CrossbowArcVelocity;
fsm.AtlatlArcVelocity = _settings.AtlatlArcVelocity;
fsm.MagicArcVelocity = _settings.MagicArcVelocity;
fsm.MissileArcClearance = _settings.MissileArcClearance;
}
// Deferred predicted kill-shot swap: a cast that armed it is confirmed
@ -1990,39 +1994,19 @@ public class CombatManager : IDisposable
return true;
}
// MAGIC: settle-before-cast facing gate. Never cast mid-turn and
// never let a turn-stop ride alongside the cast packet — both orphan
// the ACE server's deferred targeted-cast windup (root cause of
// "animates but 0 damage / too busy"). Makes combat behave like the
// working self-buff path. Applies regardless of UseNativeAttack
// (native attack is a physical swing; in Magic mode the bot always
// casts, so the facing race is the same with or without it).
if (CurrentCombatMode == CombatMode.Magic)
// MAGIC and MISSILE: the server turns the player to the target itself,
// as retail did — ACE Rotate(target) before a targeted cast (and again
// after the windup if needed) and before the first missile shot and
// between repeat shots. So the bot doesn't turn at all. A client-side
// turn servo on top only fought that rotation: missile characters spun
// in circles between shots (2026-09-27, Lucy, Olthoi swarm at close
// range), and for magic the server waits while the client holds a turn
// (PendingTurnRelease), which is where the "animates but 0 damage / too
// busy" orphaned windups came from. Applies with or without
// UseNativeAttack. Only a turn another mode left held is released — with one
// settle tick before a cast, so the stop doesn't ride with the packet.
if (CurrentCombatMode == CombatMode.Magic || CurrentCombatMode == CombatMode.Missile)
{
double facingError = GetFacingError(activeTargetId);
if (facingError > FACE_TOLERANCE_DEG)
{
FaceTarget(activeTargetId);
if (!_facingTarget)
{
_facingTarget = true;
_faceStartTime = DateTime.Now;
}
// Keep turning until actually within angle. Do NOT "fire
// anyway" while still turning (that was the bug). Only a long
// safety timeout falls through, so a jittery point-blank pose
// can't wedge combat forever.
if ((DateTime.Now - _faceStartTime).TotalMilliseconds < FACE_MAX_WAIT_MS)
{
LastCombatSkipReason = "facing-turning"; // D4 record-only
return true;
}
_host.Log($"[CombatCast] facing did not converge in {FACE_MAX_WAIT_MS:0}ms (err={facingError:0.0}°) — releasing turn + casting anyway");
}
// Within angle (or safety-timed-out). If we were turning, release
// the turn motions and give the stop ONE settle tick to reach the
// server BEFORE the cast packet.
if (_facingTarget)
{
ClearCombatTurnMotions();
@ -2031,7 +2015,8 @@ public class CombatManager : IDisposable
LastCombatSkipReason = "face-settle-release"; // D4 record-only
return true; // settle tick
}
if ((DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS)
if (CurrentCombatMode == CombatMode.Magic
&& (DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS)
{
LastCombatSkipReason = "face-settle-wait"; // D4 record-only
return true; // let the turn-stop settle on the server first
@ -2282,11 +2267,20 @@ public class CombatManager : IDisposable
double bestScore = double.MinValue;
double heldScore = double.MinValue; // scored total for the incumbent, for the switch log
bool incumbentSeen = false;
double acquireRange = Math.Max(1.0, _settings.MonsterRange);
foreach (var c in _scannedTargets)
{
double s = ScoreCandidate(c);
// The incumbent keeps stickiness and commitment only inside MonsterRange. The
// scan holds a locked target out to DisengageDistance (MonsterRange+3 by default)
// so a lone mob at the edge doesn't flip engage/peace, not so it can out-score
// mobs inside the range the user set. Beyond MonsterRange it competes on its
// merits, and any reasonable in-range mob takes over. Before this a target at
// 5-8 m kept +45 and could hold off mobs at 3-5 m (2026-09-27, Olthoi swarm:
// Monster Range 5, one target kept for over a minute, never out of range).
if (c.Id == _lockedTargetId)
{
double meritScore = s;
s += TARGET_SWITCH_STICKINESS;
// Commitment: once we have COMMITTED to the locked target,
// finishing it outranks any small positional edge a fresh mob
@ -2334,6 +2328,8 @@ public class CombatManager : IDisposable
if (!undamaged || (withinFlightWindow && withinUndamagedGrace))
s += DAMAGE_COMMITMENT_BONUS;
if (c.Distance > acquireRange)
s = meritScore; // beyond MonsterRange: no stickiness, no commitment (see above)
heldScore = s;
incumbentSeen = true;
_lockedLastScore = s;
@ -2365,8 +2361,10 @@ public class CombatManager : IDisposable
// up) — if this floods the log, selection is thrashing again and the two
// scores say by how much.
if (_lockedTargetId != 0)
_host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' (score={(heldScore == double.MinValue ? "gone" : heldScore.ToString("0.0"))}) " +
$"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0})");
_host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' (score={(heldScore == double.MinValue ? "gone" : heldScore.ToString("0.0"))}, {DescribeTargetPos(_lockedTargetId)}) " +
$"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, {DescribeTargetPos(bestId)})");
else
_host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, {DescribeTargetPos(bestId)})");
activeTargetId = bestId;
_lockedTargetId = bestId;
@ -2898,21 +2896,92 @@ public class CombatManager : IDisposable
return lines;
}
/// <summary>
/// Attack type for the scan's LOS test. Missile mode names the weapon in hand so the
/// bow/crossbow/atlatl arc and its velocity apply (the scan used to pass "", which made
/// every missile LOS test a straight line). Peace mode with a missile weapon picked counts
/// as missile, so a target acquired from peace is tested with the arc it will be shot on.
/// Magic stays a straight line, as before.
/// </summary>
private TargetingFSM.AttackType DetermineAttackTypeForLOS()
{
if (CurrentCombatMode == CombatMode.Magic)
if (_raycastSystem?.TargetingFSM == null) return TargetingFSM.AttackType.Linear;
int mode = CurrentCombatMode;
WorldObject? weapon = _equippedWeaponId != 0 ? _worldFilter[_equippedWeaponId] : null;
bool missileWeapon = weapon != null && weapon.ObjectClass == AcObjectClass.MissileWeapon;
if (mode == CombatMode.NonCombat && missileWeapon)
mode = CombatMode.Missile;
string weaponName = mode == CombatMode.Missile && missileWeapon ? weapon!.Name ?? "" : "";
return _raycastSystem.GetAttackType(mode, weaponName);
}
// ── LOS / target-distance diagnostics ────────────────────────────────────
// "Far away" can't be judged from the log without positions, so target lock, switch and
// drop lines carry the 3D distance, its horizontal and vertical parts and both cells.
// With LosDebugLog on, the scan also logs each target's LOS verdict (line / arc, rise,
// hit point) when it changes and at most every LosDebugRepeatMs otherwise.
private readonly Dictionary<int, (DateTime At, bool Blocked)> _losDebugLast = new();
private const double LosDebugRepeatMs = 5000;
private const double LosDebugMinGapMs = 1000;
private int _losDebugWeaponId;
/// <summary>"d=6.2m (h=5.9 dz=+1.8) cell=0x61450123 me=0x61450119", or why it can't be measured.</summary>
private string DescribeTargetPos(int targetId)
{
uint pid = _host.GetPlayerId();
if (pid == 0 || targetId == 0) return "pos=?";
if (!_host.TryGetObjectPosition(pid, out uint pc, out float px, out float py, out float pz))
return "pos=? (no player position)";
if (!_host.TryGetObjectPosition((uint)targetId, out uint tc, out float tx, out float ty, out float tz))
return "pos=? (no target position)";
double dx = (((tc >> 24) & 0xFF) * 192.0 + tx) - (((pc >> 24) & 0xFF) * 192.0 + px);
double dy = (((tc >> 16) & 0xFF) * 192.0 + ty) - (((pc >> 16) & 0xFF) * 192.0 + py);
double dz = tz - pz;
double h = Math.Sqrt(dx * dx + dy * dy);
double d = Math.Sqrt(h * h + dz * dz);
return $"d={d:0.0}m (h={h:0.0} dz={dz:+0.0;-0.0;0.0}) cell=0x{tc:X8} me=0x{pc:X8}";
}
private void LogLosDebug(WorldObject wo, bool blocked, in TargetingFSM.LosDetail det)
{
DateTime now = DateTime.Now;
if (_losDebugLast.TryGetValue(wo.Id, out var last))
{
// Get rule from current target name if available
var targetObj = _worldFilter[activeTargetId];
var rule = GetRuleForTarget(targetObj);
if (rule != null && rule.UseArc) return TargetingFSM.AttackType.MagicArc;
return TargetingFSM.AttackType.Linear;
double ms = (now - last.At).TotalMilliseconds;
bool changed = last.Blocked != blocked;
if (ms < LosDebugMinGapMs || (!changed && ms < LosDebugRepeatMs)) return;
}
if (_losDebugLast.Count > 256) _losDebugLast.Clear();
_losDebugLast[wo.Id] = (now, blocked);
if (_raycastSystem?.TargetingFSM != null)
return _raycastSystem.GetAttackType(CurrentCombatMode, "");
string verdict;
if (!det.Checked) verdict = "clear (not tested: no geometry near the path)";
else if (det.LineBlocked) verdict = "BLOCKED line";
else if (det.ArcChecked && det.Arc.OutOfReach) verdict = "BLOCKED arc: out of reach at this velocity";
else if (det.ArcChecked && det.Arc.Blocked) verdict = $"BLOCKED arc: hit {det.Arc.HitAlong:0.0}m out, {det.Arc.HitZ:+0.0;-0.0;0.0}m vs launch";
else verdict = "clear";
return TargetingFSM.AttackType.Linear;
string arcInfo = det.Velocity > 0
? $" v={det.Velocity:0.0} rise={det.Arc.Sag:0.00} apex={det.Arc.Apex:0.00} clr={_settings.MissileArcClearance:0.0}{(det.ArcChecked ? "" : " (flat: line only)")}"
: "";
_host.Log($"[LOS] 0x{(uint)wo.Id:X8} '{wo.Name}' {verdict} | {det.Type}{(det.Dungeon ? " dungeon" : "")}{arcInfo} | {DescribeTargetPos(wo.Id)}");
}
/// <summary>LOS debug: once per missile weapon, what the client knows of its launch speed.</summary>
private void LogLosDebugWeapon()
{
int wid = _equippedWeaponId;
if (wid == 0 || wid == _losDebugWeaponId) return;
var weapon = _worldFilter[wid];
if (weapon == null || weapon.ObjectClass != AcObjectClass.MissileWeapon) return;
_losDebugWeaponId = wid;
double maxVel = _worldFilter.GetDoubleProperty(wid, (uint)DoubleValueKey.MaximumVelocity, 0);
var type = DetermineAttackTypeForLOS();
float setting = _raycastSystem?.TargetingFSM?.VelocityFor(type) ?? 0f;
_host.Log($"[LOS] missile weapon 0x{(uint)wid:X8} '{weapon.Name}': MaximumVelocity={(maxVel > 0 ? maxVel.ToString("0.0") : "unknown (not appraised)")}, " +
$"LOS uses {type} v={setting:0.0}");
}
private void FaceTarget(int targetId)
@ -2961,6 +3030,15 @@ public class CombatManager : IDisposable
_host.SetMotion(MotionTurnLeft, false);
}
/// <summary>Let go of a turn the facing servo is holding. Called when combat stops
/// ticking (macro off), which would otherwise leave the turn held for good.</summary>
public void ReleaseHeldTurn()
{
if (!_facingTarget) return;
_facingTarget = false;
ClearCombatTurnMotions();
}
/// <summary>
/// True while a previously-issued combat cast is still resolving on the ACE
/// server. Serializes magic casts so the next cast's turn/stop motion can't

View file

@ -45,6 +45,7 @@ public class MissileCraftingManager
private const int APPLY_RETRY_MS = 2000;
private const int CRAFT_TIMEOUT_MS = 15000;
private const int EQUIP_DELAY_MS = 500;
private const int ERROR_BACKOFF_MS = 60000;
private int _headBundleId = 0;
private int _shaftBundleId = 0;
@ -69,15 +70,33 @@ public class MissileCraftingManager
public void ProcessCrafting()
{
if (!_settings.EnableMissileCrafting) return;
// While State isn't Idle the plugin holds combat, nav and looting, so turning
// crafting off mid-craft must let go too.
if (!_settings.EnableMissileCrafting)
{
if (State != CraftState.Idle) Reset("Missile crafting turned off");
return;
}
if (IsBusy) return;
switch (State)
// An exception here used to leave State where it was, and the bot stood still
// forever with nothing in chat: say what broke, let go, and try again later.
try
{
case CraftState.Idle: ProcessIdle(); break;
case CraftState.Evaluating: ProcessEvaluating(); break;
case CraftState.Combining: ProcessCombining(); break;
case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break;
switch (State)
{
case CraftState.Idle: ProcessIdle(); break;
case CraftState.Evaluating: ProcessEvaluating(); break;
case CraftState.Combining: ProcessCombining(); break;
case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break;
}
}
catch (Exception ex)
{
string reason = $"Stopped by an error ({ex.GetType().Name}: {ex.Message}); trying again in a minute";
if (State == CraftState.Idle) ChatLog(reason); // Reset only speaks for a craft in progress
Reset(reason);
_lastAmmoCheck = DateTime.Now.AddMilliseconds(ERROR_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
}
}
@ -169,9 +188,22 @@ public class MissileCraftingManager
if (bestCraftable != null)
{ StartCrafting(bestCraftable, inv); return; }
// No ammo at all and only bundles the skill check calls risky: a bow with nothing
// to shoot can't fight, so a combine that may fail beats standing there.
if (tooHard != null)
Reset($"No ammo, and Fletching {fletching?.Buffed} is too low to make {tooHard.OutputName} reliably " +
$"(difficulty {tooHard.Difficulty}; a failed combine destroys both bundles)");
{
int skill = fletching?.Buffed ?? 250;
ChatLog($"No ammo: making {tooHard.OutputName} anyway, about " +
$"{AmmoRecipes.SuccessChance(skill, tooHard.Difficulty):P0} with Fletching {skill} " +
"(a failed combine destroys both bundles)");
StartCrafting(tooHard, inv);
return;
}
if (fletching != null && fletching.Training < 2
&& AmmoRecipes.BestCraftable(inv.Select(i => i.Name), category, 0, out var carried) == null
&& carried != null)
Reset($"No ammo, and Fletching is untrained, so the bundles for {carried.OutputName} can't be combined");
else
Reset("No ammo and no bundles available");
}

View file

@ -903,7 +903,11 @@ public class WorldObjectCache
float dx = gx1 - gx2;
float dy = gy1 - gy2;
float dz = z1 - z2;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
double d = Math.Sqrt(dx * dx + dy * dy + dz * dz);
// A garbage position read (NaN/∞) must read as out of range. NaN fails every
// "dist > limit" test, so it passed both the scan's range gate and Think's
// disengage drop, and a target could be kept at any real distance.
return double.IsFinite(d) ? d : double.MaxValue;
}
/// <summary>Enumerate objects in player's inventory (no physics position).</summary>
@ -1547,7 +1551,7 @@ public class WorldObjectCache
// ── Type-flag item classification ─────────────────────────────────────
private static AcObjectClass ClassifyByItemType(uint typeFlags)
internal static AcObjectClass ClassifyByItemType(uint typeFlags)
{
// Most specific / unambiguous types first
if ((typeFlags & ItemTypePromissoryNote) != 0) return AcObjectClass.TradeNote;

View file

@ -374,16 +374,32 @@ public sealed partial class RynthAiPlugin
public override void OnVendorOpen(uint vendorId)
{
_metaManager?.OnVendorOpen(vendorId);
// AutoVendor prints the open line itself (UB's merchant-info line when it can read the
// vendor, once per open rather than on every list re-send) and may start a session.
var autoVendor = _autoVendor;
if (autoVendor != null)
{
autoVendor.OnVendorOpen(vendorId);
return;
}
string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}";
Host.WriteToChat($"[RynthAi] Vendor open: {label}", 1);
_metaManager?.OnVendorOpen(vendorId);
}
public override void OnVendorClose(uint vendorId)
{
_metaManager?.OnVendorClose(vendorId);
var autoVendor = _autoVendor;
if (autoVendor != null)
{
autoVendor.OnVendorClose(vendorId);
return;
}
string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}";
Host.WriteToChat($"[RynthAi] Vendor closed: {label}", 1);
_metaManager?.OnVendorClose(vendorId);
}
private void TickCorpseOpening()

View file

@ -23,6 +23,9 @@ internal sealed class LegacyAdvancedSettingsUi
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _missileCraftingManager = mgr;
private Func<string>? _autoVendorStatus;
public void SetAutoVendorStatusProvider(Func<string> status) => _autoVendorStatus = status;
public string MissileCraftingState => _missileCraftingManager?.State.ToString() ?? string.Empty;
public bool MissileCraftingActive => _missileCraftingManager?.IsCrafting ?? false;
public string MissileCraftingStatus => _missileCraftingManager?.StatusMessage ?? string.Empty;
@ -60,6 +63,51 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.End();
}
private void RenderVendoring()
{
ImGui.Text("AutoVendor (UtilityBelt)");
ImGui.Separator();
ImGui.Spacing();
string status = _autoVendorStatus?.Invoke() ?? "Not logged in";
ImGui.TextDisabled($"Status: {status}");
ImGui.Spacing();
ImGui.Checkbox("Enabled##AV", ref _settings.AutoVendorEnabled);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\n" +
"Profiles: <Vendor Name>.utl or default.utl in your character's AutoVendor\n" +
"folder, the server folder, or " + Vendor.AutoVendorManager.MainProfileDir + ".");
ImGui.Checkbox("Test Mode (only print what it would do)##AV", ref _settings.AutoVendorTestMode);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Lists what would be bought and sold without trading. Leave this on until\n" +
"the list looks right: selling can't be undone.");
ImGui.Checkbox("Buy##AV", ref _settings.AutoVendorEnableBuying);
ImGui.SameLine();
ImGui.Checkbox("Sell##AV", ref _settings.AutoVendorEnableSelling);
ImGui.Checkbox("Only Sell From Main Pack##AV", ref _settings.AutoVendorOnlyFromMainPack);
ImGui.Checkbox("Show Merchant Info##AV", ref _settings.AutoVendorShowMerchantInfo);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Print the vendor's buy/sell rates and max value when it opens.");
ImGui.Checkbox("Think When Finished##AV", ref _settings.AutoVendorThink);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Send 'AutoVendor finished: <vendor>' (and failures) as a /tell to yourself,\n" +
"so a meta's chat condition can wait for it.");
ImGui.Spacing();
ImGui.Text("/ub vendor open");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Tries##AV", ref _settings.AutoVendorTries))
_settings.AutoVendorTries = Math.Clamp(_settings.AutoVendorTries, 1, 20);
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Time Between Tries (ms)##AV", ref _settings.AutoVendorTriesTime, 250))
_settings.AutoVendorTriesTime = Math.Clamp(_settings.AutoVendorTriesTime, 500, 30000);
ImGui.Spacing();
ImGui.TextDisabled("Never sold: equipped, attuned, bonded, retained, tinkered, imbued,");
ImGui.TextDisabled("inscribed, rare, zero value, packs, or anything a Keep rule could match.");
}
private void RenderTabContent(int tabIndex)
{
if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length)
@ -147,10 +195,15 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Spacing();
ImGui.Text("Missile Arc Velocities (m/s)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Per-weapon projectile speed used for line-of-sight arc checks.\nLower velocity = higher arc. Tune until LoS matches in-game hits.\nDungeons always use linear checks to avoid false ceiling blocks.");
ImGui.SetTooltip("Per-weapon launch speed used for line-of-sight arc checks.\n" +
"Lower velocity = higher arc. Tune until LoS matches in-game hits\n" +
"(/ra lostest bow on a selected mob shows the arc and where it hits).\n" +
"Indoors the arc is checked against ceilings too.");
ImGui.Checkbox("Use Arcs for Missile LoS", ref _settings.UseArcs);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When off, all missile LoS checks are linear (eye-to-eye).");
ImGui.SetTooltip("On: a missile target must pass the straight line AND the arc the\n" +
"missile flies (checked against ceilings in dungeons).\n" +
"Off: all missile LoS checks are a straight line (eye-to-eye).");
if (_settings.UseArcs)
{
ImGui.Indent();
@ -162,8 +215,18 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SliderFloat("Atlatl", ref _settings.AtlatlArcVelocity, 10.0f, 60.0f, "%.1f");
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Magic Arc", ref _settings.MagicArcVelocity, 10.0f, 60.0f, "%.1f");
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Arc Clearance (m)", ref _settings.MissileArcClearance, 0.0f, 3.0f, "%.1f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Extra headroom the arc must have at mid-flight. Raise it if shots\n" +
"still hit ceilings; lower it if mobs the arrows can reach are skipped.\n" +
"Default 0.5.");
ImGui.Unindent();
}
ImGui.Checkbox("LoS Debug Log", ref _settings.LosDebugLog);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Log each in-range mob's LoS verdict ([LOS] lines: straight line or arc,\n" +
"how high the arc rises, where it hits, distance and cells). For tuning.");
ImGui.Separator();
ImGui.Spacing();
@ -490,6 +553,12 @@ internal sealed class LegacyAdvancedSettingsUi
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint).");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Shortcut Tolerance (yd)", ref _settings.NavShortcutYards, 0.5f, 1f, "%.1f");
_settings.NavShortcutYards = Math.Clamp(_settings.NavShortcutYards, 0f, 10f);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("On reaching a waypoint, skip ahead only while the straight line to a later waypoint passes within this distance of every waypoint skipped. Lower keeps closer to the route; 0 = visit every waypoint.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f");
if (ImGui.IsItemHovered())
@ -541,6 +610,15 @@ internal sealed class LegacyAdvancedSettingsUi
"values (<60s) risk a gap between the old buff dropping and the new one\n" +
"landing.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Also Refresh Under (seconds left)", ref _settings.RebuffTopOffSecondsRemaining, 30, 3600);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"When a buff is due, also recast every other buff with less than this\n" +
"much time left, so they land together. Buffs with more time are left\n" +
"alone. Default 1200 (20 minutes). At or below 'Rebuff With', only the\n" +
"expiring buff is recast.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Buff Difficulty (Min Buffed Skill)");
@ -667,6 +745,10 @@ internal sealed class LegacyAdvancedSettingsUi
}
break;
case "Vendoring":
RenderVendoring();
break;
default:
ImGui.Text($"Settings for {tabName} are currently under development.");
break;

View file

@ -280,6 +280,12 @@ internal sealed class LegacyDashboardRenderer
public void SetWorldFilter(WorldObjectCache cache) => _weaponsUi.SetWorldFilter(cache);
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedSettingsUi.SetMissileCraftingManager(mgr);
public void SetAutoVendorStatusProvider(Func<string> status) => _advancedSettingsUi.SetAutoVendorStatusProvider(status);
// The open vendor's AutoVendor profile path (null when no vendor is open), for the
// dashboard snapshot's vendorProfilePath.
private Func<string?>? _vendorProfilePath;
public void SetVendorProfilePathProvider(Func<string?> path) => _vendorProfilePath = path;
public void SetRaycast(Raycasting.MainLogic raycast)
{
@ -766,6 +772,8 @@ internal sealed class LegacyDashboardRenderer
CrossbowArcVelocity = s.CrossbowArcVelocity,
AtlatlArcVelocity = s.AtlatlArcVelocity,
MagicArcVelocity = s.MagicArcVelocity,
MissileArcClearance = s.MissileArcClearance,
LosDebugLog = s.LosDebugLog,
BlacklistAttempts = s.BlacklistAttempts,
BlacklistTimeoutSec = s.BlacklistTimeoutSec,
BlacklistCastSettleMs = s.BlacklistCastSettleMs,
@ -827,6 +835,7 @@ internal sealed class LegacyDashboardRenderer
NavDeadZone = s.NavDeadZone,
NavSweepMult = s.NavSweepMult,
NavLookaheadYards = s.NavLookaheadYards,
NavShortcutYards = s.NavShortcutYards,
NavTurnRateDegPerSec = s.NavTurnRateDegPerSec,
NavTier1TurnSpeed = s.NavTier1TurnSpeed,
PostPortalDelaySec = s.PostPortalDelaySec,
@ -840,6 +849,7 @@ internal sealed class LegacyDashboardRenderer
EnableBuffing = s.EnableBuffing,
RebuffWhenIdle = s.RebuffWhenIdle,
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
@ -878,6 +888,16 @@ internal sealed class LegacyDashboardRenderer
SalvageSalvageDelayMs = s.SalvageSalvageDelayMs,
SalvageResultDelayFirstMs = s.SalvageResultDelayFirstMs,
SalvageResultDelayFastMs = s.SalvageResultDelayFastMs,
// Vendoring (AutoVendor)
AutoVendorEnabled = s.AutoVendorEnabled,
AutoVendorEnableBuying = s.AutoVendorEnableBuying,
AutoVendorEnableSelling = s.AutoVendorEnableSelling,
AutoVendorTestMode = s.AutoVendorTestMode,
AutoVendorThink = s.AutoVendorThink,
AutoVendorShowMerchantInfo = s.AutoVendorShowMerchantInfo,
AutoVendorOnlyFromMainPack = s.AutoVendorOnlyFromMainPack,
AutoVendorTries = s.AutoVendorTries,
AutoVendorTriesTime = s.AutoVendorTriesTime,
};
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.SettingsBridgePayload);
}
@ -892,7 +912,20 @@ internal sealed class LegacyDashboardRenderer
if (string.IsNullOrWhiteSpace(json)) return;
try
{
var p = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.SettingsBridgePayload);
// Lay the sent fields over the current settings, so a field the sender leaves
// out keeps its value instead of deserializing to 0 and being applied. The
// overlay's Settings panel keeps its own copy of this payload; when that copy
// lacked BlacklistCastSettleMs/MonsterDisengageRange, every click zeroed them.
var merged = System.Text.Json.Nodes.JsonNode.Parse(BuildSettingsJson(),
new System.Text.Json.Nodes.JsonNodeOptions { PropertyNameCaseInsensitive = true })?.AsObject();
if (merged == null) return;
using (var sent = JsonDocument.Parse(json))
{
if (sent.RootElement.ValueKind != JsonValueKind.Object) return;
foreach (var prop in sent.RootElement.EnumerateObject())
merged[prop.Name] = System.Text.Json.Nodes.JsonNode.Parse(prop.Value.GetRawText());
}
var p = JsonSerializer.Deserialize(merged.ToJsonString(), RynthAiJsonContext.Default.SettingsBridgePayload);
if (p == null) return;
var s = _settings;
// Display
@ -918,9 +951,13 @@ internal sealed class LegacyDashboardRenderer
s.CrossbowArcVelocity = p.CrossbowArcVelocity;
s.AtlatlArcVelocity = p.AtlatlArcVelocity;
s.MagicArcVelocity = p.MagicArcVelocity;
if (p.MissileArcClearance >= 0f) s.MissileArcClearance = Math.Min(p.MissileArcClearance, 3f);
s.LosDebugLog = p.LosDebugLog;
s.BlacklistAttempts = p.BlacklistAttempts;
s.BlacklistTimeoutSec = p.BlacklistTimeoutSec;
s.BlacklistCastSettleMs = p.BlacklistCastSettleMs;
// -1 = not sent. 0 is never meant (it judges a cast before its damage can land)
// and is what the bug saved into profiles, so it keeps the default too.
if (p.BlacklistCastSettleMs > 0) s.BlacklistCastSettleMs = p.BlacklistCastSettleMs;
s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec;
s.GiveQueueIntervalMs = p.GiveQueueIntervalMs;
// Recharge
@ -957,7 +994,7 @@ internal sealed class LegacyDashboardRenderer
s.MinSkillLevelTier8 = p.MinSkillLevelTier8;
// Ranges
s.MonsterRange = p.MonsterRange;
s.MonsterDisengageRange = p.MonsterDisengageRange;
if (p.MonsterDisengageRange >= 0) s.MonsterDisengageRange = p.MonsterDisengageRange; // -1 = not sent
s.RingRange = p.RingRange;
s.ApproachRange = p.ApproachRange;
s.CorpseApproachRangeMax = p.CorpseApproachRangeMax;
@ -979,6 +1016,7 @@ internal sealed class LegacyDashboardRenderer
s.NavDeadZone = p.NavDeadZone;
s.NavSweepMult = p.NavSweepMult;
s.NavLookaheadYards = p.NavLookaheadYards;
s.NavShortcutYards = p.NavShortcutYards;
s.NavTurnRateDegPerSec = p.NavTurnRateDegPerSec;
s.NavTier1TurnSpeed = p.NavTier1TurnSpeed;
s.PostPortalDelaySec = p.PostPortalDelaySec;
@ -992,6 +1030,7 @@ internal sealed class LegacyDashboardRenderer
s.EnableBuffing = p.EnableBuffing;
s.RebuffWhenIdle = p.RebuffWhenIdle;
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
@ -1027,6 +1066,16 @@ internal sealed class LegacyDashboardRenderer
s.SalvageSalvageDelayMs = p.SalvageSalvageDelayMs;
s.SalvageResultDelayFirstMs = p.SalvageResultDelayFirstMs;
s.SalvageResultDelayFastMs = p.SalvageResultDelayFastMs;
// Vendoring: only fields the sender actually included (older panels omit them)
if (p.AutoVendorEnabled is bool avOn) s.AutoVendorEnabled = avOn;
if (p.AutoVendorEnableBuying is bool avBuy) s.AutoVendorEnableBuying = avBuy;
if (p.AutoVendorEnableSelling is bool avSell) s.AutoVendorEnableSelling = avSell;
if (p.AutoVendorTestMode is bool avTest) s.AutoVendorTestMode = avTest;
if (p.AutoVendorThink is bool avThink) s.AutoVendorThink = avThink;
if (p.AutoVendorShowMerchantInfo is bool avInfo) s.AutoVendorShowMerchantInfo = avInfo;
if (p.AutoVendorOnlyFromMainPack is bool avMain) s.AutoVendorOnlyFromMainPack = avMain;
if (p.AutoVendorTries is int avTries) s.AutoVendorTries = Math.Clamp(avTries, 1, 20);
if (p.AutoVendorTriesTime is int avTime) s.AutoVendorTriesTime = Math.Clamp(avTime, 500, 30000);
SaveSettings();
}
catch { }
@ -1302,6 +1351,7 @@ internal sealed class LegacyDashboardRenderer
dst.NavDeadZone = tmp.NavDeadZone;
dst.NavSweepMult = tmp.NavSweepMult;
dst.NavLookaheadYards = tmp.NavLookaheadYards;
dst.NavShortcutYards = tmp.NavShortcutYards;
dst.NavTurnRateDegPerSec = tmp.NavTurnRateDegPerSec;
dst.NavTier1TurnSpeed = tmp.NavTier1TurnSpeed;
dst.PostPortalDelaySec = tmp.PostPortalDelaySec;
@ -1384,9 +1434,12 @@ internal sealed class LegacyDashboardRenderer
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
dst.BlacklistAttempts = tmp.BlacklistAttempts;
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
dst.BlacklistCastSettleMs = tmp.BlacklistCastSettleMs;
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
// saved into profiles: it judges each cast before its damage can land.
dst.BlacklistCastSettleMs = tmp.BlacklistCastSettleMs > 0 ? tmp.BlacklistCastSettleMs : 1500;
dst.TargetNoProgressTimeoutSec = tmp.TargetNoProgressTimeoutSec;
dst.MeleeAttackPower = tmp.MeleeAttackPower;
dst.MissileAttackPower = tmp.MissileAttackPower;
@ -1399,6 +1452,8 @@ internal sealed class LegacyDashboardRenderer
dst.CrossbowArcVelocity = tmp.CrossbowArcVelocity;
dst.AtlatlArcVelocity = tmp.AtlatlArcVelocity;
dst.MagicArcVelocity = tmp.MagicArcVelocity;
dst.MissileArcClearance = tmp.MissileArcClearance >= 0f ? Math.Min(tmp.MissileArcClearance, 3f) : 0.5f;
dst.LosDebugLog = tmp.LosDebugLog;
dst.EnableFPSLimit = tmp.EnableFPSLimit;
dst.TargetFPSFocused = tmp.TargetFPSFocused;
dst.TargetFPSBackground = tmp.TargetFPSBackground;
@ -1453,6 +1508,15 @@ internal sealed class LegacyDashboardRenderer
dst.EnableManaTapping = tmp.EnableManaTapping;
dst.ManaTapMinMana = tmp.ManaTapMinMana;
dst.ManaStoneKeepCount = tmp.ManaStoneKeepCount;
dst.AutoVendorEnabled = tmp.AutoVendorEnabled;
dst.AutoVendorEnableBuying = tmp.AutoVendorEnableBuying;
dst.AutoVendorEnableSelling = tmp.AutoVendorEnableSelling;
dst.AutoVendorTestMode = tmp.AutoVendorTestMode;
dst.AutoVendorThink = tmp.AutoVendorThink;
dst.AutoVendorShowMerchantInfo = tmp.AutoVendorShowMerchantInfo;
dst.AutoVendorOnlyFromMainPack = tmp.AutoVendorOnlyFromMainPack;
dst.AutoVendorTries = tmp.AutoVendorTries;
dst.AutoVendorTriesTime = tmp.AutoVendorTriesTime;
dst.MetaDebug = tmp.MetaDebug;
dst.StartMacroOnLogin = tmp.StartMacroOnLogin;
dst.PatrolOnLogin = tmp.PatrolOnLogin;
@ -2542,6 +2606,9 @@ internal sealed class LegacyDashboardRenderer
string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath)); sb.Append(',');
AppendString(sb, "currentLootName",
string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath)); sb.Append(',');
// Full paths for the dashboard's Edit (✎) button, which opens the Loot Editor.
AppendString(sb, "currentLootPath", _settings.CurrentLootPath ?? string.Empty); sb.Append(',');
AppendString(sb, "vendorProfilePath", _vendorProfilePath?.Invoke() ?? string.Empty); sb.Append(',');
AppendString(sb, "currentMetaName",
string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath)); sb.Append(',');
AppendInt(sb, "selectedNavIdx", _selectedNavIdx); sb.Append(',');

View file

@ -40,6 +40,7 @@ public sealed class LegacyUiSettings
public float NavDeadZone = 4f;
public float NavSweepMult = 2.5f;
public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off)
public float NavShortcutYards = 1.0f; // on arrival, skip waypoints only while the straight run to a later one stays within this of every skipped point (0 = visit every point)
public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate
public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate)
public float PostPortalDelaySec = 4.0f;
@ -149,6 +150,13 @@ public sealed class LegacyUiSettings
/// landing.
/// </summary>
public int RebuffSecondsRemaining = 300;
/// <summary>
/// When a buff falls under RebuffSecondsRemaining, also refresh every other buff
/// with less than this many seconds left, so they land together instead of each
/// interrupting the fight on its own. Buffs with more time are left alone. At or
/// below RebuffSecondsRemaining only the expiring buff is recast.
/// </summary>
public int RebuffTopOffSecondsRemaining = 1200;
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
@ -225,6 +233,20 @@ public sealed class LegacyUiSettings
public float CrossbowArcVelocity = 40.0f;
public float AtlatlArcVelocity = 22.0f;
public float MagicArcVelocity = 25.0f;
/// <summary>
/// Extra headroom (meters) a missile's arc must have at mid-flight for LoS to pass,
/// on top of the modelled flight path (launch speed above, AC gravity 9.8). Covers
/// what the model can't know exactly: launch height, the real launch speed, the
/// projectile's size. Raise it if shots still hit ceilings, lower it if targets
/// under a ceiling the arrows clear are skipped. Only used with UseArcs.
/// </summary>
public float MissileArcClearance = 0.5f;
/// <summary>
/// Log each in-range target's LoS verdict (straight line / arc, how high the arc
/// rises, where it hits) and the missile weapon's known launch speed. For tuning
/// the arc settings; off by default (a few lines a second in a crowd).
/// </summary>
public bool LosDebugLog;
public bool EnableFPSLimit = true;
public int TargetFPSFocused = 60;
@ -256,6 +278,23 @@ public sealed class LegacyUiSettings
public int ManaTapMinMana = 2500;
public int ManaStoneKeepCount = 5;
// ── AutoVendor (UtilityBelt AutoVendor; /ub autovendor, /ub vendor) ────────
/// <summary>Run AutoVendor when a vendor opens (and allow /ub autovendor). UB defaults this on;
/// RynthAi defaults it off because the plugin auto-updates and selling can't be undone.</summary>
public bool AutoVendorEnabled = false;
public bool AutoVendorEnableBuying = true;
public bool AutoVendorEnableSelling = true;
/// <summary>Only print what would be bought and sold. On by default in RynthAi (UB: off).</summary>
public bool AutoVendorTestMode = true;
/// <summary>Send "AutoVendor finished: ..." (and fatal/failed lines) as a /tell to yourself, for metas.</summary>
public bool AutoVendorThink = false;
public bool AutoVendorShowMerchantInfo = true;
public bool AutoVendorOnlyFromMainPack = false;
/// <summary>Attempts to open a vendor on /ub vendor open[p].</summary>
public int AutoVendorTries = 4;
/// <summary>Milliseconds between /ub vendor open attempts.</summary>
public int AutoVendorTriesTime = 5000;
public List<MonsterRule> MonsterRules { get; set; } = new();
public List<ItemRule> ItemRules { get; set; } = new();
public List<ConsumableRule> ConsumableRules { get; set; } = new();
@ -372,7 +411,7 @@ public sealed class LegacyUiSettings
public readonly string[] AdvancedTabs =
{
"Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat",
"Ranges", "Navigation", "Buffing", "Crafting", "Looting"
"Ranges", "Navigation", "Buffing", "Crafting", "Looting", "Vendoring"
};
[JsonIgnore]
@ -571,9 +610,13 @@ public sealed class SettingsBridgePayload
public float CrossbowArcVelocity { get; set; }
public float AtlatlArcVelocity { get; set; }
public float MagicArcVelocity { get; set; }
public float MissileArcClearance { get; set; } = 0.5f; // absent in older payloads
public bool LosDebugLog { get; set; }
public int BlacklistAttempts { get; set; }
public int BlacklistTimeoutSec { get; set; }
public int BlacklistCastSettleMs { get; set; }
// -1 = absent from the payload: the overlay's Settings panel didn't send it, and
// applying the missing 0 made every panel click zero the setting (2026-09-27).
public int BlacklistCastSettleMs { get; set; } = -1;
public int TargetNoProgressTimeoutSec { get; set; }
public int GiveQueueIntervalMs { get; set; }
@ -614,7 +657,7 @@ public sealed class SettingsBridgePayload
// Ranges
public int MonsterRange { get; set; }
public int MonsterDisengageRange { get; set; }
public int MonsterDisengageRange { get; set; } = -1; // -1 = absent, see BlacklistCastSettleMs
public int RingRange { get; set; }
public int ApproachRange { get; set; }
public double CorpseApproachRangeMax { get; set; }
@ -637,6 +680,7 @@ public sealed class SettingsBridgePayload
public float NavDeadZone { get; set; }
public float NavSweepMult { get; set; }
public float NavLookaheadYards { get; set; }
public float NavShortcutYards { get; set; }
public float NavTurnRateDegPerSec { get; set; }
public float NavTier1TurnSpeed { get; set; }
public float PostPortalDelaySec { get; set; }
@ -651,6 +695,7 @@ public sealed class SettingsBridgePayload
public bool EnableBuffing { get; set; }
public bool RebuffWhenIdle { get; set; }
public int RebuffSecondsRemaining { get; set; }
public int RebuffTopOffSecondsRemaining { get; set; } = 1200; // absent in older files
public int BuffMinSkillLevelTier1 { get; set; }
public int BuffMinSkillLevelTier2 { get; set; }
public int BuffMinSkillLevelTier3 { get; set; }
@ -691,6 +736,17 @@ public sealed class SettingsBridgePayload
public int SalvageSalvageDelayMs { get; set; }
public int SalvageResultDelayFirstMs { get; set; }
public int SalvageResultDelayFastMs { get; set; }
// AutoVendor. Nullable so a settings panel that doesn't know these fields yet
// leaves the character's values alone instead of resetting them.
public bool? AutoVendorEnabled { get; set; }
public bool? AutoVendorEnableBuying { get; set; }
public bool? AutoVendorEnableSelling { get; set; }
public bool? AutoVendorTestMode { get; set; }
public bool? AutoVendorThink { get; set; }
public bool? AutoVendorShowMerchantInfo { get; set; }
public bool? AutoVendorOnlyFromMainPack { get; set; }
public int? AutoVendorTries { get; set; }
public int? AutoVendorTriesTime { get; set; }
}
public enum MetaConditionType

View file

@ -158,6 +158,14 @@ public static class VTankLootEvaluator
}
}
/// <summary>
/// One condition on its own, same semantics as inside <see cref="Match(VTankLootRule, WorldObject?, VTankLootContext?)"/>.
/// AutoVendor judges conditions one at a time so it can tell "no" from "can't tell".
/// Throws on a malformed data line or an unsupported node type (the caller decides what that means).
/// </summary>
public static bool MatchCondition(VTankLootCondition cond, WorldObject item, VTankLootContext? ctx)
=> Match(cond, item, unchecked((uint)item.Id), ctx);
private static bool Match(VTankLootCondition cond, WorldObject item, uint itemId, VTankLootContext? ctx)
{
var d = cond.DataLines;

View file

@ -209,6 +209,16 @@ public sealed partial class RynthAiPlugin
["manastonelootcount"] = "ManaStoneKeepCount",
["rebuftimeremainingseconds"] = "RebuffSecondsRemaining",
["navclosestoprange"] = "NavCloseStopRange",
// UtilityBelt AutoVendor options (/ub opt set AutoVendor.TestMode true)
["autovendor.enabled"] = "AutoVendorEnabled",
["autovendor.enablebuying"] = "AutoVendorEnableBuying",
["autovendor.enableselling"] = "AutoVendorEnableSelling",
["autovendor.testmode"] = "AutoVendorTestMode",
["autovendor.think"] = "AutoVendorThink",
["autovendor.showmerchantinfo"] = "AutoVendorShowMerchantInfo",
["autovendor.onlyfrommainpack"] = "AutoVendorOnlyFromMainPack",
["autovendor.tries"] = "AutoVendorTries",
["autovendor.triestime"] = "AutoVendorTriesTime",
};
private string? GetOptionValue(string optName)

View file

@ -3204,6 +3204,13 @@ internal sealed class ExpressionEngine
["EnableLooting"] = (() => B(s.EnableLooting), v => s.EnableLooting = ToDouble(v) != 0),
["EnableMeta"] = (() => B(s.EnableMeta), v => s.EnableMeta = ToDouble(v) != 0),
["EnableRaycasting"] = (() => B(s.EnableRaycasting), v => s.EnableRaycasting = ToDouble(v) != 0),
["UseArcs"] = (() => B(s.UseArcs), v => s.UseArcs = ToDouble(v) != 0),
["LosDebugLog"] = (() => B(s.LosDebugLog), v => s.LosDebugLog = ToDouble(v) != 0),
["BowArcVelocity"] = (() => F(s.BowArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.BowArcVelocity = Math.Clamp(f, 10f, 60f); }),
["CrossbowArcVelocity"] = (() => F(s.CrossbowArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.CrossbowArcVelocity = Math.Clamp(f, 10f, 80f); }),
["AtlatlArcVelocity"] = (() => F(s.AtlatlArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.AtlatlArcVelocity = Math.Clamp(f, 10f, 60f); }),
["MagicArcVelocity"] = (() => F(s.MagicArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.MagicArcVelocity = Math.Clamp(f, 10f, 60f); }),
["MissileArcClearance"] = (() => F(s.MissileArcClearance), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.MissileArcClearance = Math.Clamp(f, 0f, 3f); }),
["EnableAutostack"] = (() => B(s.EnableAutostack), v => s.EnableAutostack = ToDouble(v) != 0),
["EnableAutocram"] = (() => B(s.EnableAutocram), v => s.EnableAutocram = ToDouble(v) != 0),
["EnableCombineSalvage"]= (() => B(s.EnableCombineSalvage),v => s.EnableCombineSalvage= ToDouble(v) != 0),
@ -3236,7 +3243,19 @@ internal sealed class ExpressionEngine
["CorpseApproachRangeMin"] = (() => D(s.CorpseApproachRangeMin), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMin = d; }),
["ManaStoneKeepCount"] = (() => I(s.ManaStoneKeepCount), v => { if (int.TryParse(v, out int i)) s.ManaStoneKeepCount = i; }),
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0),
["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0),
["AutoVendorEnableSelling"] = (() => B(s.AutoVendorEnableSelling), v => s.AutoVendorEnableSelling = ToDouble(v) != 0),
["AutoVendorTestMode"] = (() => B(s.AutoVendorTestMode), v => s.AutoVendorTestMode = ToDouble(v) != 0),
["AutoVendorThink"] = (() => B(s.AutoVendorThink), v => s.AutoVendorThink = ToDouble(v) != 0),
["AutoVendorShowMerchantInfo"] = (() => B(s.AutoVendorShowMerchantInfo), v => s.AutoVendorShowMerchantInfo = ToDouble(v) != 0),
["AutoVendorOnlyFromMainPack"] = (() => B(s.AutoVendorOnlyFromMainPack), v => s.AutoVendorOnlyFromMainPack = ToDouble(v) != 0),
["AutoVendorTries"] = (() => I(s.AutoVendorTries), v => { if (int.TryParse(v, out int i)) s.AutoVendorTries = Math.Clamp(i, 1, 20); }),
["AutoVendorTriesTime"] = (() => I(s.AutoVendorTriesTime), v => { if (int.TryParse(v, out int i)) s.AutoVendorTriesTime = Math.Clamp(i, 500, 30000); }),
["NavCloseStopRange"] = (() => F(s.NavCloseStopRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavCloseStopRange = f; }),
["NavShortcutYards"] = (() => F(s.NavShortcutYards), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavShortcutYards = Math.Clamp(f, 0f, 10f); }),
["MaxMonRange"] = (() => D(s.MaxMonRange), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.MaxMonRange = d; }),
["NavRingThickness"] = (() => F(s.NavRingThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavRingThickness = f; }),
["NavLineThickness"] = (() => F(s.NavLineThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavLineThickness = f; }),

View file

@ -121,6 +121,11 @@ internal sealed class NavigationEngine
// waypoint). Tunable in Advanced ▸ Navigation ▸ Steering.
private double LookaheadYards => Math.Max(0.0, _settings.NavLookaheadYards);
// Straight-line shortcut on arrival: skip waypoints only while the straight run
// to a later one stays within this many yards of every waypoint skipped.
// 0 = off (visit every waypoint). Tunable in Advanced ▸ Navigation ▸ Steering.
private double ShortcutYards => Math.Max(0.0, _settings.NavShortcutYards);
// Mode 0 heading servo: cap the heading change we command per tick so the
// turn is smooth and never overshoots (deadbeat). Floored at 10°/s so a
// stray 0 from an old config can't freeze turning.
@ -423,7 +428,16 @@ internal sealed class NavigationEngine
{
_inPause = false;
_inRecovery = false;
_linearDir = 1;
// _linearDir is NOT reset here. Stop() runs on every pause (combat, loot,
// buff, door), and resetting it turned a Linear route around after each
// fight on the way back: the bot re-walked the far leg to the end instead of
// finishing the return. A new route resets it (route swap / ResetRouteState).
//
// Combat, looting, buffing and doors stop nav and move the character. The
// closest-approach reading from before the pause says nothing about where we
// are now; kept, the first tick back reads the displacement as a sweep-pass
// and advances past a waypoint that was never reached.
_prevDist = double.MaxValue;
_stopRequestedAt = long.MaxValue;
ResetPortalState();
_host.SetAutoRun(false);
@ -436,6 +450,7 @@ internal sealed class NavigationEngine
public void ResetRouteState()
{
Stop();
_linearDir = 1;
_stuckCount = 0;
_recoveryKind = RecoveryKind.Jump;
_prevDist = double.MaxValue;
@ -871,36 +886,59 @@ internal sealed class NavigationEngine
if (skipped > 0)
_host.Log($"Nav: skipped {skipped} dense waypoint(s) within {arrival:F1}yd → now on [{_settings.ActiveNavIndex}]");
// Collinear-waypoint skip: if current target lies nearly on the straight
// line from the player to the waypoint after it, skip it. Handles straight
// dungeon corridors and outdoor paths with too many recorded points.
const double CollinearThreshYards = 2.0;
const int ColSkipBudget = 64;
int colSkipped = 0;
while (colSkipped < ColSkipBudget && IndexValid(_settings.ActiveNavIndex, route))
// Straight-line shortcut: bypass waypoints that the straight run from here
// to a later waypoint already passes close to (straight corridors, recorded
// routes with many points on a line). EVERY bypassed waypoint must lie
// within ShortcutYards of the segment player→new target.
//
// This used to test each waypoint only against the line to its immediate
// successor. A point is never farther than one spacing from the line to the
// next point, so on a player-made route with 1-3yd spacing the test passed
// step after step around curves and corners: one arrival jumped up to 64
// waypoints and aimed a straight line 15-50yd off the route, into walls,
// where the stuck ladder then skipped more (2026-09-27). Replaying every
// arrival of 518 real VTank routes: 5% cut a corner by >3yd, worst 49.6yd.
// The cumulative test caps the deviation at ShortcutYards by construction.
double tolerance = ShortcutYards;
if (tolerance > 0.0)
{
var curr = route.Points[_settings.ActiveNavIndex];
if (curr.Type != NavPointType.Point) break;
const int ShortcutBudget = 64;
Span<int> bypassed = stackalloc int[ShortcutBudget];
int count = 0;
double worst = 0.0;
while (count < ShortcutBudget && IndexValid(_settings.ActiveNavIndex, route))
{
int ci = _settings.ActiveNavIndex;
var curr = route.Points[ci];
if (curr.Type != NavPointType.Point) break;
int ni = PeekNext(_settings.ActiveNavIndex, route);
if (ni < 0 || ni == _settings.ActiveNavIndex) break;
var next = route.Points[ni];
if (next.Type != NavPointType.Point) break;
int ni = PeekNext(ci, route);
if (ni < 0 || ni == ci) break;
var next = route.Points[ni];
if (next.Type != NavPointType.Point) break;
// Only skip if next is farther from player than curr (don't skip past a turn)
double dCurrNS = curr.NS - curNs, dCurrEW = curr.EW - curEw;
double dNextNS = next.NS - curNs, dNextEW = next.EW - curEw;
if (dNextNS * dNextNS + dNextEW * dNextEW <= dCurrNS * dCurrNS + dCurrEW * dCurrEW) break;
// Only shortcut forward: the new target must be farther from the
// player than the one it replaces (don't skip past a turn back).
double dCurrNS = curr.NS - curNs, dCurrEW = curr.EW - curEw;
double dNextNS = next.NS - curNs, dNextEW = next.EW - curEw;
if (dNextNS * dNextNS + dNextEW * dNextEW <= dCurrNS * dCurrNS + dCurrEW * dCurrEW) break;
if (CrossDistYards(curNs, curEw, curr.NS, curr.EW, next.NS, next.EW) >= CollinearThreshYards) break;
double off = SegmentDistYards(curr.NS, curr.EW, curNs, curEw, next.NS, next.EW);
for (int b = 0; b < count && off < tolerance; b++)
{
var bp = route.Points[bypassed[b]];
off = Math.Max(off, SegmentDistYards(bp.NS, bp.EW, curNs, curEw, next.NS, next.EW));
}
if (off >= tolerance) break;
int beforeCol = _settings.ActiveNavIndex;
AdvanceOneIndex(route);
if (_settings.ActiveNavIndex == beforeCol) break;
colSkipped++;
AdvanceOneIndex(route);
if (_settings.ActiveNavIndex == ci) break;
bypassed[count++] = ci;
if (off > worst) worst = off;
}
if (count > 0)
_host.Log($"Nav: shortcut past {count} waypoint(s), ≤{worst:F1}yd off route → now on [{_settings.ActiveNavIndex}]");
}
if (colSkipped > 0)
_host.Log($"Nav: skipped {colSkipped} collinear waypoint(s) → now on [{_settings.ActiveNavIndex}]");
}
if (_settings.ActiveNavIndex != oldIdx && IndexValid(_settings.ActiveNavIndex, route))
@ -1734,13 +1772,14 @@ internal sealed class NavigationEngine
private static double Lerp(double a, double b, double t) => a + (b - a) * t;
// Perpendicular distance (yards) from point B to the infinite line through A and C.
private static double CrossDistYards(double aNS, double aEW, double bNS, double bEW, double cNS, double cEW)
// Distance (yards) from point P to the segment A→B.
private static double SegmentDistYards(double pNS, double pEW, double aNS, double aEW, double bNS, double bEW)
{
double acNS = cNS - aNS, acEW = cEW - aEW;
double acLen = Math.Sqrt(acNS * acNS + acEW * acEW);
if (acLen < 1e-9) return 0.0;
double abNS = bNS - aNS, abEW = bEW - aEW;
return Math.Abs(abNS * acEW - abEW * acNS) / acLen * 240.0;
double len2 = abNS * abNS + abEW * abEW;
double t = len2 < 1e-18 ? 0.0
: Math.Clamp(((pNS - aNS) * abNS + (pEW - aEW) * abEW) / len2, 0.0, 1.0);
double dNS = pNS - (aNS + t * abNS), dEW = pEW - (aEW + t * abEW);
return Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0;
}
}

View file

@ -0,0 +1,182 @@
using System;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// The flight path of an AC missile (arrow, bolt, dart), as pure math: no host, no
/// geometry, no allocation. Kept dependency-free so Tools/RynthCore.MissileArcTests
/// compiles it directly.
///
/// The server launches every missile at the weapon's fixed speed on the LOW solution of
/// the ballistic arc to the aim point, under gravity (ACE GetProjectileVelocity →
/// Trajectory.solve_ballistic_arc, first solution; PhysicsGlobals.Gravity = 9.8). So the
/// arc height is not a constant: it grows with distance and shrinks with launch speed.
/// At 5 m a bow shot is a straight line; at 40 m with 25 m/s it rises about 3.5 m above
/// the launch point, which is enough to hit a dungeon ceiling the straight line clears.
///
/// Units are meters, Z up. "t" is the horizontal fraction of the shot, 0 at the launch
/// point and 1 at the aim point.
/// </summary>
public readonly struct MissileArc
{
/// <summary>Launch point.</summary>
public readonly float OX, OY, OZ;
/// <summary>Unit horizontal direction from launch point to aim point.</summary>
public readonly float DirX, DirY;
/// <summary>Horizontal distance from launch point to aim point.</summary>
public readonly float HorizDist;
/// <summary>Aim point Z minus launch point Z.</summary>
public readonly float Rise;
/// <summary>Tangent of the launch elevation (low solution).</summary>
public readonly float TanTheta;
/// <summary>Curvature: height(x) = x·TanTheta − K·x², K = g(1+tan²θ)/(2v²).</summary>
public readonly float K;
/// <summary>False when the aim point is out of reach at this launch speed.</summary>
public readonly bool Valid;
/// <summary>True for a (near) vertical shot, flown as a straight line.</summary>
public readonly bool Vertical;
internal MissileArc(float ox, float oy, float oz, float dirX, float dirY, float horizDist,
float rise, float tanTheta, float k, bool valid, bool vertical)
{
OX = ox; OY = oy; OZ = oz;
DirX = dirX; DirY = dirY;
HorizDist = horizDist; Rise = rise;
TanTheta = tanTheta; K = k;
Valid = valid; Vertical = vertical;
}
/// <summary>Height above the launch point at horizontal fraction t (no clearance).</summary>
public float HeightAt(float t)
{
if (!Valid) return 0f;
if (Vertical) return Rise * t;
float x = t * HorizDist;
return x * TanTheta - K * x * x;
}
/// <summary>
/// The point at horizontal fraction t, raised by <paramref name="clearance"/> at
/// mid-flight (see <see cref="MissileBallistics.ClearanceBump"/>). The ends never
/// move: t=0 is the launch point and t=1 the aim point.
/// </summary>
public void PointAt(float t, float clearance, out float x, out float y, out float z)
{
float h = t * HorizDist;
x = OX + DirX * h;
y = OY + DirY * h;
z = OZ + HeightAt(t) + MissileBallistics.ClearanceBump(t, clearance);
}
/// <summary>
/// How far the arc rises above the straight line from launch point to aim point, at
/// its highest. This is the part a straight line-of-sight check never sees.
/// </summary>
public float MaxRiseAboveChord
{
get
{
if (!Valid || Vertical || HorizDist <= 0f || K <= 0f) return 0f;
// height(x) − Rise·x/d = x·(tanθ − Rise/d) − K·x². Its maximum is at
// x* = a/(2K), value a²/(4K), where a = tanθ − Rise/d.
float a = TanTheta - Rise / HorizDist;
if (a <= 0f) return 0f;
float xStar = a / (2f * K);
if (xStar >= HorizDist) xStar = HorizDist;
return a * xStar - K * xStar * xStar;
}
}
/// <summary>Highest point of the flight above the launch point (never below the ends).</summary>
public float ApexAboveLaunch
{
get
{
if (!Valid) return 0f;
if (Vertical) return Math.Max(0f, Rise);
if (K <= 0f) return Math.Max(0f, Rise);
float xApex = TanTheta / (2f * K);
float apex = xApex > 0f && xApex < HorizDist
? TanTheta * xApex - K * xApex * xApex
: 0f;
return Math.Max(apex, Math.Max(0f, Rise));
}
}
}
public static class MissileBallistics
{
/// <summary>AC's gravity (PhysicsGlobals.Gravity = -9.8).</summary>
public const float AcGravity = 9.8f;
/// <summary>Below this horizontal distance a shot is treated as vertical.</summary>
private const float VerticalEpsilon = 0.05f;
/// <summary>
/// Solves the low ballistic arc from the launch point to the aim point at a fixed launch
/// speed. Out of reach (the speed can't carry that far or that high) gives Valid=false.
/// </summary>
public static MissileArc Solve(float ox, float oy, float oz,
float tx, float ty, float tz,
float speed, float gravity = AcGravity)
{
float dx = tx - ox, dy = ty - oy;
float rise = tz - oz;
float d = (float)Math.Sqrt(dx * dx + dy * dy);
if (float.IsNaN(d) || float.IsNaN(rise) || speed <= 0f || gravity <= 0f)
return new MissileArc(ox, oy, oz, 0f, 0f, 0f, 0f, 0f, 0f, valid: false, vertical: false);
if (d < VerticalEpsilon)
return new MissileArc(ox, oy, oz, 0f, 0f, d, rise, 0f, 0f, valid: true, vertical: true);
// Low-angle solution of rise = d·tanθ − g·d²·(1+tan²θ)/(2v²):
// tanθ = (v² − √(v⁴ − g(g·d² + 2·rise·v²))) / (g·d)
double v2 = (double)speed * speed;
double disc = v2 * v2 - gravity * (gravity * (double)d * d + 2.0 * rise * v2);
if (disc < 0.0)
return new MissileArc(ox, oy, oz, dx / d, dy / d, d, rise, 0f, 0f, valid: false, vertical: false);
double tan = (v2 - Math.Sqrt(disc)) / (gravity * (double)d);
double k = gravity * (1.0 + tan * tan) / (2.0 * v2);
return new MissileArc(ox, oy, oz, dx / d, dy / d, d, rise, (float)tan, (float)k, valid: true, vertical: false);
}
/// <summary>
/// Extra height added to the tested path: <paramref name="clearance"/> at mid-flight,
/// tapering to zero at both ends (4t(1−t)), so the launch and aim points stay put. It
/// covers what the model can't know exactly: launch height, the real launch speed, the
/// projectile's own size.
/// </summary>
public static float ClearanceBump(float t, float clearance)
{
if (clearance <= 0f || t <= 0f || t >= 1f) return 0f;
return clearance * 4f * t * (1f - t);
}
/// <summary>Number of straight segments used to test an arc: about one per 2.5 m, 6 to 24.</summary>
public static int SegmentCount(float horizDist)
{
if (float.IsNaN(horizDist) || horizDist <= 0f) return 6;
int n = (int)Math.Ceiling(horizDist / 2.5f);
return Math.Clamp(n, 6, 24);
}
/// <summary>
/// Highest Z the tested path reaches (arc plus clearance), sampled like the geometry
/// test samples it. Lets a caller compare the path against a known ceiling height.
/// </summary>
public static float MaxPathZ(in MissileArc arc, float clearance)
{
if (!arc.Valid) return float.NaN;
int n = SegmentCount(arc.HorizDist) * 4;
float best = Math.Max(arc.OZ, arc.OZ + arc.Rise);
for (int i = 1; i < n; i++)
{
arc.PointAt((float)i / n, clearance, out _, out _, out float z);
if (z > best) best = z;
}
return best;
}
}
}

View file

@ -224,6 +224,89 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
return false; // Arc clears all obstacles
}
/// <summary>What <see cref="IsBallisticArcBlocked"/> found, for the LOS debug log and /ra lostest.</summary>
public struct ArcLosResult
{
public bool Blocked;
public bool OutOfReach; // the launch speed can't carry the shot that far / that high
public float Sag; // how far the arc rises above the straight line, at most (m)
public float Apex; // highest point of the flight above the launch point (m)
public float HitAlong; // horizontal distance from the shooter to the hit (m)
public float HitZ; // height of the hit above the launch point (m)
}
/// <summary>
/// Tests the path a missile really flies: the low ballistic arc at the weapon's launch
/// speed (see <see cref="MissileBallistics"/>), raised by <paramref name="clearance"/>
/// at mid-flight. Unlike <see cref="IsArcPathBlocked"/> (the old flat-ground
/// approximation, kept for magic arcs), the arc passes exactly through the aim point
/// for any height difference. Floors and ceilings are part of the dungeon geometry, so
/// an arc that rises into a ceiling reports blocked. Out of reach counts as blocked.
/// Hits within 0.5 m of the shooter or 0.3 m of the target are ignored, as in the
/// straight-line test.
/// </summary>
public static bool IsBallisticArcBlocked(Vector3 origin, Vector3 target, float speed, float clearance,
List<BoundingVolume> geometry, out ArcLosResult result)
{
result = default;
if (float.IsNaN(origin.X) || float.IsNaN(origin.Y) || float.IsNaN(origin.Z) ||
float.IsNaN(target.X) || float.IsNaN(target.Y) || float.IsNaN(target.Z))
return false;
var arc = MissileBallistics.Solve(origin.X, origin.Y, origin.Z, target.X, target.Y, target.Z, speed);
result.Sag = arc.MaxRiseAboveChord;
result.Apex = arc.ApexAboveLaunch;
if (!arc.Valid)
{
result.OutOfReach = true;
result.Blocked = true;
return true;
}
if (geometry == null || geometry.Count == 0)
return false;
clearance = Math.Max(0f, clearance);
int n = MissileBallistics.SegmentCount(arc.HorizDist);
Vector3 prev = origin;
float travelled = 0f;
for (int i = 1; i <= n; i++)
{
float t = (float)i / n;
Vector3 cur;
if (i == n) cur = target;
else
{
arc.PointAt(t, clearance, out float px, out float py, out float pz);
cur = new Vector3(px, py, pz);
}
Vector3 seg = cur - prev;
float len = seg.Length();
if (len > 1e-4f)
{
Vector3 dir = seg / len;
foreach (var volume in geometry)
{
if (volume.IsDoor) continue;
if (!volume.RayIntersect(prev, dir, len, out float hd)) continue;
if (hd < 0f || hd > len) continue;
if (travelled + hd < 0.5f) continue; // at the shooter
if (i == n && hd > len - 0.3f) continue; // at the target
Vector3 hit = prev + dir * hd;
float hx = hit.X - origin.X, hy = hit.Y - origin.Y;
result.Blocked = true;
result.HitAlong = (float)Math.Sqrt(hx * hx + hy * hy);
result.HitZ = hit.Z - origin.Z;
return true;
}
}
travelled += len;
prev = cur;
}
return false;
}
/// <summary>
/// Tests if a line segment between two points intersects any geometry.
/// Used internally for arc sampling.

View file

@ -45,6 +45,41 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
// If true, use arc checks for missile weapons. If false, treat all as linear.
public bool UseArcs { get; set; } = true;
// Extra headroom (m) the missile arc must have at mid-flight, on top of the modelled
// flight path. Covers launch height, the real launch speed and the projectile's size.
// CombatManager overrides it from LegacyUiSettings.MissileArcClearance each tick.
public float MissileArcClearance { get; set; } = 0.5f;
// An arc that rises less than this above the straight line is flown as that line:
// the straight-line test (multi-ray in dungeons, ±0.3 m) already covers it, and the
// clearance bump is not applied to short, flat shots.
private const float ArcSagIgnoreMeters = 0.15f;
/// <summary>How a LOS verdict was reached, for the LOS debug log.</summary>
public struct LosDetail
{
public AttackType Type;
public bool Dungeon;
public bool Checked; // false = no verdict computed (no geometry near, too far, no position)
public float Velocity; // launch speed used for a missile arc (0 = straight line)
public bool LineBlocked;
public bool ArcChecked;
public RaycastEngine.ArcLosResult Arc;
}
private static bool IsMissileArc(AttackType t) =>
t == AttackType.BowArc || t == AttackType.CrossbowArc || t == AttackType.AtlatlArc;
/// <summary>Launch speed configured for a missile attack type.</summary>
public float VelocityFor(AttackType t) => t switch
{
AttackType.BowArc => BowArcVelocity,
AttackType.CrossbowArc => CrossbowArcVelocity,
AttackType.AtlatlArc => AtlatlArcVelocity,
AttackType.MagicArc => MagicArcVelocity,
_ => 0f,
};
// Max scan distance in meters. Only check LOS for targets within this range.
// Set from CombatManager based on MonsterRange + buffer.
public float MaxScanDistanceMeters { get; set; } = 120.0f;
@ -62,7 +97,23 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
/// Returns false if the target is clear to attack.
/// </summary>
public bool IsTargetBlocked(RynthCoreHost host, uint targetId, AttackType attackType)
=> IsTargetBlocked(host, targetId, attackType, out _);
/// <summary>
/// As <see cref="IsTargetBlocked(RynthCoreHost, uint, AttackType)"/>, and reports how the
/// verdict was reached.
///
/// Missile weapons (bow, crossbow, atlatl) with UseArcs on: the target must pass the
/// straight line (walls, corner seams) AND the arc the missile really flies, low
/// ballistic solution at the weapon's launch speed plus MissileArcClearance headroom.
/// Indoors this is what catches ceilings: the old code forced a straight-line test in
/// dungeons, so a target 20-50 m down a corridor passed LOS while the arrow, rising
/// 2-6 m on its way there, hit the ceiling (2026-09-27, Longbow, Olthoi swarm).
/// </summary>
public bool IsTargetBlocked(RynthCoreHost host, uint targetId, AttackType attackType, out LosDetail detail)
{
detail = default;
detail.Type = attackType;
if (!_geoLoader.IsInitialized)
return false;
@ -90,55 +141,72 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
uint landcell = GetPlayerLandcell(host);
uint cellPart = landcell & 0xFFFF;
bool isDungeon = cellPart >= 0x0100;
detail.Dungeon = isDungeon;
// Force linear checks indoors — arc trajectories hit ceilings
if (isDungeon)
bool missileArc = UseArcs && IsMissileArc(attackType);
// Magic arcs keep the old rule: straight line indoors.
if (isDungeon && !missileArc)
attackType = AttackType.Linear;
detail.Type = attackType;
var geometry = _geoLoader.GetLandblockGeometry(landcell);
if (geometry == null || geometry.Count == 0)
return false;
// The missile's real path: solved up front so the pre-filter box covers its apex.
MissileArc arc = default;
float arcHeadroom = 0f;
if (missileArc)
{
detail.Velocity = VelocityFor(attackType);
arc = MissileBallistics.Solve(origin.X, origin.Y, origin.Z,
targetPos.X, targetPos.Y, targetPos.Z, detail.Velocity);
arcHeadroom = arc.ApexAboveLaunch + Math.Max(0f, MissileArcClearance) + 0.5f;
}
// Pre-filter: skip full ray test if no geometry near the path
float margin = Math.Min(flatDist * 0.3f, 15.0f);
margin = Math.Max(margin, 3.0f);
margin = Math.Max(margin, arcHeadroom);
if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin))
return false;
detail.Checked = true;
if (missileArc)
{
// Walls first (cheap, and most blocked targets stop here). In dungeons use
// multi-ray: 5 rays covering the player silhouette catch thin corner
// geometry that a single center ray slips through.
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
if (detail.LineBlocked)
return true;
// A short, flat shot is the straight line just tested.
if (arc.Valid && arc.MaxRiseAboveChord < ArcSagIgnoreMeters)
{
detail.Arc.Sag = arc.MaxRiseAboveChord;
detail.Arc.Apex = arc.ApexAboveLaunch;
return false;
}
detail.ArcChecked = true;
return RaycastEngine.IsBallisticArcBlocked(origin, targetPos, detail.Velocity,
MissileArcClearance, geometry, out detail.Arc);
}
// In dungeons use multi-ray checks — 5 rays covering the player silhouette
// catch thin corner geometry that a single center ray slips through.
switch (attackType)
{
case AttackType.Linear:
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
case AttackType.BowArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, BowArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
case AttackType.BowArc: // arcs off (UseArcs=false) → straight line
case AttackType.CrossbowArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, CrossbowArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
case AttackType.AtlatlArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, AtlatlArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
return detail.LineBlocked;
case AttackType.MagicArc:
if (UseArcs && !isDungeon)
@ -289,8 +357,14 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (currentCombatMode == 2)
return AttackType.Linear;
// MISSILE MODE: Check the weapon name for bow vs crossbow vs thrown
if (currentCombatMode == 4 && !string.IsNullOrEmpty(wieldedWeaponName))
// MISSILE MODE: Check the weapon name for bow vs crossbow vs thrown.
// No name (weapon not resolved yet) is still a missile shot: bow arc. The
// combat scan used to pass "" here, which fell through to Linear, so no missile
// LOS check ever used an arc or the per-weapon velocities.
if (currentCombatMode == 4 && string.IsNullOrEmpty(wieldedWeaponName))
return UseArcs ? AttackType.BowArc : AttackType.Linear;
if (currentCombatMode == 4)
{
string name = wieldedWeaponName.ToLower();

View file

@ -80,6 +80,8 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra bufftest — one-shot: snapshot enchant registries pre/post next item-spell cast (logs to RynthCore.log)");
ChatLine("[RynthAi] /ra settings savechar <name> — save current settings to named profile (create if new)");
ChatLine("[RynthAi] /ra settings loadchar <name> — load named settings profile (create from current if new)");
ChatLine("[RynthAi] /ub autovendor [profile.utl|cancel] — run AutoVendor at the open vendor (TestMode on by default)");
ChatLine("[RynthAi] /ub vendor open[p] <name|id|selected> | opencancel | addbuy[p]/addsell[p] [n] <item> | buyall | sellall | clearbuy | clearsell");
}
private void HandlePowerCommand(string[] parts)
@ -324,8 +326,20 @@ public sealed partial class RynthAiPlugin
if (geometry != null && geometry.Count > 0)
{
staticBlocked = RaycastEngine.IsArcPathBlocked(origin, targetPos, arcVelocity, geometry);
ChatLine($"[RynthAi LOS] IsArcPathBlocked: {staticBlocked}{(isDungeon && staticBlocked ? " (likely ceiling — combat LoS forces Linear in dungeons)" : "")}");
// Same test combat runs for missile targets: straight line (walls), then the
// arc the missile flies plus the clearance headroom (ceilings indoors).
float clearance = settings?.MissileArcClearance ?? 0.5f;
bool lineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
bool arcBlocked = RaycastEngine.IsBallisticArcBlocked(origin, targetPos, arcVelocity, clearance, geometry, out var arc);
staticBlocked = lineBlocked || arcBlocked;
ChatLine($"[RynthAi LOS] Straight line ({(isDungeon ? "multi-ray" : "single-ray")}): {(lineBlocked ? "BLOCKED" : "clear")}");
ChatLine($"[RynthAi LOS] Arc: rises {arc.Sag:F2}m above the line, apex {arc.Apex:F2}m above launch, clearance {clearance:F1}m");
if (arc.OutOfReach)
ChatLine($"[RynthAi LOS] Arc: OUT OF REACH at v={arcVelocity:F1} (raise the velocity or get closer)");
else if (arcBlocked)
ChatLine($"[RynthAi LOS] Arc: BLOCKED {arc.HitAlong:F1}m out, {arc.HitZ:+0.0;-0.0;0.0}m vs launch{(isDungeon && arc.HitZ > 0.5f ? " (ceiling)" : "")}");
else
ChatLine("[RynthAi LOS] Arc: clear");
}
}
else
@ -392,63 +406,30 @@ public sealed partial class RynthAiPlugin
ChatLine($"[RynthAi LOS] Combined LoS ({modeLabel}): {verdict}");
}
// Samples a parabolic arc from origin→target at the given launch velocity,
// returns true if any sample point dips below terrain Z. Mirrors the math
// in RaycastEngine.IsArcPathBlocked so the terrain check tracks the same
// trajectory the static-geometry check uses.
// Samples the missile's arc from origin→target at the given launch speed and returns
// true if any sample point dips below terrain Z. Same flight path as combat's missile
// LOS (MissileBallistics: low ballistic solution, AC gravity), without the clearance.
private static bool TerrainBlockedAlongArc(Raycasting.Vector3 origin, Raycasting.Vector3 target,
float velocity, Raycasting.GeometryLoader geo,
out float hitDist, out Raycasting.Vector3 hitPoint)
{
hitDist = 0f;
hitPoint = origin;
const float GRAVITY = 9.81f;
const int SAMPLES = 20;
const int SAMPLES = 20;
var delta = target - origin;
float horiz = delta.Length2D();
if (horiz < 0.1f) return false;
float maxRange = (velocity * velocity) / GRAVITY;
if (horiz > maxRange) return false; // out-of-range is the shooter's problem, not terrain's
float sinArg = (GRAVITY * horiz) / (velocity * velocity);
if (sinArg > 1.0f) sinArg = 1.0f;
float launchAngle = (float)(0.5 * Math.Asin(sinArg));
if (launchAngle < 0.1f) launchAngle = (float)(Math.PI / 4);
float cosA = (float)Math.Cos(launchAngle);
float sinA = (float)Math.Sin(launchAngle);
float vH = velocity * cosA;
float vV = velocity * sinA;
if (vH < 0.01f) return false;
float totalTime = horiz / vH;
float hdx = delta.X / horiz;
float hdy = delta.Y / horiz;
var arc = Raycasting.MissileBallistics.Solve(origin.X, origin.Y, origin.Z, target.X, target.Y, target.Z, velocity);
if (!arc.Valid || arc.Vertical) return false; // out of reach is the shooter's problem, not terrain's
for (int i = 1; i <= SAMPLES; i++)
{
float t = (float)i / SAMPLES;
float time = t * totalTime;
float hDistAlong = vH * time;
// Deep-audit finding #31 (2026-06-18) — mirrors the fix in
// RaycastEngine.IsArcPathBlocked: the flat-range parabolic sag
// (vV*time - 0.5g*time²) is exactly 0 at t=0 AND t=1 by
// construction (totalTime is the equal-height time-of-flight),
// so adding it to a straight lerp(origin.Z, target.Z) anchors
// both endpoints exactly instead of double-applying the
// elevation difference via a separate (1-t) blend.
float z = origin.Z + delta.Z * t + (vV * time - 0.5f * GRAVITY * time * time);
float wx = origin.X + hdx * hDistAlong;
float wy = origin.Y + hdy * hDistAlong;
arc.PointAt(t, 0f, out float wx, out float wy, out float z);
float groundZ = geo.GetTerrainZWorld(wx, wy);
if (float.IsNaN(groundZ)) continue;
if (z < groundZ)
{
hitDist = hDistAlong;
hitDist = t * arc.HorizDist;
hitPoint = new Raycasting.Vector3(wx, wy, z);
return true;
}

View file

@ -11,6 +11,7 @@ using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.Plugin.RynthAi.Vendor;
using RynthCore.PluginCore;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
@ -64,6 +65,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.5.0-legacy-ui");
/// <summary>
/// Oldest engine RynthAi runs on. Players get plugin updates automatically but engine
/// updates only when they click, so this stays at 66 while newer calls are feature-
/// detected (Host.HasVendorTrade for API v67 vendor trading: AutoVendor reports "needs a
/// RynthCore update" without it). The SDK default is CurrentApiVersion, which would make
/// every SDK bump refuse older engines. Raise it only for a call RynthAi can't run without.
/// </summary>
public override uint MinimumApiVersion => 66;
private LegacyDashboardRenderer? _dashboard;
/// <summary>Snapshot bridge accessor for engine-side panels.</summary>
@ -245,6 +255,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_missileCraftingManager = null;
_jumper?.Cancel();
_jumper = null;
_autoVendor?.Reset();
_autoVendor = null;
_playerId = 0;
_loginComplete = false;
_windowVisible = false;
@ -425,6 +437,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_jumper = new Jumper(Host, _dashboard.Settings, s => Host.WriteToChat(s, 1));
if (_objectCache != null)
{
var dashForAv = _dashboard;
_autoVendor = new AutoVendorManager(Host, _dashboard.Settings, _objectCache, _playerId,
() => dashForAv?.CharFolder ?? string.Empty);
var avForUi = _autoVendor;
_dashboard.SetAutoVendorStatusProvider(() => avForUi.Status);
_dashboard.SetVendorProfilePathProvider(() => avForUi.OpenVendorProfilePath);
}
Log("RynthAi: login complete, legacy ImGui dashboard ready.");
}
@ -436,6 +458,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// away from Navigating, and the arbiter's decision is the only thing that
// decides whether nav runs at all. One edge-detect replaces the cascade.
private BotActivity _activity = BotActivity.Idle; // last arbiter decision
private bool _macroWasRunning; // edge: release held turns when the macro stops
private BotActivity _navStoppedFor = BotActivity.Idle; // activity we last issued a nav Stop() for
private bool _navStopIssued;
// Buffing-coma watchdog (see the Priority-1 block): how long BotAction has
@ -554,7 +577,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["TargetFPSFocused"] = (10, 240), ["TargetFPSBackground"] = (5, 60),
["BlacklistAttempts"] = (1, 20), ["BlacklistTimeoutSec"] = (5, 120), ["BlacklistCastSettleMs"] = (500, 5000),
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000),
["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60),
["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3),
["HealAt"] = (0, 100), ["RestamAt"] = (0, 100), ["GetManaAt"] = (0, 100),
["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100),
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
@ -569,10 +592,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["FollowNavMin"] = (0.5, 20), ["NavRingThickness"] = (1, 16), ["NavLineThickness"] = (1, 16),
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 2),
["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10),
["NavLookaheadYards"] = (0, 30), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30),
["NavLookaheadYards"] = (0, 30), ["NavShortcutYards"] = (0, 10), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30),
["T2Speed"] = (0.1, 5), ["T2WalkWithinYd"] = (1, 50), ["T2DistanceTo"] = (0.1, 10), ["T2ReissueMs"] = (100, 10000),
["T2MaxRangeYd"] = (50, 2000), ["T2MaxLandblocks"] = (1, 20),
["RebuffSecondsRemaining"] = (30, 1800),
["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600),
["AutoVendorTries"] = (1, 20), ["AutoVendorTriesTime"] = (500, 30000),
["BuffMinSkillLevelTier1"] = (1, 500), ["BuffMinSkillLevelTier2"] = (1, 500), ["BuffMinSkillLevelTier3"] = (1, 500), ["BuffMinSkillLevelTier4"] = (1, 500),
["BuffMinSkillLevelTier5"] = (1, 500), ["BuffMinSkillLevelTier6"] = (1, 500), ["BuffMinSkillLevelTier7"] = (1, 500), ["BuffMinSkillLevelTier8"] = (1, 500),
["LootJumpHeight"] = (1, 100), ["LootOwnership"] = (0, 2),
@ -1116,6 +1140,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return;
if (diag) Host.Log($"[RynthAi] OnTick: settings ok, macro={settings.IsMacroRunning} action={settings.BotAction}");
// Macro switched off: combat stops ticking, so a turn it was holding would
// stay held and the character spun on its own (2026-09-27). Let go once.
if (_macroWasRunning && !settings.IsMacroRunning)
_combatManager?.ReleaseHeldTurn();
_macroWasRunning = settings.IsMacroRunning;
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
{
_patrolOnLoginPending = false;
@ -1232,6 +1262,25 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
catch { /* arbiter must never throw out of the live tick */ }
// ── AutoVendor (UtilityBelt-style) ───────────────────────────────
// Runs whether or not the macro is on: it starts when a vendor opens.
// While it holds the bot (a vendoring session, or /ub vendor open
// trying to reach a vendor) nothing else moves the character or the
// inventory — UB takes VTank's Navigation + ItemUse locks the same way.
// Bounded by AutoVendor's own 60 s bail timer.
var autoVendor = _autoVendor;
if (autoVendor != null)
{
autoVendor.Tick(_busyCount);
if (autoVendor.HoldsBot)
{
if (settings.IsMacroRunning)
StopNavFor(BotActivity.Idle);
_metaManager?.Think();
return;
}
}
// ── Priority 1: Buffing ───────────────────────────────────────────
// Blocks combat, looting, and navigation entirely. The coma
// watchdog that used to live here now runs ahead of the decision
@ -1543,6 +1592,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
float prevRatio = _objectCache?.GetHealthRatio(unchecked((int)targetId)) ?? -1f;
_objectCache?.OnUpdateHealth(targetId, healthRatio);
_dashboard?.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
if (_loginComplete && targetId == _playerId && maxHealth > 0)
@ -1551,9 +1601,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_vitals.MaxHealth = maxHealth;
}
// When a creature's health changes, something hit it — reset its miss counter
// so the blacklist doesn't trigger on valid in-combat targets.
if (targetId != _playerId)
// When a creature's health DROPS, something hit it — reset its miss counter so the
// blacklist doesn't trigger on valid in-combat targets. Only a drop counts: the
// client also gets health for a mob the player merely selects (QueryHealth reply),
// for the fight target combat queries at lock, and on regen, all at unchanged or
// higher health. Counting those as hits reset the no-damage miss streak,
// un-blacklisted the mob and gave it the damage-commitment bonus, so selecting a
// mob could steer combat and a target the arrows weren't hurting could be held far
// past BlacklistAttempts misses (2026-09-27, Olthoi swarm).
if (targetId != _playerId && IsHealthDrop(prevRatio, healthRatio))
_combatManager?.ReportDamageOnTarget((int)targetId);
// Capture observed creature data into the persistent store. maxHealth>0 means
@ -1563,6 +1619,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
CaptureCreatureSample(targetId, maxHealth);
}
/// <summary>
/// True when a health update means the creature lost health: lower than the last ratio
/// we knew, or, for the first report of a creature, below full.
/// </summary>
private static bool IsHealthDrop(float prevRatio, float newRatio)
{
if (float.IsNaN(newRatio)) return false;
return prevRatio < 0f ? newRatio < 0.999f : newRatio < prevRatio - 0.0005f;
}
/// <summary>
/// Something you can fight — what the Damage tab and creatures.json should learn from.
/// Appraising an NPC, a vendor, another player or your own pet also returns health, and

View file

@ -25,6 +25,10 @@ public sealed partial class RynthAiPlugin
return true;
}
// /ub autovendor ... and /ub vendor ... (UtilityBelt AutoVendor) — Vendor/AutoVendorCommands.cs
if (TryHandleAutoVendorCommand(cmd, fullCommand))
return true;
// Most remaining /ub verbs (use / usep / uselp / useip / face / give /
// givep / combatstate / cast …) share semantics with the natively
// implemented /mt verbs, which talk to host primitives (UseObject /

View file

@ -0,0 +1,94 @@
using System;
using RynthCore.Plugin.RynthAi.Vendor;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// UtilityBelt's /ub autovendor and /ub vendor commands. Parsed here (chat thread),
/// run by AutoVendorManager on the plugin tick thread.
/// </summary>
public sealed partial class RynthAiPlugin
{
private AutoVendorManager? _autoVendor;
/// <summary>
/// /ub autovendor [cancel|stop|quit|profile]
/// /ub vendor {open[p] [name|id|hex|selected] | opencancel | buy[all] | sell[all] |
/// clearbuy | clearsell | addbuy[p] [count] item | addsell[p] [count] item}
/// Returns false when the verb isn't an AutoVendor verb.
/// </summary>
private bool TryHandleAutoVendorCommand(string cmd, string fullCommand)
{
if (cmd != "autovendor" && cmd != "vendor")
return false;
var av = _autoVendor;
if (av == null)
{
ChatLine("[RynthAi] AutoVendor isn't ready yet (log in first).");
return true;
}
string rest = AfterWords(fullCommand, 2); // everything after "/ub <verb>"
if (cmd == "autovendor")
{
av.Enqueue(() => av.CommandAutoVendor(rest));
return true;
}
string action = rest;
string args = string.Empty;
int asp = rest.IndexOf(' ');
if (asp >= 0)
{
action = rest.Substring(0, asp);
args = rest.Substring(asp + 1).Trim();
}
action = action.ToLowerInvariant();
switch (action)
{
case "buy":
case "buyall": av.Enqueue(av.CommandBuyAll); break;
case "sell":
case "sellall": av.Enqueue(av.CommandSellAll); break;
case "clearbuy": av.Enqueue(av.CommandClearBuy); break;
case "clearsell": av.Enqueue(av.CommandClearSell); break;
// UB: "open" with no name picks the nearest vendor, like openp.
case "open": av.Enqueue(() => av.CommandOpen(args, partial: args.Length == 0)); break;
case "openp": av.Enqueue(() => av.CommandOpen(args, partial: true)); break;
case "opencancel": av.Enqueue(av.CommandOpenCancel); break;
case "addbuy":
case "addbuyp":
if (args.Length == 0) { VendorUsage(); break; }
av.Enqueue(() => av.CommandAddBuy(args, partial: action == "addbuyp"));
break;
case "addsell":
case "addsellp":
if (args.Length == 0) { VendorUsage(); break; }
av.Enqueue(() => av.CommandAddSell(args, partial: action == "addsellp"));
break;
default:
VendorUsage();
break;
}
return true;
}
/// <summary>The text after the first <paramref name="words"/> space-separated words, trimmed.</summary>
private static string AfterWords(string text, int words)
{
int i = 0;
string s = text ?? string.Empty;
for (int w = 0; w < words; w++)
{
while (i < s.Length && char.IsWhiteSpace(s[i])) i++;
while (i < s.Length && !char.IsWhiteSpace(s[i])) i++;
}
return i < s.Length ? s.Substring(i).Trim() : string.Empty;
}
private void VendorUsage()
=> ChatLine("[RynthAi] Usage: /ub vendor {open[p] <vendorname,vendorid,vendorhex> | buyall | sellall | clearbuy | clearsell | opencancel | addbuy[p] [count] <item> | addsell[p] [count] <item>}");
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,497 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using RynthCore.Loot;
namespace RynthCore.Plugin.RynthAi.Vendor;
// Pure planning for AutoVendor, a port of UtilityBelt's AutoVendor.DoVendoring /
// GetBuyItems / GetSellItems / ItemIsSafeToGetRidOf / AddItemToSellList. No host calls:
// the manager fills these views from the engine's vendor snapshot and the inventory,
// executes the plan, waits for the server, and plans again. One transaction per plan,
// buying before selling, exactly as UB does.
/// <summary>The open vendor (engine VendorInfo).</summary>
internal sealed class VendorView
{
public uint Id { get; init; }
public string Name { get; init; } = string.Empty;
/// <summary>Vendor pays value x BuyRate when you sell.</summary>
public float BuyRate { get; init; } = 1f;
/// <summary>Vendor charges value x SellRate when you buy.</summary>
public float SellRate { get; init; } = 1f;
public uint ItemTypes { get; init; }
public int MaxValue { get; init; }
public bool UsesAltCurrency { get; init; }
public bool Buys(uint itemType) => (ItemTypes & itemType) != 0;
}
/// <summary>One item on the vendor's list (engine VendorItem).</summary>
internal sealed class Listing
{
public uint Id { get; init; }
public string Name { get; init; } = string.Empty;
public AcObjectClass Class { get; init; }
public uint ItemType { get; init; }
/// <summary>How many the vendor has; negative = unlimited.</summary>
public int Amount { get; init; } = -1;
public int StackSize { get; init; } = 1;
public int MaxStackSize { get; init; } = 1;
/// <summary>Value of the listed stack.</summary>
public int Value { get; init; }
/// <summary>Engine's per-unit price at this vendor (0 = unknown).</summary>
public int UnitPrice { get; init; }
/// <summary>Burden of the listed stack.</summary>
public int Burden { get; init; }
public bool NeedsContainerSlot { get; init; }
public bool Unlimited => Amount < 0;
public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
public int UnitValue => StackSize > 1 ? Value / StackSize : Value;
}
/// <summary>A vendor item the profile wants, with how many (int.MaxValue = all you can afford).</summary>
internal sealed class BuyWant
{
public Listing Item { get; init; } = null!;
public int Amount { get; init; }
public string RuleName { get; init; } = string.Empty;
}
/// <summary>An inventory item that passed the safety checks and a Sell rule.</summary>
internal sealed class SellItem
{
public uint Id { get; init; }
public string Name { get; init; } = string.Empty;
public AcObjectClass Class { get; init; }
public uint ItemType { get; init; }
public int StackSize { get; init; } = 1;
/// <summary>Value of the whole stack.</summary>
public int Value { get; init; }
public string RuleName { get; init; } = string.Empty;
public string Location { get; init; } = string.Empty;
public int SortSlot { get; init; }
public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
public int UnitValue => StackSize > 1 ? Value / StackSize : Value;
}
/// <summary>Money and room, read fresh before each plan.</summary>
internal sealed class PackState
{
/// <summary>Pyreals, or the vendor's alt currency.</summary>
public long Funds { get; init; }
/// <summary>Free item slots in the MAIN pack (UB: Weenie(player).FreeSpace).</summary>
public int FreeMainSlots { get; init; }
public int FreeContainerSlots { get; init; }
public int PyrealStackSize { get; init; } = AutoVendorPlanner.DefaultPyrealStackSize;
}
internal enum PlanKind : byte
{
Done = 0,
Buy = 1,
Sell = 2,
Split = 3,
Fatal = 4,
}
internal readonly record struct BuyLine(Listing Item, int Amount);
internal sealed class VendorPlan
{
public PlanKind Kind { get; init; }
public List<BuyLine> Buys { get; init; } = new();
public List<SellItem> Sells { get; init; } = new();
/// <summary>Buy: estimated cost. Sell: estimated payout.</summary>
public long Total { get; init; }
public SellItem? SplitItem { get; init; }
public int SplitAmount { get; init; }
public string Message { get; init; } = string.Empty;
public static VendorPlan Done() => new() { Kind = PlanKind.Done };
public static VendorPlan Fatal(string msg) => new() { Kind = PlanKind.Fatal, Message = msg };
public static VendorPlan Split(SellItem item, int amount, string why) =>
new() { Kind = PlanKind.Split, SplitItem = item, SplitAmount = amount, Message = why };
}
/// <summary>What the manager read about an inventory item for UB's "safe to get rid of" checks.</summary>
internal sealed class SafetyFacts
{
/// <summary>Has appraisal data: without it the checks below can't be trusted, so never sell.</summary>
public bool Appraised { get; init; }
public AcObjectClass Class { get; init; }
public int Value { get; init; }
/// <summary>ACE IsSellable (69); null = unknown (treated as sellable, like UB's default).</summary>
public bool? CanBeSold { get; init; }
public bool IsRare { get; init; }
public bool InMainPack { get; init; }
public bool Equipped { get; init; }
public int Attuned { get; init; }
public int Bonded { get; init; }
public bool Retained { get; init; }
public int TimesTinkered { get; init; }
public int Imbued { get; init; }
public string Inscription { get; init; } = string.Empty;
/// <summary>A pack or focus (holds items).</summary>
public bool HoldsItems { get; init; }
}
internal static class AutoVendorPlanner
{
public const int MaxVendorBuyCount = 5000; // UB MAX_VENDOR_BUY_COUNT
public const int MaxSellLines = 99; // UB: GDLE rejects 100+ items per transaction
public const int DefaultPyrealStackSize = 25000;
public const uint PyrealWcid = 273;
public const uint ItemTypePromissoryNote = 0x00040000;
// UB ShopItemListTypes: shop category names for the test-mode report.
private static readonly (uint Bit, string Name)[] ShopCategories =
{
(0x00000001, "Weapons"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"),
(0x00000010, "Miscellaneous"), (0x00000020, "Food"), (0x00000080, "Miscellaneous"), (0x00000100, "Weapons"),
(0x00000200, "Containers"), (0x00000400, "Miscellaneous"), (0x00000800, "Gems"), (0x00001000, "Spell Components"),
(0x00002000, "Books, Paper"), (0x00004000, "Keys, Tools"), (0x00008000, "Magic Items"), (0x00040000, "Trade Notes"),
(0x00080000, "Mana Stones"), (0x00100000, "Services"), (0x00400000, "Cooking Items"), (0x00800000, "Alchemical Items"),
(0x01000000, "Fletching Items"), (0x04000000, "Alchemical Items"), (0x08000000, "Fletching Items"), (0x20000000, "Keys, Tools"),
};
public static string CategoryName(uint itemType)
{
foreach (var (bit, name) in ShopCategories)
if ((itemType & bit) != 0) return name;
return $"Unknown Category 0x{itemType:X8}";
}
// ── Prices (ACE Vendor.GetSellCost / GetBuyCost, as the engine checks them) ──────────
/// <summary>What you pay for one created stack worth <paramref name="stackValue"/>.</summary>
public static long PlayerPays(VendorView v, bool isNote, long stackValue)
{
float rate = isNote ? 1.15f : v.SellRate;
float product = rate * stackValue;
return Math.Max(1L, (long)Math.Ceiling(product - 0.1));
}
/// <summary>What the vendor pays for one item (whole stack) worth <paramref name="value"/>.</summary>
public static long VendorPays(VendorView v, bool isNote, long value)
{
float rate = isNote ? 1.0f : v.BuyRate;
float product = rate * value;
return Math.Max(1L, (long)Math.Floor(product + 0.1));
}
/// <summary>Per-unit price: the engine's figure, else UB's (int)(Value/Stack) x rate rounded like ACE.</summary>
public static long UnitPrice(VendorView v, Listing item)
{
if (item.UnitPrice > 0) return item.UnitPrice;
if (item.UnitValue <= 0) return 0;
return PlayerPays(v, item.IsNote, item.UnitValue);
}
/// <summary>The engine's EstimateBuy: stackables in full stacks, limited listings at least the whole listing.</summary>
public static long EstimateCost(VendorView v, Listing item, int amount)
{
if (amount <= 0) return 0;
long unitValue = Math.Max(0, item.UnitValue);
long cost;
if (item.MaxStackSize > 1)
{
long max = item.MaxStackSize;
long full = amount / max;
long rem = amount % max;
cost = full * PlayerPays(v, item.IsNote, unitValue * max) + (rem > 0 ? PlayerPays(v, item.IsNote, unitValue * rem) : 0);
}
else
{
cost = amount * PlayerPays(v, item.IsNote, unitValue);
}
if (!item.Unlimited)
cost = Math.Max(cost, PlayerPays(v, item.IsNote, Math.Max(0, item.Value)));
return cost;
}
/// <summary>Largest amount in [0, max] whose EstimateCost fits <paramref name="money"/> (cost only grows with amount).</summary>
public static int MostAffordable(VendorView v, Listing item, int max, long money)
{
int lo = 0, hi = Math.Max(0, max);
while (lo < hi)
{
int mid = lo + (hi - lo + 1) / 2;
if (EstimateCost(v, item, mid) <= money) lo = mid;
else hi = mid - 1;
}
return lo;
}
public static int SlotsFor(Listing item, int amount)
{
int max = Math.Max(1, item.MaxStackSize);
return (int)((amount + (long)max - 1) / max);
}
/// <summary>UB PyrealsWillFitInMainPack: always leaves one main-pack slot free.</summary>
public static bool PyrealsFit(PackState p, double amount)
{
int stack = Math.Max(1, p.PyrealStackSize);
return p.FreeMainSlots - Math.Ceiling(amount / stack) > 0;
}
// ── Safety (UB ItemIsSafeToGetRidOf + Util.IsItemSafeToGetRidOf, stricter) ──────────
/// <summary>Null when the item may be sold; otherwise the reason it never will be.</summary>
public static string? UnsafeReason(SafetyFacts f, bool onlyFromMainPack)
{
if (!f.Appraised) return "not identified";
if (f.Equipped) return "equipped";
if (f.Class == AcObjectClass.Money) return "money";
if (f.Class == AcObjectClass.Container || f.HoldsItems) return "container";
if (f.Class == AcObjectClass.Foci) return "focus";
if (f.Value <= 0) return "no value";
if (f.CanBeSold == false) return "not sellable";
if (f.IsRare) return "rare";
if (onlyFromMainPack && !f.InMainPack) return "not in main pack";
if (f.Attuned != 0) return "attuned";
if (f.Bonded != 0) return "bonded";
if (f.Retained) return "retained";
if (f.TimesTinkered > 0) return "tinkered";
if (f.Imbued != 0) return "imbued";
if (!string.IsNullOrEmpty(f.Inscription)) return "inscribed";
return null;
}
/// <summary>
/// UB VendorInfo.WillBuyItem. Trade notes skip the value cap like UB, but the vendor must
/// still list the note item type: the engine refuses anything outside the vendor's types.
/// </summary>
public static bool VendorWillBuy(VendorView v, uint itemType, bool isNote, int unitValue)
{
if (!v.Buys(itemType)) return false;
if (isNote) return true;
return v.MaxValue > 0 && unitValue <= v.MaxValue;
}
// ── Buy list (UB GetBuyItems) ────────────────────────────────────────────
/// <summary>
/// Keep # buys (count - have), where have is the inventory count by exact name (containers:
/// by object class, and only the first container rule). Keep buys int.MaxValue. Sorted
/// trade notes last, then cheapest unit price first.
/// </summary>
public static List<BuyWant> BuildBuyWants(
VendorView v,
IEnumerable<(Listing Item, BuyDecision Decision)> judged,
Func<string, int> countByName,
Func<AcObjectClass, int> countByClass)
{
var list = judged.ToList();
var wants = new List<BuyWant>();
bool buyingContainers = false;
foreach (var (item, d) in list)
{
if (d.Kind != BuyKind.KeepUpTo) continue;
if (item.Class == AcObjectClass.Container)
{
int have = countByClass(AcObjectClass.Container);
if (!buyingContainers && d.KeepCount > have)
{
buyingContainers = true;
wants.Add(new BuyWant { Item = item, Amount = d.KeepCount - have, RuleName = d.RuleName });
}
}
else
{
int have = countByName(item.Name);
if (d.KeepCount > have)
wants.Add(new BuyWant { Item = item, Amount = d.KeepCount - have, RuleName = d.RuleName });
}
}
foreach (var (item, d) in list)
if (d.Kind == BuyKind.Keep)
wants.Add(new BuyWant { Item = item, Amount = int.MaxValue, RuleName = d.RuleName });
return wants
.OrderBy(w => w.Item.IsNote ? 1 : 0)
.ThenBy(w => UnitPrice(v, w.Item))
.ToList();
}
/// <summary>UB GetSellItems sort: trade notes last, then cheapest stack payout first.</summary>
public static List<SellItem> SortSells(VendorView v, IEnumerable<SellItem> items) =>
items.OrderBy(s => s.IsNote ? 1 : 0)
.ThenBy(s => VendorPays(v, s.IsNote, s.Value))
.ToList();
// ── One transaction (UB DoVendoring) ─────────────────────────────────────
/// <param name="wants">From BuildBuyWants (already sorted).</param>
/// <param name="sells">From SortSells.</param>
public static VendorPlan PlanNext(VendorView v, IReadOnlyList<BuyWant> wants, IReadOnlyList<SellItem> sells, PackState p)
{
// ── Buy first ──
var buys = new List<BuyLine>();
long totalCost = 0;
int totalSlots = 0, totalContainerSlots = 0;
// UB re-orders by the listing's raw Value here (a stable sort over the price order).
foreach (var want in wants.OrderBy(w => w.Item.Value))
{
Listing item = want.Item;
long price = UnitPrice(v, item);
if (price <= 0)
return VendorPlan.Fatal(string.Format(CultureInfo.InvariantCulture,
"AutoVendor Fatal - No vendor price found while adding {0:n0}x {1}[0x{2:X8}] Value: {3:n}",
want.Amount, item.Name, item.Id, (double)price));
bool fits;
if (item.NeedsContainerSlot)
fits = p.FreeContainerSlots - totalContainerSlots > 0;
else
fits = p.FreeMainSlots - totalSlots > (item.IsNote ? 0 : 1);
if (totalCost + price <= p.Funds && fits)
{
long affordable = (p.Funds - totalCost) / price;
long count = Math.Min(affordable, want.Amount);
count = Math.Min(count, MaxVendorBuyCount);
if (!item.Unlimited) count = Math.Min(count, item.Amount);
if (item.NeedsContainerSlot)
{
count = Math.Min(count, p.FreeContainerSlots - totalContainerSlots);
}
else if (p.FreeMainSlots < SlotsFor(item, (int)count) + totalSlots)
{
// UB: limit to what fits, keeping two slots spare (never below zero).
long fit = (long)Math.Max(1, item.MaxStackSize) * Math.Max(0, (p.FreeMainSlots - 2) - totalSlots);
count = Math.Min(count, fit);
}
// The engine's exact cost can exceed the per-unit estimate (a limited listing
// costs at least the whole listing): take the most that still fits the money.
if (count > 0 && totalCost + EstimateCost(v, item, (int)count) > p.Funds)
count = MostAffordable(v, item, (int)count, p.Funds - totalCost);
if (count <= 0)
break;
int n = (int)count;
buys.Add(new BuyLine(item, n));
if (item.NeedsContainerSlot) totalContainerSlots += n;
else totalSlots += SlotsFor(item, n);
totalCost += EstimateCost(v, item, n);
if (want.Amount > n)
break; // couldn't take all of it: don't reach for the next item
}
else if (buys.Count > 0)
{
break;
}
}
if (buys.Count > 0)
return new VendorPlan { Kind = PlanKind.Buy, Buys = buys, Total = totalCost };
// ── Then sell ──
// nextBuy: the item we want but couldn't afford (notes are sold only to pay for it).
// An alt-currency vendor isn't paid in pyreals, so selling can't fund its items.
Listing? nextBuy = !v.UsesAltCurrency && wants.Count > 0 ? wants[0].Item : null;
var chosen = new List<SellItem>();
long totalValue = 0;
for (int i = 0; i < sells.Count && chosen.Count < MaxSellLines; i++)
{
SellItem item = sells[i];
int stack = Math.Max(1, item.StackSize);
long stackPayout = VendorPays(v, item.IsNote, item.Value);
double unit = (double)stackPayout / stack;
// Never sell notes to buy notes, and never sell notes when there's nothing to buy.
if (item.IsNote && (nextBuy == null || nextBuy.IsNote))
break;
// Selling notes to afford something: one note at a time, and only on its own.
if (nextBuy != null && item.IsNote)
{
if (chosen.Count > 0) break;
if (!PyrealsFit(p, unit))
return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}");
SellItem? single = null;
foreach (var s in sells)
if (s.IsNote && s.StackSize <= 1 && string.Equals(s.Name, item.Name, StringComparison.Ordinal))
{ single = s; break; }
if (single != null)
return new VendorPlan { Kind = PlanKind.Sell, Sells = new List<SellItem> { single }, Total = VendorPays(v, true, single.Value) };
return VendorPlan.Split(item, 1, $"one {item.Name} to afford {nextBuy.Name}");
}
// Can't sell the whole stack? Split off what the pyreals will fit.
if (!PyrealsFit(p, totalValue + stackPayout))
{
if (chosen.Count < 1)
{
int newStack = unit > 0 ? (int)Math.Floor((p.FreeMainSlots - 2) * (double)Math.Max(1, p.PyrealStackSize) / unit) : 0;
newStack = Math.Min(newStack, stack - 1);
if (newStack > 0)
return VendorPlan.Split(item, newStack, "the pyreals for the whole stack won't fit");
return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}");
}
break;
}
chosen.Add(item);
totalValue += stackPayout;
}
if (chosen.Count > 0)
return new VendorPlan { Kind = PlanKind.Sell, Sells = chosen, Total = totalValue };
return VendorPlan.Done();
}
// ── /ub vendor addsell (UB AddItemToSellList) ────────────────────────────
/// <summary>
/// Whole stacks that fit in the remaining count are taken; if units are still missing,
/// the smallest stack bigger than what's missing is returned to be split.
/// </summary>
public static (List<SellItem> Whole, int Missing, SellItem? SplitFrom) PlanAddSell(IReadOnlyList<SellItem> matches, int count)
{
var whole = new List<SellItem>();
int needed = Math.Max(0, count);
SellItem? oversized = null;
foreach (var m in matches)
{
if (needed == 0) break;
int stack = Math.Max(1, m.StackSize);
if (stack <= needed)
{
whole.Add(m);
needed -= stack;
}
else if (oversized == null || oversized.StackSize > stack)
{
oversized = m;
}
}
return (whole, needed, needed > 0 ? oversized : null);
}
// ── Shared parsing ───────────────────────────────────────────────────────
/// <summary>"[count] name" as UB's addbuy/addsell read it; count defaults to 1.</summary>
public static (int Count, string Name) ParseCountAndName(string args)
{
string s = (args ?? string.Empty).Trim();
int sp = s.IndexOf(' ');
if (sp > 0 && int.TryParse(s.Substring(0, sp), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
return (n, s.Substring(sp + 1).Trim());
return (1, s);
}
}

View file

@ -0,0 +1,318 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
namespace RynthCore.Plugin.RynthAi.Vendor;
// Pure rule judging for AutoVendor: no host, no WorldObject. The manager hands in a
// per-condition matcher (VTankLootEvaluator.MatchCondition) and the facts it has about
// the item; this file decides which conditions can be answered with that data and turns
// the answers into a profile verdict. Kept dependency-free so the test project can link it.
//
// Selling is destructive, so every answer is three-valued: Yes, No, or Unknown ("we don't
// have the data VTank would use"). A rule with an Unknown condition never counts as a
// match. UB leans on VTank's own evaluator; ours has approximations (buffed damage, colour
// similarity, base skill), and those node types always read Unknown here.
internal enum Tri : byte
{
No = 0,
Yes = 1,
Unknown = 2,
}
/// <summary>What the manager knows about an item before judging it.</summary>
internal readonly struct ItemFacts
{
/// <summary>An item on the vendor's list: only the engine's vendor snapshot is known.</summary>
public bool IsVendorListing { get; init; }
/// <summary>Inventory item with appraisal (ID) data.</summary>
public bool Appraised { get; init; }
public AcObjectClass ObjectClass { get; init; }
/// <summary>The item's spell list can be read (appraised and the host exposes spell ids).</summary>
public bool HasSpellData { get; init; }
public bool HasPalettes { get; init; }
public bool HasCharacterSkills { get; init; }
public bool HasCharacterLevel { get; init; }
}
/// <summary>The profile's answer for one item.</summary>
internal sealed class ProfileVerdict
{
/// <summary>First rule that matched (Certain) or might match (!Certain); null = no rule can match.</summary>
public VTankLootRule? Rule { get; init; }
public int RuleIndex { get; init; } = -1;
/// <summary>True when Rule definitely matched, or when no rule can match at all.</summary>
public bool Certain { get; init; }
/// <summary>Some Keep / Keep # rule anywhere in the profile matches or might match.</summary>
public bool KeepPossible { get; init; }
/// <summary>Name of a Keep / Keep # rule that matches or might match (for messages).</summary>
public string KeepRuleName { get; init; } = string.Empty;
/// <summary>Why the deciding rule could not be judged (node type name), when !Certain.</summary>
public string UnknownReason { get; init; } = string.Empty;
public string RuleName => Rule == null ? string.Empty : AutoVendorRules.RuleLabel(Rule, RuleIndex);
}
internal enum BuyKind : byte
{
None = 0,
/// <summary>Keep: buy as many as you can afford.</summary>
Keep = 1,
/// <summary>Keep #: buy up to the rule's count.</summary>
KeepUpTo = 2,
}
internal readonly record struct BuyDecision(BuyKind Kind, int KeepCount, string RuleName);
internal readonly record struct SellDecision(bool Sell, string RuleName, string Reason);
internal static class AutoVendorRules
{
// STypeInt keys a vendor listing carries (engine VendorItem: ItemType, Burden,
// MaxStackSize, StackSize, Value). Anything else on a listing is unknown.
internal static readonly HashSet<int> ListingIntKeys = new() { 1, 5, 11, 12, 19 };
// Keys the client keeps in PublicWeenieDesc, readable without appraisal
// (items/containers capacity, locations, wielded location, stack sizes, material).
internal static readonly HashSet<int> PwdIntKeys = new() { 6, 7, 9, 10, 11, 12, 131 };
// Decal's synthetic LongValueKey ids start at 0x0D000000; RynthAi reads STypes only.
internal const int MaxStandardKey = 0xFFFF;
// RynthAi derives ObjectClass from ITEM_TYPE alone. Decal splits these further
// (Misc -> HealingKit/Lockpick, Book -> Scroll/Journal/Sign, Container -> Foci,
// Key -> Lockpick, Food -> Plant), so an ObjectClass test on them is unknown.
internal static readonly HashSet<AcObjectClass> CoarseClasses = new()
{
AcObjectClass.Unknown, AcObjectClass.Misc, AcObjectClass.Book,
AcObjectClass.Container, AcObjectClass.Food, AcObjectClass.Key,
};
public static string RuleLabel(VTankLootRule rule, int index)
=> string.IsNullOrWhiteSpace(rule.Name) ? $"#{index}" : rule.Name.Trim();
/// <summary>Can this condition be answered for an item with these facts?</summary>
public static bool CanJudge(VTankLootCondition cond, in ItemFacts f)
{
var d = cond.DataLines;
switch (cond.NodeType)
{
case VTankNodeTypes.DisabledRule:
case VTankNodeTypes.DamagePercentGE: // VTank itself always answers "no"
case VTankNodeTypes.ObjectClass: // coarse classes handled in JudgeObjectClass
return true;
case VTankNodeTypes.CharacterMainPackEmptySlotsGE:
return true;
case VTankNodeTypes.CharacterSkillGE:
return f.HasCharacterSkills;
case VTankNodeTypes.CharacterLevelGE:
case VTankNodeTypes.CharacterLevelLE:
return f.HasCharacterLevel;
case VTankNodeTypes.StringValueMatch:
{
if (!TryKey(d, 1, out int key)) return false;
if (key == 1) return true; // Name
return !f.IsVendorListing && f.Appraised && key <= MaxStandardKey;
}
case VTankNodeTypes.LongValKeyLE:
case VTankNodeTypes.LongValKeyGE:
case VTankNodeTypes.LongValKeyE:
case VTankNodeTypes.LongValKeyNE:
case VTankNodeTypes.LongValKeyFlagExists:
{
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);
}
case VTankNodeTypes.DoubleValKeyLE:
case VTankNodeTypes.DoubleValKeyGE:
{
if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false;
return !f.IsVendorListing && f.Appraised;
}
case VTankNodeTypes.SpellNameMatch:
case VTankNodeTypes.SpellMatch:
case VTankNodeTypes.SpellCountGE:
return !f.IsVendorListing && f.HasSpellData;
case VTankNodeTypes.SlotExactPalette:
return !f.IsVendorListing && f.HasPalettes;
case VTankNodeTypes.TotalRatingsGE:
return !f.IsVendorListing && f.Appraised;
// Approximated or not implemented by RynthAi's evaluator: never trusted.
case VTankNodeTypes.AnySimilarColor:
case VTankNodeTypes.SimilarColorArmorType:
case VTankNodeTypes.SlotSimilarColor:
case VTankNodeTypes.CharacterBaseSkill:
case VTankNodeTypes.MinDamageGE:
case VTankNodeTypes.BuffedMedianDamageGE:
case VTankNodeTypes.BuffedMissileDamageGE:
case VTankNodeTypes.BuffedLongValKeyGE:
case VTankNodeTypes.BuffedDoubleValKeyGE:
case VTankNodeTypes.CalcdBuffedTinkedDamageGE:
case VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE:
default:
return false;
}
}
/// <summary>ObjectClass test without the evaluator: unknown for classes Decal splits further.</summary>
public static Tri JudgeObjectClass(VTankLootCondition cond, AcObjectClass itemClass)
{
if (!TryKey(cond.DataLines, 0, out int target)) return Tri.Unknown;
if (CoarseClasses.Contains(itemClass)) return Tri.Unknown;
return (int)itemClass == target ? Tri.Yes : Tri.No;
}
/// <summary>
/// Judge one condition. <paramref name="match"/> is only called for conditions that
/// CanJudge says are answerable; if it throws (malformed data line) the answer is Unknown.
/// </summary>
public static Tri JudgeCondition(VTankLootCondition cond, in ItemFacts f, Func<VTankLootCondition, bool> match)
{
if (!CanJudge(cond, f)) return Tri.Unknown;
if (cond.NodeType == VTankNodeTypes.ObjectClass) return JudgeObjectClass(cond, f.ObjectClass);
try { return match(cond) ? Tri.Yes : Tri.No; }
catch { return Tri.Unknown; }
}
/// <summary>All conditions must hold: any No -> No, else any Unknown -> Unknown, else Yes.</summary>
public static Tri JudgeRule(VTankLootRule rule, Func<VTankLootCondition, Tri> cond, out string unknownReason)
{
unknownReason = string.Empty;
if (rule.Conditions.Count == 0) return Tri.Yes;
bool unknown = false;
foreach (var c in rule.Conditions)
{
Tri t = cond(c);
if (t == Tri.No) { unknownReason = string.Empty; return Tri.No; }
if (t == Tri.Unknown && !unknown)
{
unknown = true;
unknownReason = VTankNodeTypes.DisplayName(c.NodeType);
}
}
return unknown ? Tri.Unknown : Tri.Yes;
}
/// <summary>
/// VTank order: the first rule that matches decides. A rule that might match stops the
/// scan too (we can't know whether it or a later rule applies). Also records whether
/// any Keep / Keep # rule anywhere could match, which AutoVendor treats as "never sell".
/// </summary>
public static ProfileVerdict Decide(IReadOnlyList<VTankLootRule> rules, Func<VTankLootCondition, Tri> cond)
{
VTankLootRule? decided = null;
int decidedIdx = -1;
bool certain = true;
string reason = string.Empty;
bool keepPossible = false;
string keepName = string.Empty;
for (int i = 0; i < rules.Count; i++)
{
var rule = rules[i];
bool isKeep = rule.Action is VTankLootAction.Keep or VTankLootAction.KeepUpTo;
if (decided != null && (!isKeep || keepPossible))
continue; // only still scanning for keep rules
Tri t = JudgeRule(rule, cond, out string why);
if (t == Tri.No) continue;
if (isKeep && !keepPossible)
{
keepPossible = true;
keepName = RuleLabel(rule, i);
}
if (decided == null)
{
decided = rule;
decidedIdx = i;
certain = t == Tri.Yes;
reason = why;
}
}
return new ProfileVerdict
{
Rule = decided,
RuleIndex = decidedIdx,
Certain = decided == null || certain,
UnknownReason = reason,
KeepPossible = keepPossible,
KeepRuleName = keepName,
};
}
/// <summary>
/// UB GetBuyItems for one vendor listing: Keep # buys up to the count, Keep buys all it
/// can afford. First match decides, as in VTank. A rule we can't judge (a listing carries
/// only name, type, value, stack and burden) is handled so we never buy more than VTank would:
/// an unjudgeable non-buy rule ends the scan with no purchase (it might be the one that
/// matches); an unjudgeable Keep / Keep # rule lets the scan go on, since either way the
/// item gets bought, and the smallest count seen is used.
/// </summary>
public static BuyDecision DecideBuy(IReadOnlyList<VTankLootRule> rules, Func<VTankLootCondition, Tri> cond)
{
long cap = long.MaxValue;
for (int i = 0; i < rules.Count; i++)
{
var rule = rules[i];
Tri t = JudgeRule(rule, cond, out _);
if (t == Tri.No) continue;
long count = rule.Action switch
{
VTankLootAction.KeepUpTo => Math.Max(0, rule.KeepCount ?? 0),
VTankLootAction.Keep => int.MaxValue,
_ => -1,
};
if (count < 0)
return new BuyDecision(BuyKind.None, 0, RuleLabel(rule, i)); // a non-buy rule matches or might
cap = Math.Min(cap, count);
if (t == Tri.Yes)
{
int n = (int)Math.Min(cap, int.MaxValue);
return n == int.MaxValue
? new BuyDecision(BuyKind.Keep, int.MaxValue, RuleLabel(rule, i))
: new BuyDecision(BuyKind.KeepUpTo, n, RuleLabel(rule, i));
}
}
return new BuyDecision(BuyKind.None, 0, string.Empty);
}
/// <summary>
/// UB GetSellItems (result.IsSell), stricter: the deciding rule must be a Sell rule that
/// definitely matched, and no Keep / Keep # rule anywhere in the profile may match or
/// possibly match the item.
/// </summary>
public static SellDecision JudgeSell(ProfileVerdict v)
{
if (v.Rule == null) return new SellDecision(false, string.Empty, "no rule matches");
if (v.Rule.Action != VTankLootAction.Sell)
return new SellDecision(false, v.RuleName, $"first rule is {v.Rule.Action}");
if (!v.Certain)
return new SellDecision(false, v.RuleName, $"rule '{v.RuleName}' needs {v.UnknownReason} data we don't have");
if (v.KeepPossible)
return new SellDecision(false, v.RuleName, $"also matches keep rule '{v.KeepRuleName}'");
return new SellDecision(true, v.RuleName, string.Empty);
}
private static bool TryKey(IList<string> d, int idx, out int value)
{
value = 0;
return d != null && idx < d.Count
&& int.TryParse(d[idx].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
}
}