diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs index fe62ab5..9fde1e7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs @@ -36,6 +36,12 @@ public partial class CombatManager // Priority 0 ones (ignored by the rule, so never above anything). private readonly List _passedOver = new(); + // Refilled by every scan: monsters up to PassedOverBeyondRangeM past Monster Range (not the + // engaged one), id and distance only. A higher priority among them is not a candidate only + // because of the Monster Range setting, which a player can't tell from the chair (the owner, + // 2026-11-01: "might have just been the attack distance being set too low"). + private readonly List _beyondRange = new(); + // Per lock: the monsters already logged as passed over, with the reason logged, so a // monster held behind a wall is one line, not one per tick. Emptied by every lock. private readonly Dictionary _passedOverLogged = new(); @@ -64,9 +70,16 @@ public partial class CombatManager /// The second half walks the landscape, so it is for the lock line only (a lock is rare). /// internal string? DescribePassedOver(int priority, int pickedId, bool lookBeyondRange) + => DescribePassedOver(priority, pickedId, lookBeyondRange, out _); + + private string? DescribePassedOver(int priority, int pickedId, bool lookBeyondRange, out int namedId) { + namedId = 0; if (TryBestPassedOver(priority, pickedId, out var po, out int poPriority)) + { + namedId = po.Id; return $"0x{po.Id:X8} '{_worldFilter[po.Id]?.Name}' priority {poPriority}, {po.Distance:0.0} m: {po.Why}"; + } if (!lookBeyondRange) return null; int playerId = (int)_playerId; @@ -85,6 +98,7 @@ public partial class CombatManager if (p <= priority) continue; bestId = wo.Id; bestP = p; bestDist = d; } + namedId = bestId; return bestId == 0 ? null : $"0x{bestId:X8} '{_worldFilter[bestId]?.Name}' priority {bestP}, {bestDist:0.0} m: beyond Monster Range ({range:0.#} m)"; } @@ -115,7 +129,9 @@ public partial class CombatManager /// internal void NotePassedOverWhileEngaged() { - if (_lockedTargetId == 0 || _passedOver.Count == 0) return; + if (_lockedTargetId == 0) return; + NoteBeyondRangeWhileEngaged(); + if (_passedOver.Count == 0) return; for (int i = 0; i < _passedOver.Count; i++) { var po = _passedOver[i]; @@ -130,12 +146,52 @@ public partial class CombatManager } } + /// The reason logged for a higher priority that is only past Monster Range. + internal string BeyondRangeWhy() => + $"beyond Monster Range ({Math.Max(1.0, _settings.MonsterRange):0.#} m), the Monster Range setting"; + + /// + /// While a target is fought: a monster of a higher Priority just past Monster Range is logged + /// once per monster for this lock. Selection is unchanged (only monsters inside Monster Range + /// are candidates); this says the setting is why. + /// + private void NoteBeyondRangeWhileEngaged() + { + if (_beyondRange.Count == 0) return; + string why = BeyondRangeWhy(); + for (int i = 0; i < _beyondRange.Count; i++) + { + var po = _beyondRange[i]; + if (po.Id == _lockedTargetId) continue; + if (_passedOverLogged.TryGetValue(po.Id, out string? was) && was == why) continue; + if (_recentlyKilled.ContainsKey(po.Id) || _worldFilter.GetHealthRatio(po.Id) == 0f) continue; + int p = PriorityOf(po.Id); + if (p <= _lockedPriority) continue; + if (_passedOverLogged.Count >= 64) _passedOverLogged.Clear(); + _passedOverLogged[po.Id] = why; + _host.Log($"[CombatTarget] passed over 0x{po.Id:X8} '{_worldFilter[po.Id]?.Name}' priority {p}, {po.Distance:0.0} m: {why}; " + + $"the target stays 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' priority {_lockedPriority}"); + } + } + + /// + /// For /ra why: the best higher-priority monster the current target was picked over (left out + /// by the scan, or just past Monster Range) and why, or null when there is none or no target. + /// + internal string? DescribeHigherPriorityPassedOver() + { + if (_lockedTargetId == 0) return null; + return DescribePassedOver(_lockedPriority, _lockedTargetId, lookBeyondRange: true); + } + /// A new lock: the lock line names what it passed over; the per-lock log starts over. private string PassedOverNoteForLock(int bestId, int bestPriority) { _passedOverLogged.Clear(); - string? po = DescribePassedOver(bestPriority, bestId, lookBeyondRange: true); + string? po = DescribePassedOver(bestPriority, bestId, lookBeyondRange: true, out int namedId); if (po == null) return ""; + // Named on the lock line: not logged again by NoteBeyondRangeWhileEngaged. + if (namedId != 0) _passedOverLogged[namedId] = BeyondRangeWhy(); // The monster named here isn't logged again by NotePassedOverWhileEngaged for the same reason. if (TryBestPassedOver(bestPriority, bestId, out var inRange, out _)) _passedOverLogged[inRange.Id] = inRange.Why; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs index 01b604e..142fc1b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs @@ -147,6 +147,7 @@ public partial class CombatManager bool atFight = castTarget == unchecked((uint)activeTargetId); bool judged = atFight && !area && !noJudge; _lastCastWasRing = !judged; // anything else gets no per-target judgement + if (atFight) NoteCastSent(activeTargetId); // the in-flight hold (Target Lock off) _wallFaceAt = DateTime.MinValue; if (judged) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.SelectedTarget.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.SelectedTarget.cs new file mode 100644 index 0000000..dec70b3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.SelectedTarget.cs @@ -0,0 +1,134 @@ +// ============================================================================ +// RynthSuite - Combat/CombatManager.SelectedTarget.cs +// "Fight the monster I select" (Settings > Ranges > Combat Targeting, off by default; +// /ra fightselected [on|off]; the FightSelectedTarget setting key): the automatic form of +// the target lock (CombatManager.TargetLock.cs). When the PLAYER selects an attackable monster +// in game, it becomes the forced target: fought ahead of the Targeting setting and the +// Priority tiers until it dies, can't be reached (blacklisted, or out of the scan for +// ForcedTargetLostMs from the click), or the player selects another monster or deselects. +// +// Player or bot? RynthAi's own selections are marked right before Host.SelectItem +// (ItemInfo.SelfSelect: combat's native attack re-selecting its target, the looter's corpse +// and item picks, a meta's selectitem). A selection change the bot didn't just make is the +// player's: a click in the game world, the radar, or another plugin's window (RynthDefective's +// Selection window, RynthLua scripts) all go through the same in-game selection and count. +// +// Followed: monsters the combat scan accepts - a Monster, attackable, alive, not a player, +// not a pet, not blacklisted, not Priority 0 ("ignore") and not on the never-attack list +// (/ra targetlock still forces those). Not followed (nothing changes, the lock stays): items, +// corpses, NPCs, players, the character itself. +// Reach: like an engaged target, out to Disengage Range (Monster Range + 3 by default). A +// monster selected farther away is said once in chat; it is fought if it comes within that +// reach in time, never chased past it. +// A /ra targetlock lock is the player's explicit pick: selections never move it. /ra targetlock +// on a monster the setting is already fighting turns it into that explicit lock. +// Only selections made while the macro runs with Combat on are followed. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Plugin.RynthAi; + +public partial class CombatManager +{ + private const string SelectedSettingOff = "the setting was turned off"; + + // The forced target came from the player's selection (Fight the monster I select), not from + // /ra targetlock. Written with _forcedTargetId; the game thread sets it, the pump reads it. + private volatile bool _forcedBySelection; + private long _selectedAtTicks; // TargetClock ticks of the click that set it + private int _selectedFarNotedId; // the "too far" chat line, once per monster + + /// The forced target is the monster the player selected (not a /ra targetlock). + public bool ForcedBySelection => _forcedBySelection && ForcedTargetId != 0; + + private DateTime SelectedAt + { + get + { + long t = Interlocked.Read(ref _selectedAtTicks); + return t == 0 ? DateTime.MinValue : new DateTime(t); + } + } + + /// Why the player's selection of isn't followed, or null. + internal string? SelectedTargetRefusal(int id) + { + string? refusal = ForcedTargetRefusal(id); + if (refusal != null) return refusal; + var wo = _worldFilter[id]!; // known: ForcedTargetRefusal checked it + if (_host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)id), out uint wcid) && wcid != 0 + && CreatureData.PlayerWeenies.IsPlayerWcid(wcid)) + return $"{wo.Name} is a player"; + if (_blacklistManager.IsBlacklisted(id)) return $"{wo.Name} is blacklisted (unreachable)"; + if (IsUserBlacklistedName(wo.Name)) return $"{wo.Name} is on the never-attack list"; + if (PriorityOf(id) <= 0) return $"{wo.Name} is set to ignore (Priority 0)"; + return null; + } + + /// + /// The in-game selection changed to (0 = deselected). + /// : RynthAi selected it itself (ItemInfo.SelfSelect), so it's not + /// the player's choice. Returns what it did, for the log and tests (null = nothing). + /// + internal string? OnSelectionChanged(uint selected, bool ours) + { + if (!_settings.FightSelectedTarget || ours) return null; + int fid = ForcedTargetId; + if (fid != 0 && !_forcedBySelection) return null; // a /ra targetlock lock: kept + + if (selected == 0) + { + if (fid == 0) return null; + string gone = _worldFilter[fid]?.Name ?? $"0x{(uint)fid:X8}"; + ClearForcedTarget(); + _host.Log($"[CombatTarget] fight-selected: deselected, 0x{(uint)fid:X8} '{gone}' released"); + return "deselected"; + } + + int id = unchecked((int)selected); + if (id == fid) return null; + if (!_settings.IsMacroRunning || !_settings.EnableCombat) return null; + + string? refusal = SelectedTargetRefusal(id); + if (refusal != null) + { + // Monsters only: the player's item and corpse clicks aren't worth a log line. + var seen = _worldFilter[id]; + if (seen != null && (int)seen.ObjectClass == (int)AcObjectClass.Monster) + _host.Log($"[CombatTarget] fight-selected: 0x{selected:X8} '{seen.Name}' not followed: {refusal}"); + return refusal; + } + + var wo = _worldFilter[id]!; + Interlocked.Exchange(ref _selectedAtTicks, TargetClock().Ticks); + _forcedBySelection = true; + Interlocked.Increment(ref _forcedSetSeq); + Volatile.Write(ref _forcedTargetId, id); + + double reach = Math.Max(_settings.MonsterRange, DisengageDistance); + double dist = _worldFilter.Distance(unchecked((int)_playerId), id); + bool far = dist < double.MaxValue && dist > reach; + _host.Log($"[CombatTarget] fight-selected: the player selected 0x{selected:X8} '{wo.Name}'" + + (dist < double.MaxValue ? $" at {dist:0.0} m" : "") + (far ? $" (past the {reach:0} m reach)" : "") + ": fighting it first"); + if (far && _selectedFarNotedId != id) + { + _selectedFarNotedId = id; + _host.WriteToChat($"[RynthAi] {wo.Name} is {dist:0} yd away, past Disengage Range ({reach:0} yd): " + + $"fighting it if it comes that close in the next {ForcedTargetLostMs / 1000:0} s, not chasing it.", 1); + } + return far ? "far" : "locked"; + } + + /// + /// /ra targetlock on the monster this setting already fights: it becomes the explicit lock + /// (selections no longer move it). True when it did. + /// + internal bool PromoteSelectedToTargetLock(int id) + { + if (id == 0 || !_forcedBySelection || ForcedTargetId != id) return false; + _forcedBySelection = false; + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.TargetLock.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.TargetLock.cs index 7ff1979..9fc56d4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.TargetLock.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.TargetLock.cs @@ -11,6 +11,11 @@ // turns into a corpse, gets blacklisted (unreachable), is out of the scan for // ForcedTargetLostMs, or the player clears it (/ra targetlock off, or the same // monster again). +// +// "Fight the monster I select" (CombatManager.SelectedTarget.cs) sets the same lock from the +// player's own in-game selection; _forcedBySelection tells the two apart (it ends quietly on +// the kill, the player's next monster selection moves it, a deselect clears it, and turning +// the setting off releases it). // ============================================================================ using System; @@ -26,6 +31,8 @@ public partial class CombatManager private int _forcedTargetId; // Pump-thread state: when the current forced target was first and last seen. private int _forcedSeenFor; + private int _forcedSetSeq; // bumped on every lock (any thread); the pump compares _forcedSeenSeq + private int _forcedSeenSeq; private DateTime _forcedSince = DateTime.MinValue; private DateTime _forcedLastInScan = DateTime.MinValue; @@ -45,11 +52,21 @@ public partial class CombatManager return null; } - /// Locks combat onto (checked with first). - internal void SetForcedTarget(int id) => Volatile.Write(ref _forcedTargetId, id); + /// Locks combat onto (checked with first). + /// A /ra targetlock lock: the player's later selections don't move it. + internal void SetForcedTarget(int id) + { + _forcedBySelection = false; + Interlocked.Increment(ref _forcedSetSeq); + Volatile.Write(ref _forcedTargetId, id); + } /// Ends the target lock (the monster stays the fight target until normal selection moves on). - internal void ClearForcedTarget() => Volatile.Write(ref _forcedTargetId, 0); + internal void ClearForcedTarget() + { + Volatile.Write(ref _forcedTargetId, 0); + _forcedBySelection = false; + } /// /// HandleCombatTrigger, before the normal selection: true when the forced target holds the @@ -60,18 +77,34 @@ public partial class CombatManager int fid = ForcedTargetId; if (fid == 0) return false; DateTime now = TargetClock(); - if (_forcedSeenFor != fid) + bool bySelection = _forcedBySelection; + int seq = Volatile.Read(ref _forcedSetSeq); + // A new lock, or the same monster locked again (selected, deselected, selected): its clock restarts. + if (_forcedSeenFor != fid || _forcedSeenSeq != seq) { _forcedSeenFor = fid; - _forcedSince = now; + _forcedSeenSeq = seq; + // A selected monster's 30 s count from the click, not from the first tick that saw it. + DateTime selectedAt = SelectedAt; + _forcedSince = bySelection && selectedAt != DateTime.MinValue ? selectedAt : now; _forcedLastInScan = DateTime.MinValue; } - string? end = ForcedTargetEnded(fid, now); + string? end = bySelection && !_settings.FightSelectedTarget ? SelectedSettingOff + : ForcedTargetEnded(fid, now); if (end != null) { + // _forcedBySelection is left as is: every lock sets it before its id, and with the id 0 it means nothing. Interlocked.CompareExchange(ref _forcedTargetId, 0, fid); string name = _worldFilter[fid]?.Name ?? $"0x{(uint)fid:X8}"; + if (bySelection) + { + _host.Log($"[CombatTarget] fight-selected: 0x{(uint)fid:X8} '{name}' ended: {end}"); + // The kill is the normal end (and the setting off was the player's own doing): no chat line. + if (end is not ("killed" or "it died" or SelectedSettingOff)) + _host.WriteToChat($"[RynthAi] Stopped fighting the monster you selected ({name}): {end}.", 1); + return false; + } _host.Log($"[CombatTarget] target lock on 0x{(uint)fid:X8} '{name}' ended: {end}"); _host.WriteToChat($"[RynthAi] Target lock on {name} ended: {end}.", 1); return false; @@ -90,8 +123,12 @@ public partial class CombatManager _lockedLastSeenInScan = now; return true; } - LockTarget(c, priority, $"target lock: picked by the player, {DescribeTargetPos(fid)}", - _lockedTargetId != 0 ? "target lock" : null); + if (bySelection) + LockTarget(c, priority, $"fight the monster I select: selected by the player, {DescribeTargetPos(fid)}", + _lockedTargetId != 0 ? "the player selected another monster" : null); + else + LockTarget(c, priority, $"target lock: picked by the player, {DescribeTargetPos(fid)}", + _lockedTargetId != 0 ? "target lock" : null); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 12506a7..1672527 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -620,6 +620,8 @@ public partial class CombatManager : IDisposable // or the suppression ends and the scan has it again, it counts for HasTargets, // HasCloseThreat (so HasEngageableTarget: combat keeps the tick, no corpse is claimed, no // starved loot turn) and the idle peace-mode swap. id -> when it was swapped off (TargetClock). + // A kill notice matched by name to a monster other than the fight target is held here the + // same way (SuppressGuessedDeath): the name can match the wrong one of a same-named pack. private readonly Dictionary _predictedDeathPending = new(); private readonly List _predictedDeathScratch = new(); @@ -706,6 +708,18 @@ public partial class CombatManager : IDisposable /// . Bounds the in-flight hold. private DateTime _lastAttackedAt = DateTime.MinValue; + /// The last offensive cast sent, at whom and when (TargetClock), before any judgement: + /// the in-flight hold's view of a cast that has just gone out. + private int _castSentTargetId; + private DateTime _castSentAt = DateTime.MinValue; + + /// An offensive cast went out at (internal for tests). + internal void NoteCastSent(int targetId) + { + _castSentTargetId = targetId; + _castSentAt = TargetClock(); + } + // Incumbent continuity across scan gaps. ScanNearbyTargets drops a target on // a single bad LOS result or a transient miss — the candidate list has been // observed oscillating 14<->17 entries tick to tick. Picking only from what is @@ -806,16 +820,23 @@ public partial class CombatManager : IDisposable bool over = (now - kv.Value).TotalMilliseconds > PREDICTED_SWAP_SUPPRESS_MS; if (alive && !over) continue; _predictedDeathScratch.Add(kv.Key); + bool guessed = _guessedDeaths.Contains(kv.Key); if (!alive) continue; // health 0 or the corpse: dead after all, nothing to say // Alive at the end of the window: lift the swap's suppression now, whatever RynthClock // says (TargetClock is that clock outside tests). A confirmed kill took the id out of // this map in OnKillNotification, so its longer suppression is never lifted here. _recentlyKilled.Remove(kv.Key); - _host.Log($"[RynthAi] Predicted kill of 0x{(uint)kv.Key:X8} '{_worldFilter[kv.Key]?.Name}' not confirmed " + - $"{(now - kv.Value).TotalSeconds:0.0} s after the swap and it is still alive: it is a target again."); + _host.Log(guessed + ? $"[RynthAi] Kill notice matched by name to 0x{(uint)kv.Key:X8} '{_worldFilter[kv.Key]?.Name}' not confirmed " + + $"{(now - kv.Value).TotalSeconds:0.0} s later and it is still alive: it is a target again." + : $"[RynthAi] Predicted kill of 0x{(uint)kv.Key:X8} '{_worldFilter[kv.Key]?.Name}' not confirmed " + + $"{(now - kv.Value).TotalSeconds:0.0} s after the swap and it is still alive: it is a target again."); } for (int i = 0; i < _predictedDeathScratch.Count; i++) + { _predictedDeathPending.Remove(_predictedDeathScratch[i]); + _guessedDeaths.Remove(_predictedDeathScratch[i]); + } } /// A predicted kill was hit after the swap (a damage line, which a killing blow never @@ -824,8 +845,12 @@ public partial class CombatManager : IDisposable { if (id == 0 || !_predictedDeathPending.Remove(id)) return; _recentlyKilled.Remove(id); - _host.Log($"[RynthAi] Predicted kill of 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' took a {amount}-point hit after the swap: " + - "it is alive, a target again."); + bool guessed = _guessedDeaths.Remove(id); + _host.Log(guessed + ? $"[RynthAi] Kill notice matched by name to 0x{(uint)id:X8} '{_worldFilter[id]?.Name}', but it took a {amount}-point hit: " + + "it is alive, a target again." + : $"[RynthAi] Predicted kill of 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' took a {amount}-point hit after the swap: " + + "it is alive, a target again."); } /// True only when actively attacking a specific target. Unlike HasTargets, this is false between kills even when more monsters are scanned nearby. @@ -1051,6 +1076,7 @@ public partial class CombatManager : IDisposable _scannedTargets.Clear(); _passedOver.Clear(); + _beyondRange.Clear(); _nearbyNoLos = 0; int scanTotal = 0, scanRing = 0; // D2 telemetry, published after the loop int playerId = (int)_playerId; @@ -1133,7 +1159,14 @@ public partial class CombatManager : IDisposable // Target lock (/ra targetlock): the player picked this one; the name list and // Priority 0 don't keep it out (attackable, alive and LOS still do). bool isForced = wo.Id != 0 && wo.Id == ForcedTargetId; - if (dist > (isEngaged || isForced ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue; + if (dist > (isEngaged || isForced ? Math.Max(maxDist, DisengageDistance) : maxDist)) + { + // Just past Monster Range: noted (no other reads here) so the fight can say when a + // higher-priority monster is left only because of the Monster Range setting. + if (!isEngaged && dist <= maxDist + PassedOverBeyondRangeM) + _beyondRange.Add(new PassedOverMonster { Id = wo.Id, Distance = dist, Why = "" }); + continue; + } // Left out below for a reason that can hide a monster worth fighting: noted for the // lock line's "passed over" (CombatManager.PassedOver.cs). In range, not the target. bool notePassed = !isEngaged && dist <= maxDist; @@ -1275,6 +1308,7 @@ public partial class CombatManager : IDisposable int id = (int)objectId; _recentlyKilled.Remove(id); _predictedDeathPending.Remove(id); // gone (died and despawned, or out of view): not a monster in range + _guessedDeaths.Remove(id); _hitAt.Remove(id); _blacklistManager.ForgetTarget(id); Ghosts.NoteDeleted(id); @@ -1699,12 +1733,26 @@ public partial class CombatManager : IDisposable if (string.IsNullOrEmpty(name)) return 0; PruneHits(now); int fight = _fightTargetId; - if (fight != 0 && !HitInVolley(fight, now) + // A swing or a shot hits the one monster it was aimed at, so in Melee and Missile mode + // every line naming the fight target is the fight target's. The volley rule below is for + // spells that hurt several monsters at once. Applied to melee, a dual-wield or multi-strike + // weapon's second hit (about 0.3 s after the first, inside the volley window) was handed + // to the nearest other monster of the same name: that monster was marked hurt and "hit by + // us", and the next kill notice was matched to it. It was kept out of the scan for 4 s + // while it was alive and fighting, so the bot looted mid-fight or turned to lesser + // monsters (2026-11-01, a same-named pack). + bool singleTarget = IsSingleTargetMode(); + if (fight != 0 && (singleTarget || !HitInVolley(fight, now)) && string.Equals(_worldFilter[fight]?.Name, name, StringComparison.OrdinalIgnoreCase)) { _hitAt[fight] = now; return fight; } + // Between fights (the target just died) a melee or missile line naming the last fight's + // monster is that fight's last hit, not a neighbour's. + if (singleTarget && fight == 0 && _lastFightName.Length > 0 + && string.Equals(_lastFightName, name, StringComparison.OrdinalIgnoreCase)) + return 0; int anchor = fight != 0 ? fight : unchecked((int)_playerId); int best = 0, any = 0; @@ -1727,6 +1775,13 @@ public partial class CombatManager : IDisposable private bool HitInVolley(int id, DateTime now) => _hitAt.TryGetValue(id, out DateTime t) && (now - t).TotalMilliseconds <= VolleyWindowMs; + /// Melee or Missile mode: each attack hits only the monster it was aimed at. + private bool IsSingleTargetMode() + { + int mode = CurrentCombatMode; + return mode == CombatMode.Melee || mode == CombatMode.Missile; + } + private readonly List _hitPruneScratch = new(); private void PruneHits(DateTime now) { @@ -2598,6 +2653,7 @@ public partial class CombatManager : IDisposable ForgetScanned(swapId); _predictedSwapAt[swapId] = TargetClock(); // fought again later = it didn't die (PredictionFailed) _predictedDeathPending[swapId] = TargetClock(); // still a monster in range until its death is confirmed + _guessedDeaths.Remove(swapId); // Queue this predicted one-shot so it's CREDITED when its death confirms — // we may swap away before its KillerNotification. Capture the name LIVE // from the world filter (_fightTargetName is often empty this early). @@ -2647,6 +2703,18 @@ public partial class CombatManager : IDisposable DateTime nowKill = RynthClock.Now; _predictedKillPending.RemoveAll(p => p.Expiry < nowKill); + // One death, two notices: the second is an echo of the first (no kill, nobody hidden). + if (IsKillEcho(deathMessage, nowKill)) + { + if (_killDbgCount < 1000) + { + _killDbgCount++; + _host.Log($"[KillDbg] how=echo of 0x{(uint)_lastConfirmedKillId:X8} " + + $"(+{(nowKill - _lastConfirmedKillAt).TotalMilliseconds:0} ms) msg='{deathMessage}'"); + } + return; + } + bool recorded = false; string how = "miss"; int pendingKillId = 0; // id of the predicted one-shot this notice was credited to (tier 1) @@ -2682,7 +2750,11 @@ public partial class CombatManager : IDisposable // pending until its own health, corpse or window says. if (pendingKillId != 0 && !(curMatches && tid != pendingKillId) && _predictedDeathPending.Remove(pendingKillId)) + { + _guessedDeaths.Remove(pendingKillId); _recentlyKilled[pendingKillId] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS); + NoteConfirmedKill(pendingKillId, nowKill); + } // (2) The current target died (its name is in the message). if (!recorded && curMatches && _fightTargetWcid != 0 && _fightCastCount > 0) @@ -2783,11 +2855,12 @@ public partial class CombatManager : IDisposable : "it hasn't been attacked yet") + " — keeping the target"); if (noticeForNeighbour) - _recentlyKilled[otherVictim] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS); + SuppressGuessedDeath(otherVictim, nowKill); } else if (tid != 0 && curMatches) { _recentlyKilled[tid] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS); + NoteConfirmedKill(tid, nowKill); ForgetScanned(tid); DropTarget("killed (KillerNotification)"); } @@ -2797,10 +2870,99 @@ public partial class CombatManager : IDisposable // Keep the scan off it while its corpse forms. int victim = FindRecentlyHitVictim(deathMessage, tid, nowKill); if (victim != 0) - _recentlyKilled[victim] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS); + SuppressGuessedDeath(victim, nowKill); } } + // ── Kill notices that name no one for sure ─────────────────────────────── + // The notice carries only the monster's name. For the fight target that is enough (it is the + // monster we were hitting); for any other monster it is a guess by name among those we hit + // lately, and in a same-named pack the guess can be wrong. + // + // 2026-11-01 (DreamWeave, a melee character, a pack of same-named monsters): some kills + // brought two KillerNotifications 1-2 ms apart with different wording ("You killed X!" and + // "X suffers a frozen fate!") and one corpse. The second was matched by name to a live + // neighbour, which was kept out of the scan for 4 s: with no other monster scanned, combat + // let the tick go and the bot opened a corpse with that monster 3 m away hitting it, then + // locked it again 4 s later. If the neighbour had been the top-priority monster, lesser ones + // would have been fought instead. + // + // Now: a second notice for the same monster right after a confirmed kill is an echo, and a + // death credited by guess keeps the monster counted as a monster in range (no looting, no + // peace mode) until the server confirms it (corpse, deleted, health 0), for at most + // PREDICTED_SWAP_SUPPRESS_MS, the way a predicted kill does; a damage line on it ends that. + + /// How soon after a confirmed kill a notice naming the same monster is its echo. + internal const double KillEchoMs = 300; + + private int _lastConfirmedKillId; + private string _lastConfirmedKillName = ""; + private DateTime _lastConfirmedKillAt = DateTime.MinValue; + // Ids in _predictedDeathPending whose death came from a kill notice matched by name (not a + // predicted kill-shot swap): for the log's wording only. + private readonly HashSet _guessedDeaths = new(); + + private void NoteConfirmedKill(int id, DateTime now) + { + _lastConfirmedKillId = id; + _lastConfirmedKillName = _worldFilter[id]?.Name ?? ""; + _lastConfirmedKillAt = now; + } + + /// + /// True when repeats the death confirmed just before: it names + /// that monster, came within , and no other monster of that name could + /// have died (none hit lately, no attack on its way at a same-named target, no predicted kill + /// of that name pending). + /// + private bool IsKillEcho(string deathMessage, DateTime now) + { + if (_lastConfirmedKillId == 0 || _lastConfirmedKillName.Length == 0) return false; + if ((now - _lastConfirmedKillAt).TotalMilliseconds > KillEchoMs) return false; + if (deathMessage.IndexOf(_lastConfirmedKillName, StringComparison.OrdinalIgnoreCase) < 0) return false; + for (int i = 0; i < _predictedKillPending.Count; i++) + if (!string.IsNullOrEmpty(_predictedKillPending[i].Name) + && deathMessage.IndexOf(_predictedKillPending[i].Name, StringComparison.OrdinalIgnoreCase) >= 0) + return false; + int tid = activeTargetId; + if (tid != 0 && tid != _lastConfirmedKillId && _pendingOffensiveTargetId == tid + && string.Equals(_worldFilter[tid]?.Name, _lastConfirmedKillName, StringComparison.OrdinalIgnoreCase)) + return false; + return FindRecentlyHitVictim(deathMessage, _lastConfirmedKillId, now) == 0; + } + + /// + /// A death credited by name to a monster that isn't the fight target: off the scan for the + /// predicted window, but still a monster in range for the fight and loot gates until its death + /// is confirmed (see ). + /// + private void SuppressGuessedDeath(int id, DateTime nowKill) + { + _recentlyKilled[id] = nowKill.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS); + _predictedDeathPending[id] = TargetClock(); + _guessedDeaths.Add(id); + } + + /// The highest Priority among guessed deaths still pending and alive within + /// , or int.MinValue when there is none. + private int TopGuessedDeathPriority(double range) + { + if (_guessedDeaths.Count == 0) return int.MinValue; + DateTime now = TargetClock(); + int me = unchecked((int)_playerId); + int top = int.MinValue; + foreach (int id in _guessedDeaths) + { + if (!_predictedDeathPending.TryGetValue(id, out DateTime at) + || (now - at).TotalMilliseconds > PREDICTED_SWAP_SUPPRESS_MS) continue; + if (!IsLiveMonster(id)) continue; + if (me == 0 || _worldFilter.Distance(me, id) > range) continue; + int p = PriorityOf(id); + if (p > top) top = p; + } + return top; + } + /// Test seam: engage as the fight target, as a target lock does. internal void EngageForTest(int targetId) { @@ -4513,6 +4675,11 @@ public partial class CombatManager : IDisposable if (p > topAnyRange) topAnyRange = p; if (c.Distance <= acquireRange && p > topPriority) topPriority = p; } + // A monster whose kill notice was matched to it by name only (SuppressGuessedDeath) is off + // the scan for a moment but may be alive: its tier still stands, so a lesser monster + // isn't locked in the meantime (with nothing of that tier to pick, no lock this tick). + int guessedTop = TopGuessedDeathPriority(acquireRange); + if (guessedTop > topPriority) topPriority = guessedTop; bool anyInRange = topPriority != int.MinValue; if (!anyInRange) topPriority = topAnyRange; @@ -4572,6 +4739,12 @@ public partial class CombatManager : IDisposable // Target Lock off: switch only to a clearly better one, and never with an attack // at the incumbent still on its way. + // Not while the incumbent is out of this tick's scan (inside the scan grace): its + // values are the last ones seen, and judging fresh candidates against them switched + // away from a monster closing in. R-20261031-201214-8be7: a Brier Wasp Swarm last + // scanned at 4.3 m, live at 1.9 m, lost to a wasp at 2.4 m as "clearly better", + // 124 ms after a bolt went out at it. + if (incInScan == null) return; double incKey = SchemeKey(scheme, inc); if (incKey - bestKey < SchemeMargin(scheme)) return; if (AttackInFlightAtLocked(now)) return; @@ -4710,10 +4883,16 @@ public partial class CombatManager : IDisposable /// private bool AttackInFlightAtLocked(DateTime now) { - if (_lockedTargetId == 0 || _lastAttackedTargetId != _lockedTargetId || _lastAttackedAt == DateTime.MinValue) - return false; - if ((now - _lastAttackedAt).TotalMilliseconds > CastCommitmentWindowMs) return false; - if (_lastDamageDealtAt != DateTime.MinValue && _lastDamageDealtAt >= _lastAttackedAt) return false; // it landed + if (_lockedTargetId == 0) return false; + // The last attack at it: a judged one (RecordOffensiveCast), or a cast just sent. A cast + // is judged only after its refusal window, so for its first half second or more the hold + // didn't know it had gone out, and a switch walked away from the bolt in the air + // (R-20261031-201214-8be7: the switch came 124 ms after the cast). + DateTime sent = _lastAttackedTargetId == _lockedTargetId ? _lastAttackedAt : DateTime.MinValue; + if (_castSentTargetId == _lockedTargetId && _castSentAt > sent) sent = _castSentAt; + if (sent == DateTime.MinValue) return false; + if ((now - sent).TotalMilliseconds > CastCommitmentWindowMs) return false; + if (_lastDamageDealtAt != DateTime.MinValue && _lastDamageDealtAt >= sent) return false; // it landed DateTime progress = _lastDamageDealtAt != DateTime.MinValue ? _lastDamageDealtAt : _targetLockedAt; return progress != DateTime.MinValue && (now - progress).TotalMilliseconds <= UndamagedCommitmentMaxMs; } @@ -6946,7 +7125,8 @@ public partial class CombatManager : IDisposable // Called each attack cycle — the client handles turn-to-face naturally. if (_settings.UseNativeAttack && _host.HasNativeAttack) { - _host.SelectItem(targetId); + // Marked as RynthAi's own pick: "Fight the monster I select" follows the player's only. + ItemInfo.SelfSelect.SelectAsBot(_host, targetId); _host.NativeAttack(acHeight, power); } // Direct attack: raw game action (bypasses client facing) @@ -7197,6 +7377,7 @@ public partial class CombatManager : IDisposable _pendingOffensiveSpellId = offensiveSpellId; _pendingOffensiveCastAt = RynthClock.Now; _pendingOffensiveTargetId = activeTargetId; + NoteCastSent(activeTargetId); NoteOffensiveSeq(); // Environment-impact throttle: follow this cast's projectiles (rings and walls // don't fly at the target, so they aren't judged). diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index a28ece0..dbbe499 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -104,7 +104,9 @@ public sealed partial class RynthAiPlugin int capped = _corpseCappedIds.Count(id => !_corpseMatchedIds.Contains(id)); if (approved == 0 && capped == 0) return _corpseItemsEvaluated > 0 - ? $"[RynthAi] Nothing {(chest ? "in" : "on")} {name} matches the loot profile." + ? (LootModes.IsRares(_dashboard?.Settings?.LootMode ?? LootModes.Profile) + ? $"[RynthAi] Nothing {(chest ? "in" : "on")} {name} is a rare or a needed mana stone (Loot Mode: rares)." + : $"[RynthAi] Nothing {(chest ? "in" : "on")} {name} matches the loot profile.") : $"[RynthAi] Nothing to loot on {name}."; if (approved == 0) return $"[RynthAi] Nothing to loot on {name}: {capped} item(s) match, but you already have enough."; @@ -161,11 +163,13 @@ public sealed partial class RynthAiPlugin private bool _currentLootItemAwaitingAnswer; // the last send has had no answer yet private long _currentLootItemRefusedAt; // when a refusal of the last send was first seen (0 = none) private uint _currentLootItemRefusalError; + private uint _currentLootItemRefusalObject; // the item the refusal named (0: none, a quest refusal) private bool _currentLootItemRefusalBusy; // "too busy": before its pickup could run, not the pack's answer private int _currentLootItemDestRefusals; // tries into _currentLootItemDest refused after the pickup ran private int _currentLootItemDestTimeouts; // tries into it with no answer in PickupAnswerWaitMs private bool _currentLootItemTimedOut; // a send of this item went unanswered: a later answer may be to it private readonly List _currentLootItemDestsTried = new(); + private readonly List _currentLootItemFullPacks = new(); // packs this item's refusals marked full private long _moveAwaitTickAt; // CorpseNowMs of the previous answer-wait call // How long the server took to answer recent pickups (confirmations and refusals after the // pickup ran): the answer wait is sized from the slowest of them. @@ -1750,7 +1754,10 @@ public sealed partial class RynthAiPlugin if (!_lootEvalLogged.TryGetValue(item.Id, out string? loggedVerdict) || loggedVerdict != verdict) { _lootEvalLogged[item.Id] = verdict; - LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} id=0x{(uint)item.Id:X8} value={item.Values(19, 0)} stack={item.Values(12, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " + verdict); + // A left item that a rule switched off in the profile would take says so: the log + // of a "loot misses my wands" report then shows the rule (once per item per open). + string offNote = !classified && !noUst && hasAppraisalData ? SwitchedOffNote(item, settings) : string.Empty; + LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} id=0x{(uint)item.Id:X8} value={item.Values(19, 0)} stack={item.Values(12, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " + verdict + offNote); } if (classified) @@ -1826,17 +1833,19 @@ public sealed partial class RynthAiPlugin Host.SelectItem(unchecked((uint)firstMatchId)); LootDiag($"[RynthAi] {LootTag}: picking up 0x{(uint)firstMatchId:X8} '{matchItemName}' from corpse 0x{(uint)corpseId:X8}."); - // Jump-loot: jump before the move to cancel the pickup animation. - // Only jump when multiple items remain (single-item: no animation worth cancelling). - // Guards: needs both hooks, stamina > 5 to cover the cost. - int remainingItems = visibleItemCount - _processedCorpseItems.Count; - bool useJumpLoot = settings.LootJumpEnabled - && Host.HasJumpNonAutonomous - && Host.HasMoveItemExternal - && _vitals.CurrentStamina > 5; - - if (useJumpLoot && remainingItems > 1 && !pipelined) - Host.JumpNonAutonomous(Math.Clamp(settings.LootJumpHeight / 100f, 0.01f, 1f)); + // Jump-loot: jump, then the move while the character is still in the air, so the server + // skips the pickup bend-down (on ACE the pickup reads IsJumping in Player_Inventory's + // GetPickupMotion, gated by the server setting allow_jump_loot, default true). The jump is + // the keyboard one (TapJump, 0xF61B Jump, which ACE handles); JumpNonAutonomous (0xF7C9) + // has no handler on ACE and did nothing. The + // jump goes FIRST: ACE's jump handler stops any walk-to in progress, so a jump after the + // move would cancel the pickup. Every pickup, a corpse's only match included (most + // corpses hold one match, so a multi-item gate meant jump-loot almost never ran), with + // stamina > 5 to cover the cost. Not for a pipelined move: it is already queued behind + // the last pickup's Return, and a jump there would only disturb that queue. The tap jump + // has a fixed height, so LootJumpHeight no longer has an effect. + if (!pipelined && ShouldJumpLoot(settings)) + Host.TapJump(); // Always a move into a pack, never a use: a use on a wearable corpse item is // get-and-wield, which put salvage jewellery on the character (2026-10-02). @@ -2013,9 +2022,10 @@ public sealed partial class RynthAiPlugin /// (it arrived while the last pickup's bend-down still ran) or InventoryServerSaveFailed /// naming the item. Someone else's refusal (a fizzle, a use) is not ours. /// - private bool CurrentPickupRefused(out uint error) + private bool CurrentPickupRefused(out uint error, out uint objectId) { error = 0; + objectId = 0; try { if (!Host.HasGetLastWeenieError || !Host.TryGetLastWeenieError(out int seq, out uint err, out uint evt, out uint obj)) @@ -2023,8 +2033,95 @@ public sealed partial class RynthAiPlugin if (seq == 0 || seq == _currentLootItemErrSeqAtSend) return false; error = err; + objectId = obj; return err == WeenieErrorYoureTooBusy - || (evt == EventInventoryServerSaveFailed && obj == unchecked((uint)_currentLootItemId)); + || (evt == EventInventoryServerSaveFailed + && (obj == unchecked((uint)_currentLootItemId) || (obj == 0 && IsQuestPickupRefusal(err)))); + } + catch { return false; } + } + + // ── Items the server won't hand over yet (2026-11-01, #rynth-issues "Stopped looting") ── + // Conquest treasure maps have pickup timers: "after it reaches its loot attempt limit on + // some obscure item with pickup timers ... it just selects another item in the container, + // but doesn't pick it up". ACE runs the pickup motion, then checks the item's quest stamp + // (Player.VerifyQuest) and, on a timer that has not run out, answers "You have solved this + // quest too recently!" with InventoryServerSaveFailed(object 0, YouHaveSolvedThisQuestTooRecently) + // (QuestManager.HandleSolveError) - naming no object. So RynthAi saw no answer at all, and + // AC's own pending-request slot was never emptied (only an answer naming the item does that: + // the engine's ClientActionGates), so the client dropped every move after it ("You can only + // move or use one item at a time") until the engine's watchdog emptied it 10 s later. An + // answer naming the item (ItemRequiresQuestToBePickedUp, or a timer refusal that does) was + // taken as the pack's answer: after 3 tries the pack counted as full for 5 min, then the next + // pack, until no pack was left and every later item was selected and never picked up. + // Now a quest refusal leaves the item at once (a retry is refused the same way for minutes or + // hours), blames no pack, and empties the client's slot when the answer named no object. + private const uint WeenieErrorQuestSolvedTooRecently = 0x043E; + private const uint WeenieErrorQuestSolvedTooManyTimes = 0x043F; + private const uint WeenieErrorItemRequiresQuest = 0x0445; + + /// The server's answer says the item itself can't be picked up (yet), whatever pack it goes to. + internal static bool IsQuestPickupRefusal(uint error) => + error is WeenieErrorQuestSolvedTooRecently or WeenieErrorQuestSolvedTooManyTimes or WeenieErrorItemRequiresQuest; + + private static string QuestPickupRefusalText(uint error) => error switch + { + WeenieErrorQuestSolvedTooRecently => "its pickup timer has not run out (\"solved this quest too recently\")", + WeenieErrorQuestSolvedTooManyTimes => "it can't be picked up again (\"solved this quest too many times\")", + WeenieErrorItemRequiresQuest => "it needs a quest flag to be picked up", + _ => $"error 0x{error:X}", + }; + + /// + /// A quest refusal that named no object leaves AC's pending inventory request in place (the + /// client empties it only for an answer about that object). The server has answered, so the + /// slot is emptied now, as AC's RecordResponse would have, rather than after the engine's 10 s + /// watchdog: until then the client drops every move, and the next item's pickup with it. + /// + private void EmptyClientRequestAfterAnonymousRefusal(uint objectId) + { + if (objectId == 0 && Host.HasInvokeChatParser) + Host.InvokeChatParser("/rc unlockactions"); + } + + /// + /// The current item was refused for itself (): left at once, + /// no pack blamed, and the next item goes out as soon as the character is still. + /// + private void LeaveQuestRefusedLootItem(long now) + { + uint err = _currentLootItemRefusalError; + long after = _currentLootItemRefusedAt - _currentLootItemMoveRequestedAt; + string name = string.IsNullOrEmpty(_currentLootItemName) ? $"0x{(uint)_currentLootItemId:X8}" : _currentLootItemName; + LootDiag($"[RynthAi] {LootTag}: the server won't hand over 0x{(uint)_currentLootItemId:X8} '{_currentLootItemName}': {QuestPickupRefusalText(err)} " + + $"(error 0x{err:X}, object 0x{_currentLootItemRefusalObject:X8}, {after} ms after the send, try {Math.Max(1, _currentLootItemMoveAttempts)}); leaving it, no pack is to blame."); + ChatLine($"[RynthAi] Can't loot {name} - {QuestPickupRefusalText(err)}; leaving it."); + EmptyClientRequestAfterAnonymousRefusal(_currentLootItemRefusalObject); + _processedCorpseItems.Add(_currentLootItemId); + _currentLootItemDestsTried.Clear(); // nothing is at the server: no late landing to watch for + ResetCurrentLootItem(); + _lastLootActionAt = now; + } + + /// + /// A quest refusal () for came since + /// the refusal counter read (the ground looter's check). + /// + private bool QuestPickupRefusedSince(int seqAtSend, int itemId, out uint error, out uint objectId) + { + error = 0; + objectId = 0; + try + { + if (!Host.HasGetLastWeenieError || !Host.TryGetLastWeenieError(out int seq, out uint err, out uint evt, out uint obj)) + return false; + if (seq == 0 || seq == seqAtSend || evt != EventInventoryServerSaveFailed || !IsQuestPickupRefusal(err)) + return false; + if (obj != 0 && obj != unchecked((uint)itemId)) + return false; + error = err; + objectId = obj; + return true; } catch { return false; } } @@ -2078,6 +2175,7 @@ public sealed partial class RynthAiPlugin _currentLootItemAwaitingAnswer = true; _currentLootItemRefusedAt = 0; _currentLootItemRefusalError = 0; + _currentLootItemRefusalObject = 0; _currentLootItemRefusalBusy = false; } @@ -2094,12 +2192,14 @@ public sealed partial class RynthAiPlugin /// private void PollCurrentPickupRefusal(long now) { - if (_currentLootItemRefusedAt != 0 || !CurrentPickupRefused(out uint err)) + if (_currentLootItemRefusedAt != 0 || !CurrentPickupRefused(out uint err, out uint obj)) return; long after = now - _currentLootItemMoveRequestedAt; _currentLootItemRefusedAt = now; _currentLootItemRefusalError = err; - _currentLootItemRefusalBusy = err == WeenieErrorYoureTooBusy || after < PickupAnswerMinMs; + _currentLootItemRefusalObject = obj; + // A quest refusal is never "too busy", however soon it comes (2026-11-01). + _currentLootItemRefusalBusy = !IsQuestPickupRefusal(err) && (err == WeenieErrorYoureTooBusy || after < PickupAnswerMinMs); if (!_currentLootItemRefusalBusy && !_currentLootItemTimedOut) NotePickupAnswerLatency(after); } @@ -2249,6 +2349,14 @@ public sealed partial class RynthAiPlugin /// A gap between two held calls longer than this was not one continuous hold (the corpse clock is not paid back for it). internal const long PickupHoldMaxGapMs = 500; + /// Jump-loot for this pickup: the setting, the keyboard jump and the move call, stamina for + /// the jump. + private bool ShouldJumpLoot(LegacyUiSettings settings) => + settings.LootJumpEnabled + && Host.HasTapJump + && Host.HasMoveItemExternal + && _vitals.CurrentStamina > 5; + /// /// True while the server owes an answer to a cast or use (ActionPacer): ACE refuses a pickup /// then (Player.HandleActionPutItemInContainer_Verify: IsBusy -> YoureTooBusy and @@ -2361,6 +2469,14 @@ public sealed partial class RynthAiPlugin bool refused = _currentLootItemRefusedAt != 0; bool busyRefusal = refused && _currentLootItemRefusalBusy; + // Refused for the item itself (a pickup timer, a quest flag): no try into any pack will + // do better, so it is left now, with no pack blamed (2026-11-01, #rynth-issues "Stopped looting"). + if (refused && IsQuestPickupRefusal(_currentLootItemRefusalError)) + { + LeaveQuestRefusedLootItem(now); + return; + } + // Item still on corpse — wait before retrying the UseObject. The window counts from // when the character is still: while a pickup animation plays the engine holds the // move, and a retry timed from the send gave up on items whose move had not gone @@ -2405,11 +2521,17 @@ public sealed partial class RynthAiPlugin _currentLootItemTimedOut = true; lastTry = $"no answer in {answerMs} ms"; } - else if (!busyRefusal) + else if (!busyRefusal && _currentLootItemRefusalError == 0) { _currentLootItemDestRefusals++; lastTry = $"refused {answerMs} ms after the send, after its pickup ran (error 0x{_currentLootItemRefusalError:X})"; } + else if (!busyRefusal) + { + // ACE's answer for want of room carries no error code ("Unable to put X into + // container"); one with a code is about the item, not the pack (2026-11-01). + lastTry = $"refused {answerMs} ms after the send, after its pickup ran, for the item (error 0x{_currentLootItemRefusalError:X}), not the pack"; + } else lastTry = $"too busy, {answerMs} ms after the send"; } @@ -2427,7 +2549,8 @@ public sealed partial class RynthAiPlugin int dest = _currentLootItemDest; if (dest != 0 && JudgeLootDest(out bool confirmed)) { - _packRefusals.Refuse(dest, now, confirmed); + _packRefusals.Refuse(dest, now, confirmed, _currentLootItemId); + if (confirmed && !_currentLootItemFullPacks.Contains(dest)) _currentLootItemFullPacks.Add(dest); if (!_currentLootItemPackRetried && (confirmed || HasOtherLootDestination())) { LootDiag(confirmed @@ -2444,6 +2567,17 @@ public sealed partial class RynthAiPlugin } LootDiag($"[RynthAi] {LootTag}: pickup failed for 0x{(uint)_currentLootItemId:X8}; container remained 0x{(uint)_openedContainerId:X8} after {_currentLootItemMoveAttempts} attempt(s)" + (lastTry.Length > 0 ? $" (last: {lastTry})." : ".")); + // Refused for room in every pack it tried (two or more), and in none of them for + // another item: the server is refusing this item, not the packs (a pickup timer that + // says no more than a full pack does, 2026-11-01). Its marks go with it, or the next + // item finds no pack and is selected and never picked up. + if (_currentLootItemFullPacks.Count >= 2) + { + List back = _packRefusals.Withdraw(_currentLootItemId, now); + if (back.Count > 0) + LootDiag($"[RynthAi] {LootTag}: the server refused 0x{(uint)_currentLootItemId:X8} in {_currentLootItemFullPacks.Count} packs the client counts room in: it is refusing the item, not the packs; " + + $"{string.Join(" and ", back.Select(LootPackName))} {(back.Count == 1 ? "is" : "are")} no longer treated as full."); + } _processedCorpseItems.Add(_currentLootItemId); ResetCurrentLootItem(); _lastLootActionAt = now; @@ -2838,11 +2972,12 @@ public sealed partial class RynthAiPlugin } /// Boost Loot Priority is on and a corpse could be looted now (not with rare-only looting, - /// where most kills leave nothing to wait for). + /// where most kills leave nothing to wait for: LootOnlyRareCorpses, or Loot Mode rares). private bool BoostLootCanRun(LegacyUiSettings settings) => settings.BoostLootPriority && settings.IsMacroRunning && settings.EnableLooting && !BoostNavHoldsLoot(settings) && !settings.LootOnlyRareCorpses + && !LootModes.IsRares(settings.LootMode) && !IsLootingBlockedByPack(settings) && !_useRefusals.HoldsOpens(CorpseNowMs); @@ -2948,6 +3083,11 @@ public sealed partial class RynthAiPlugin ruleLabel = string.Empty; builtIn = string.Empty; + // Loot Mode "Rares and needed mana stones only": the loot profile and the other built-in + // keeps are not used (ClassifyRaresMode). + if (LootModes.IsRares(settings.LootMode)) + return ClassifyRaresMode(item, settings, preview, out actionLabel, out ruleLabel, out builtIn); + // Learn unknown spells (VTank ReadUnknownScrolls): a built-in rule ahead of the loot // profile, as in VTank. A scroll of a spell we don't know and can learn is looted to read. if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule, out string learnWhy, preview)) @@ -2966,86 +3106,7 @@ public sealed partial class RynthAiPlugin bool isConfiguredManaStone = _manaStoneManager?.IsManaStone(item) == true; if (isConfiguredManaStone) - { - // Count stones already in the pack against the KeepCount cap, using - // the SAME IsManaStone predicate as the loot gate above — if these - // diverged the cap would silently stop working (e.g. gate loots by - // ObjectClass but tally counts by name → tally stays 0 → over-loot). - // GetDirectInventory(forceRefresh:true) actively walks the player's - // containers via Host.GetContainerContents, so it's immune to the - // cache-classification race that bites AllKnownObjects() right after - // RL/login. IsManaStone's name fallback also keys on Name (always - // present), so the tally is reliable even before ITEM_TYPE lands. - // One walk per pass, not one per stone: a chest with 9 stones walked the whole - // inventory 9 times in the same tick (ManaStoneLiveCountMs). - long nowMs = CorpseNowMs; - int liveCount; - if (_manaStoneLiveCountAt != 0 && nowMs - _manaStoneLiveCountAt < ManaStoneLiveCountMs) - liveCount = _manaStoneLiveCount; - else - { - liveCount = 0; - if (_objectCache != null) - { - foreach (var inv in _objectCache.GetDirectInventory(forceRefresh: true)) - { - if (string.IsNullOrEmpty(inv.Name)) continue; - if (_manaStoneManager?.IsManaStone(inv) == true) - liveCount++; - } - } - _manaStoneLiveCount = liveCount; - _manaStoneLiveCountAt = nowMs; - } - - // Include stones already approved this session whose CreateObject event - // hasn't landed yet. Distinct ids only — same item re-evaluated across - // ticks must not bump the count. - int pendingNotYetCounted = 0; - foreach (int id in _pendingManaStoneIds) - { - if (id == item.Id) continue; // current item handled below - pendingNotYetCounted++; - } - int haveCount = liveCount + pendingNotYetCounted; - - // One-time-per-corpse log so we can see what the count was based on (it was printed - // for every stone while none was approved: 9 lines a chest at the cap). - if (!preview && _pendingManaStoneIds.Count == 0 && _manaStoneCapLoggedFor != _openedContainerId) - { - _manaStoneCapLoggedFor = _openedContainerId; - Host.Log($"[RynthAi] ManaStone count for cap check: live={liveCount} pending={pendingNotYetCounted} cap={settings.ManaStoneKeepCount} (cache_known={_objectCache?.AllKnownObjects().Count() ?? 0})"); - } - - // If this specific stone is already approved, return the same answer - // we returned last time (no further log spam, no count change). - string stoneWhy = $"a mana stone, {haveCount} of {settings.ManaStoneKeepCount} kept - change in the Items panel, Mana Stone Tapping (Keep count)"; - if (_pendingManaStoneIds.Contains(item.Id)) - { - actionLabel = "Keep"; - ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})"; - builtIn = stoneWhy; - return true; - } - - if (haveCount < settings.ManaStoneKeepCount) - { - actionLabel = "Keep"; - ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})"; - builtIn = stoneWhy; - if (preview) return true; - ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}, +1) — looting."); - _pendingManaStoneIds.Add(item.Id); - return true; - } - - if (!preview) - { - _corpseCappedIds.Add(item.Id); - ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving."); - } - return false; - } + return ClassifyManaStoneKeep(item, settings, preview, raresMode: false, out actionLabel, out ruleLabel, out builtIn); if (TryLoadNativeLootProfile(out LootProfile nativeProfile, out _)) { @@ -3112,6 +3173,166 @@ public sealed partial class RynthAiPlugin return true; } + /// + /// For the [LootEval] line of an identified item the looter leaves: " (switched-off rule #N + /// 'name' [Keep] would take it)" when a Keep or Keep # rule that's off in the VTank profile, + /// above any rule that matched (a Keep # at its count), would take the item; else empty + /// (switched-off Salvage rules aren't named here: LootSnob ships them all off). Rares mode and + /// RynthAi's own (.json) profiles have no such rules. Costs one more pass over the profile, + /// only for a left item's first log line on an open. + /// + private string SwitchedOffNote(WorldObject item, LegacyUiSettings settings) + { + try + { + if (LootModes.IsRares(settings.LootMode)) return string.Empty; + if (TryLoadNativeLootProfile(out _, out _)) return string.Empty; + if (!TryLoadLootProfile(string.Empty, out VTankLootProfile profile, out _)) return string.Empty; + VTankLootContext ctx = new(Host, _playerId) { Cache = _objectCache }; + VTankLootEvaluator.FirstMatch(profile, item, ctx, out int matched); + int off = VTankLootEvaluator.FirstSwitchedOffMatch(profile, item, ctx, matched, keepsOnly: true); + return off < 0 ? string.Empty + : $" (switched-off rule #{off + 1} '{Loot.LootWhy.NameOf(profile.Rules[off], off)}' [{profile.Rules[off].Action}] would take it)"; + } + catch { return string.Empty; } + } + + /// + /// The built-in mana stone keep: a stone (ManaStoneManager.IsManaStone) is taken while the pack + /// holds fewer than the Items panel's keep count (Mana Stone Tapping, Keep count), counting + /// stones approved on this corpse that haven't reached the pack yet; at the count it is left. + /// Profile mode runs it ahead of the loot profile; rares mode () + /// runs the same count, with its own rule label and reason. + /// + private bool ClassifyManaStoneKeep(WorldObject item, LegacyUiSettings settings, bool preview, bool raresMode, + out string actionLabel, out string ruleLabel, out string builtIn) + { + actionLabel = string.Empty; + ruleLabel = string.Empty; + builtIn = string.Empty; + + // Count stones already in the pack against the KeepCount cap, using + // the SAME IsManaStone predicate as the loot gate above — if these + // diverged the cap would silently stop working (e.g. gate loots by + // ObjectClass but tally counts by name → tally stays 0 → over-loot). + // GetDirectInventory(forceRefresh:true) actively walks the player's + // containers via Host.GetContainerContents, so it's immune to the + // cache-classification race that bites AllKnownObjects() right after + // RL/login. IsManaStone's name fallback also keys on Name (always + // present), so the tally is reliable even before ITEM_TYPE lands. + // One walk per pass, not one per stone: a chest with 9 stones walked the whole + // inventory 9 times in the same tick (ManaStoneLiveCountMs). + long nowMs = CorpseNowMs; + int liveCount; + if (_manaStoneLiveCountAt != 0 && nowMs - _manaStoneLiveCountAt < ManaStoneLiveCountMs) + liveCount = _manaStoneLiveCount; + else + { + liveCount = 0; + if (_objectCache != null) + { + foreach (var inv in _objectCache.GetDirectInventory(forceRefresh: true)) + { + if (string.IsNullOrEmpty(inv.Name)) continue; + if (_manaStoneManager?.IsManaStone(inv) == true) + liveCount++; + } + } + _manaStoneLiveCount = liveCount; + _manaStoneLiveCountAt = nowMs; + } + + // Include stones already approved this session whose CreateObject event + // hasn't landed yet. Distinct ids only — same item re-evaluated across + // ticks must not bump the count. + int pendingNotYetCounted = 0; + foreach (int id in _pendingManaStoneIds) + { + if (id == item.Id) continue; // current item handled below + pendingNotYetCounted++; + } + int haveCount = liveCount + pendingNotYetCounted; + + // One-time-per-corpse log so we can see what the count was based on (it was printed + // for every stone while none was approved: 9 lines a chest at the cap). + if (!preview && _pendingManaStoneIds.Count == 0 && _manaStoneCapLoggedFor != _openedContainerId) + { + _manaStoneCapLoggedFor = _openedContainerId; + Host.Log($"[RynthAi] ManaStone count for cap check: live={liveCount} pending={pendingNotYetCounted} cap={settings.ManaStoneKeepCount} (cache_known={_objectCache?.AllKnownObjects().Count() ?? 0})"); + } + + // If this specific stone is already approved, return the same answer + // we returned last time (no further log spam, no count change). + string stoneWhy = raresMode + ? $"a needed mana stone, {haveCount} of {settings.ManaStoneKeepCount} kept (Loot Mode: rares and needed mana stones only) - the keep count is in the Items panel, Mana Stone Tapping" + : $"a mana stone, {haveCount} of {settings.ManaStoneKeepCount} kept - change in the Items panel, Mana Stone Tapping (Keep count)"; + string stoneRule = raresMode ? LootModes.StoneRule : $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})"; + if (_pendingManaStoneIds.Contains(item.Id)) + { + actionLabel = "Keep"; + ruleLabel = stoneRule; + builtIn = stoneWhy; + return true; + } + + if (haveCount < settings.ManaStoneKeepCount) + { + actionLabel = "Keep"; + ruleLabel = stoneRule; + builtIn = stoneWhy; + if (preview) return true; + ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}, +1) — looting."); + _pendingManaStoneIds.Add(item.Id); + return true; + } + + // Rares mode: say why a stone is left (/ra loot why), as it has no rule to name. + if (raresMode) + builtIn = $"a mana stone, but {haveCount} of {settings.ManaStoneKeepCount} are kept already: not needed (Loot Mode: rares and needed mana stones only)"; + if (!preview) + { + _corpseCappedIds.Add(item.Id); + ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving."); + } + return false; + } + + /// + /// Loot Mode "Rares and needed mana stones only" (owner, 2026-10-31): the loot profile is not + /// used. A rare (RareItems: its rare icon, which the create message carries, or its RareId once + /// identified) is kept; a mana stone is kept exactly when the built-in mana stone keep wants it + /// (ClassifyManaStoneKeep: the same IsManaStone test and keep count); everything else is left, + /// built-in keeps included (Learn Unknown Spells, Mana Tap). Your own corpse is recovered by its + /// own path (TickOwnCorpseRecovery), which never comes here. + /// + private bool ClassifyRaresMode(WorldObject item, LegacyUiSettings settings, bool preview, + out string actionLabel, out string ruleLabel, out string builtIn) + { + actionLabel = string.Empty; + ruleLabel = string.Empty; + builtIn = string.Empty; + if (!preview) _corpseItemsEvaluated++; + + if (RareItems.IsRare(Host, item, out string how)) + { + actionLabel = "Keep"; + ruleLabel = LootModes.RareRule; + builtIn = $"a rare ({how}) (Loot Mode: rares and needed mana stones only) - change in Settings > Looting, Loot Mode"; + if (!preview) _corpseMatchedIds.Add(item.Id); + return true; + } + + if (_manaStoneManager?.IsManaStone(item) == true) + { + bool take = ClassifyManaStoneKeep(item, settings, preview, raresMode: true, out actionLabel, out ruleLabel, out builtIn); + if (take && !preview) _corpseMatchedIds.Add(item.Id); + return take; + } + + builtIn = "not a rare or a mana stone (Loot Mode: rares and needed mana stones only) - change in Settings > Looting, Loot Mode"; + return false; + } + private readonly HashSet _readNonScrollLogged = new(); /// @@ -3283,6 +3504,11 @@ public sealed partial class RynthAiPlugin // The ManaTap fallback (run when no rule matches) reads CurrentMana, which only // the appraisal carries, so with tapping on every item waits for its ID. var tapSettings = _dashboard?.Settings; + // Rares mode needs no ID: a rare shows by its rare icon (in the create message), a mana + // stone by its name, and Mana Tap is off there. (RareId, sent only with an ID, still + // counts for an item that has one.) + if (tapSettings != null && LootModes.IsRares(tapSettings.LootMode)) + return false; bool manaTapNeedsId = tapSettings != null && tapSettings.EnableManaTapping && tapSettings.ManaTapMinMana > 0 && _manaStoneManager != null; @@ -3455,11 +3681,13 @@ public sealed partial class RynthAiPlugin _currentLootItemAwaitingAnswer = false; _currentLootItemRefusedAt = 0; _currentLootItemRefusalError = 0; + _currentLootItemRefusalObject = 0; _currentLootItemRefusalBusy = false; _currentLootItemDestRefusals = 0; _currentLootItemDestTimeouts = 0; _currentLootItemTimedOut = false; _currentLootItemDestsTried.Clear(); + _currentLootItemFullPacks.Clear(); _moveAwaitTickAt = 0; _currentLootItemId = 0; _currentLootItemRequested = false; @@ -3593,7 +3821,7 @@ public sealed partial class RynthAiPlugin _lastOpenAttemptCorpseId = corpseId; StopCorpseMovement(); int seqBefore = watch ? Host.GetUseDoneSeq() : 0; - Host.SelectItem(unchecked((uint)corpseId)); + RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.SelectAsBot(Host, unchecked((uint)corpseId)); bool sent = Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse"); if (watch && sent) _useRefusals.OnOpenSent(corpseId, now, seqBefore); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs index e75eecf..73323b6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs @@ -69,8 +69,12 @@ internal interface IDashboardHost void AdjustOpacity(float delta); void ToggleLock(); void SelectProfile(int kind, int index); + /// The Loot Mode (Loot.LootModes): the loot profile, or rares and needed mana stones only. + void SetLootMode(int mode); /// RynthSort's auto-sort: -1 RynthSort not loaded (or not logged in, or too old to say), 0 off, 1 on. int AutoSort { get; } + /// Fight the monster I select (combat setting), for the options menu's toggle. + bool FightSelectedTarget { get; } void SetAutoSort(bool on); /// RynthSort's own window, shown or hidden. void ToggleSortWindow(); @@ -363,8 +367,9 @@ internal sealed unsafe class InstrumentDashboard dl.PopClipRect(); ImGui.SetCursorScreenPos(min); - ImGui.InvisibleButton("##activity", new Vector2(w, h)); - SafeImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + state); + // A click asks why it is doing that (or nothing): /ra why's diagnosis, in chat. + if (ImGui.InvisibleButton("##activity", new Vector2(w, h))) _d.Command("/ra why"); + SafeImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + state + "\nClick: why it's doing that, in chat (/ra why)."); return y + h; } @@ -488,7 +493,9 @@ internal sealed unsafe class InstrumentDashboard && ImGui.IsMouseReleased(ImGuiMouseButton.Left); bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right); bool hot = ImGui.IsItemHovered(); - SafeImGui.SetItemTooltip((on ? s.Name + " on. Click to turn it off." : s.Name + " off. Click to turn it on.") + "\nRight-click: " + s.Right + "."); + string mode = i == 3 && Loot.LootModes.IsRares(_r.LootMode) + ? "\nLoot Mode: rares and needed mana stones only (the loot profile is not used)." : ""; + SafeImGui.SetItemTooltip((on ? s.Name + " on. Click to turn it off." : s.Name + " off. Click to turn it on.") + mode + "\nRight-click: " + s.Right + "."); KeyFace(dl, s.Icon, on, hot, pos, size); if (clicked) _d.SetSubsystem(i, !on); if (right) SubsystemSettings(i); @@ -928,6 +935,30 @@ internal sealed unsafe class InstrumentDashboard ImGui.CloseCurrentPopup(); _d.Host.SetPanelPopOut(Title, RynthPanelPopOut.Toggle); } + // When the bot seems stuck: what it is waiting for, and the hourglass reset. + if (MenuItem(dl, ref p, w, "##m_why", RynthIcons.Info, "Why is it doing that?", "/ra why", + "A one-glance diagnosis in chat: why the bot is idle, or what it is attacking and why.")) + { + ImGui.CloseCurrentPopup(); + _d.Command("/ra why"); + } + // Fight the monster I select (also Settings > Ranges > Combat Targeting): a toggle, the + // command's reply says the new state. + bool fightSelected = _d.FightSelectedTarget; + if (MenuItem(dl, ref p, w, "##m_fightsel", RynthIcons.Crosshair, + "Fight the monster I select", fightSelected ? "ON" : "OFF", + "On: in a fight, a monster you select is fought first, until it dies, can't be reached,\n" + + "or you select another or deselect (/ra fightselected). Click to turn it " + (fightSelected ? "off." : "on."))) + { + ImGui.CloseCurrentPopup(); + _d.Command("/ra fightselected"); + } + if (MenuItem(dl, ref p, w, "##m_busy", RynthIcons.Hourglass, "Clear busy", "/ra clearbusy", + "The game thinks the character is still busy (the hourglass stays, nothing can be used): clear it.")) + { + ImGui.CloseCurrentPopup(); + _d.Command("/ra clearbusy"); + } if (_popped) { // Popped out the pickers are here as well (an older RynthCore's pop-out lets clicks @@ -939,7 +970,7 @@ internal sealed unsafe class InstrumentDashboard DashboardFiles files = _d.ReadFiles(); PickerMenu("Profile", files.Profiles, files.ProfileIdx, 3); PickerMenu("Nav", files.Navs, files.NavIdx, 0); - PickerMenu("Loot", files.Loots, files.LootIdx, 1); + PickerMenu("Loot", files.Loots, files.LootIdx, 1, files.LootMode); PickerMenu("Meta", files.Metas, files.MetaIdx, 2); PickerMenu("Buffs", files.Buffs, files.BuffIdx, 4); p = ImGui.GetCursorScreenPos(); @@ -1018,12 +1049,20 @@ internal sealed unsafe class InstrumentDashboard } /// A picker as a submenu (popped out, the options menu holds the pickers). - private void PickerMenu(string label, string[] items, int selected, int kind) + private void PickerMenu(string label, string[] items, int selected, int kind, int lootMode = -1) { string current = selected >= 0 && selected < items.Length ? items[selected] : "None"; + if (Loot.LootModes.IsRares(lootMode)) current = "rares + mana stones"; if (!ImGui.BeginMenu(label + ": " + SafeImGui.Escape(current) + "##pm" + kind)) return; try { + if (lootMode >= 0) + { + for (int m = 0; m < LootModeRows.Length; m++) + if (ImGui.MenuItem(LootModeRows[m] + "##pmm" + m, "", Loot.LootModes.Clamp(lootMode) == m)) + _d.SetLootMode(m); + ImGui.Separator(); + } if (items.Length == 0) ImGui.TextDisabled("None"); for (int i = 0; i < items.Length; i++) if (ImGui.MenuItem(SafeImGui.Escape(items[i]) + "##pmi" + kind + "_" + i, "", i == selected)) @@ -1422,7 +1461,7 @@ internal sealed unsafe class InstrumentDashboard y = PickerRow(dl, x0, y, w, "PROFILE", f.ProfileName, f.Profiles, f.ProfileIdx, 3, null, null, null) + Px(4); y = PickerRow(dl, x0, y, w, "NAV", f.NavName, f.Navs, f.NavIdx, 0, null, null, null) + Px(4); y = PickerRow(dl, x0, y, w, "LOOT", f.LootName, f.Loots, f.LootIdx, 1, RynthIcons.TreasureChest, - "Loot Editor: the loot profile in use.", () => _d.Host.SetPanelOpen("Loot Editor", RynthPanelOpen.Toggle)) + Px(4); + "Loot Editor: the loot profile in use.", () => _d.Host.SetPanelOpen("Loot Editor", RynthPanelOpen.Toggle), f.LootMode) + Px(4); y = PickerRow(dl, x0, y, w, "META", f.MetaName, f.Metas, f.MetaIdx, 2, null, null, null) + Px(4); y = PickerRow(dl, x0, y, w, "BUFFS", f.BuffName, f.Buffs, f.BuffIdx, 4, RynthIcons.Sparkle, "RynthAi Spells: the spell list and buff profiles.", _d.ToggleSpells); @@ -1430,12 +1469,13 @@ internal sealed unsafe class InstrumentDashboard } private float PickerRow(ImDrawListPtr dl, float x0, float y, float w, string label, string current, string[] items, int selected, - int kind, string? buttonIcon, string? buttonTip, Action? button) + int kind, string? buttonIcon, string? buttonTip, Action? button, int lootMode = -1) { float h = Px(22), labelW = Px(44), r = Px(3); ImFontPtr lf = Font(RynthUiFont.Narrow9); Tracked(dl, lf, lf.FontSize, new Vector2(x0, MathF.Round(y + (h - lf.FontSize) * 0.5f)), _faint, label, 0.14f * lf.FontSize); - float fx = x0 + labelW, fw = w - labelW - (button != null ? h + Px(4) : 0); + // The LOOT row also has a one-click Loot Mode key (a star, lit in rares mode) left of its button. + float fx = x0 + labelW, fw = w - labelW - (button != null ? h + Px(4) : 0) - (lootMode >= 0 ? h + Px(4) : 0); Vector2 p = new(fx, y), s = new(fw, h); string popup = Id("##pick", kind); ImGui.SetCursorScreenPos(p); @@ -1446,6 +1486,10 @@ internal sealed unsafe class InstrumentDashboard _pickWidth = fw; } bool hot = ImGui.IsItemHovered(); + if (lootMode >= 0) + SafeImGui.SetItemTooltip(Loot.LootModes.IsRares(lootMode) + ? "Loot Mode: rares and needed mana stones only. The loot profile is not used; nothing else is looted.\nClick: a loot profile, or the loot mode." + : "Loot Mode: the loot profile.\nClick: a loot profile, or the loot mode."); dl.AddRectFilled(p, p + s, _inset, r); dl.AddRect(p, p + s, hot ? Mix(_line, _accent, 0.45f) : _line, r); ImFontPtr vf = Font(RynthUiFont.Narrow11); @@ -1453,9 +1497,26 @@ internal sealed unsafe class InstrumentDashboard dl.AddText(vf, vf.FontSize, new Vector2(MathF.Round(fx + Px(7)), MathF.Round(y + (h - vf.FontSize) * 0.5f)), _text, current); dl.PopClipRect(); DrawIcon(dl, RynthIcons.CaretDown, new Vector2(fx + fw - Px(16), y), new Vector2(Px(10), h), Px(10), _dim); + float bx = fx + fw + Px(4); + if (lootMode >= 0) + { + bool rares = Loot.LootModes.IsRares(lootMode); + Vector2 mp = new(bx, y), ms = new(h, h); + ImGui.SetCursorScreenPos(mp); + if (ImGui.InvisibleButton(Id("##lootmode", kind), ms)) + _d.SetLootMode(rares ? Loot.LootModes.Profile : Loot.LootModes.Rares); + bool mhot = ImGui.IsItemHovered(); + SafeImGui.SetItemTooltip(rares + ? "Loot Mode: rares and needed mana stones only (the loot profile is not used).\nClick: loot by the loot profile again." + : "Loot Mode: the loot profile.\nClick: loot only rares and needed mana stones (the loot profile is not used)."); + dl.AddRectFilled(mp, mp + ms, rares ? Mix(_bg, _accent, 0.16f) : _key, r); + dl.AddRect(mp, mp + ms, rares ? _accent : _line, r); + DrawIcon(dl, RynthIcons.Star, mp, ms, Px(12), rares ? _accent : mhot ? _text : _dim); + bx += h + Px(4); + } if (button != null && buttonIcon != null) { - Vector2 bp = new(fx + fw + Px(4), y), bs = new(h, h); + Vector2 bp = new(bx, y), bs = new(h, h); ImGui.SetCursorScreenPos(bp); if (ImGui.InvisibleButton(Id("##fbtn", kind), bs)) button(); bool bhot = ImGui.IsItemHovered(); @@ -1464,20 +1525,24 @@ internal sealed unsafe class InstrumentDashboard dl.AddRect(bp, bp + bs, _line, r); DrawIcon(dl, buttonIcon, bp, bs, Px(12), bhot ? _text : _dim); } - PickerPopup(popup, items, selected, kind); + PickerPopup(popup, items, selected, kind, lootMode); return y + h; } private Vector2 _pickAnchor; private float _pickWidth; - private void PickerPopup(string id, string[] items, int selected, int kind) + /// The LOOT picker's Loot Mode rows, above the loot profiles. + private static readonly string[] LootModeRows = { "Mode: the loot profile", "Mode: rares + needed mana stones only" }; + + private void PickerPopup(string id, string[] items, int selected, int kind, int lootMode = -1) { if (!ImGui.IsPopupOpen(id)) return; ImGui.SetNextWindowPos(_pickAnchor, ImGuiCond.Appearing); float itemH = Px(22); - float maxH = Math.Min(items.Length * itemH + Px(10), Math.Max(Px(60), ImGui.GetIO().DisplaySize.Y - _pickAnchor.Y - Px(20))); - ImGui.SetNextWindowSize(new Vector2(Math.Max(_pickWidth, Px(160)), Math.Max(maxH, Px(32)))); + int extra = lootMode >= 0 ? LootModeRows.Length : 0; + float maxH = Math.Min((items.Length + extra) * itemH + (extra > 0 ? Px(9) : 0) + Px(10), Math.Max(Px(60), ImGui.GetIO().DisplaySize.Y - _pickAnchor.Y - Px(20))); + ImGui.SetNextWindowSize(new Vector2(Math.Max(_pickWidth, Px(extra > 0 ? 220 : 160)), Math.Max(maxH, Px(32)))); PushPopupStyle(); bool open = ImGui.BeginPopup(id); PopPopupStyle(); @@ -1487,27 +1552,44 @@ internal sealed unsafe class InstrumentDashboard ImDrawListPtr dl = ImGui.GetWindowDrawList(); float w = ImGui.GetContentRegionAvail().X; ImFontPtr f = Font(RynthUiFont.Narrow11); + + bool Row(string rowId, string text, bool isSel) + { + Vector2 p = ImGui.GetCursorScreenPos(); + bool clicked = ImGui.InvisibleButton(rowId, new Vector2(w, itemH)); + bool hot = ImGui.IsItemHovered(); + if (hot || isSel) dl.AddRectFilled(p, p + new Vector2(w, itemH), isSel ? Mix(_bg, _accent, 0.16f) : _key, Px(3)); + if (isSel) dl.AddRectFilled(new Vector2(p.X + Px(4), p.Y + itemH * 0.5f - Px(2)), new Vector2(p.X + Px(8), p.Y + itemH * 0.5f + Px(2)), _accent, Px(2)); + dl.PushClipRect(p, p + new Vector2(w, itemH), true); + dl.AddText(f, f.FontSize, new Vector2(MathF.Round(p.X + Px(14)), MathF.Round(p.Y + (itemH - f.FontSize) * 0.5f)), isSel ? _accent : _text, text); + dl.PopClipRect(); + return clicked; + } + + // The loot mode first: in rares mode the profile below isn't used. + if (extra > 0) + { + for (int m = 0; m < LootModeRows.Length; m++) + if (Row(Id("##plm", m), LootModeRows[m], Loot.LootModes.Clamp(lootMode) == m)) + { + _d.SetLootMode(m); + ImGui.CloseCurrentPopup(); + } + Vector2 sp = ImGui.GetCursorScreenPos(); + dl.AddLine(new Vector2(sp.X, sp.Y + Px(4) + 0.5f), new Vector2(sp.X + w, sp.Y + Px(4) + 0.5f), _line); + ImGui.Dummy(new Vector2(w, Px(9))); + } if (items.Length == 0) { ImGui.TextDisabled("None"); return; } for (int i = 0; i < items.Length; i++) - { - Vector2 p = ImGui.GetCursorScreenPos(); - bool isSel = i == selected; - if (ImGui.InvisibleButton(Id("##pi", i), new Vector2(w, itemH))) + if (Row(Id("##pi", i), items[i], i == selected)) { _d.SelectProfile(kind, i); ImGui.CloseCurrentPopup(); } - bool hot = ImGui.IsItemHovered(); - if (hot || isSel) dl.AddRectFilled(p, p + new Vector2(w, itemH), isSel ? Mix(_bg, _accent, 0.16f) : _key, Px(3)); - if (isSel) dl.AddRectFilled(new Vector2(p.X + Px(4), p.Y + itemH * 0.5f - Px(2)), new Vector2(p.X + Px(8), p.Y + itemH * 0.5f + Px(2)), _accent, Px(2)); - dl.PushClipRect(p, p + new Vector2(w, itemH), true); - dl.AddText(f, f.FontSize, new Vector2(MathF.Round(p.X + Px(14)), MathF.Round(p.Y + (itemH - f.FontSize) * 0.5f)), isSel ? _accent : _text, items[i]); - dl.PopClipRect(); - } } finally { diff --git a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs index 2809923..250126f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs @@ -38,6 +38,7 @@ public sealed partial class RynthAiPlugin private long _groundTargetSince; private long _groundPickupRequestedAt; private int _groundPickupAttempts; + private int _groundErrSeqAtSend; // the refusal counter at the last send (a quest refusal since then) private string _groundTargetName = string.Empty; private string _groundTargetAction = string.Empty; private string _groundTargetRule = string.Empty; @@ -115,8 +116,9 @@ public sealed partial class RynthAiPlugin if (_objectCache == null || maxMeters <= 0.25) return null; // The profile loaders chat on every failed load; a 300 ms scan must not trigger that. + // Rares mode loads no profile (rares and needed mana stones only). string profilePath = (settings.CurrentLootPath ?? string.Empty).Trim().Trim('"'); - if (profilePath.Length == 0 || !System.IO.File.Exists(profilePath)) + if (!Loot.LootModes.IsRares(settings.LootMode) && (profilePath.Length == 0 || !System.IO.File.Exists(profilePath))) return null; int playerId = unchecked((int)_playerId); @@ -244,6 +246,17 @@ public sealed partial class RynthAiPlugin return; } + // The server won't hand it over yet (a pickup timer, a quest flag: 2026-11-01, #rynth-issues + // "Stopped looting"): no retry will do better for minutes, and an answer naming no object + // leaves the client's request slot full (see LeaveQuestRefusedLootItem). + if (QuestPickupRefusedSince(_groundErrSeqAtSend, id, out uint questErr, out uint questObj)) + { + LootDiag($"[RynthAi] Ground loot: the server won't hand over 0x{(uint)id:X8} '{_groundTargetName}': {QuestPickupRefusalText(questErr)} (error 0x{questErr:X}, object 0x{questObj:X8}); leaving it."); + EmptyClientRequestAfterAnonymousRefusal(questObj); + FinishGroundTarget(now, GroundFailCooldownMs); + return; + } + if (now - _groundPickupRequestedAt < GroundPickupVerifyMs) return; @@ -265,6 +278,7 @@ public sealed partial class RynthAiPlugin uint uid = unchecked((uint)_groundTargetId); Host.SelectItem(uid); + _groundErrSeqAtSend = LastWeenieErrorSeq(); bool sent = Host.HasMoveItemExternal ? Host.MoveItemExternal(uid, _playerId, 0) : Host.UseObject(uid); diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs index 13efac0..a43fbaa 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs @@ -4,6 +4,7 @@ // [RynthAi] Looted [Keep] Blunt Crossbow (rule "(M) Xbow (OD +9)"): Gold, Pierce Crossbow, +22, +162%, ... // [RynthAi] Looted [Salvage] Ornate Long Sword (rule "Gold any"): Gold, Craft 6 (Include salvage on) // [RynthAi] Looted [Keep] Pyreal (stackables: plain) +// [RynthAi] Looted [Keep] Pearl of Blood Drinking (Rares mode: rare): ... (Loot Mode rares) // // The head stays "[RynthAi] Looted [] ": the self-test meta and players' metas match it. using System; @@ -77,7 +78,10 @@ internal static class LootChatLine if (!identified) fields.Add("not IDed"); var sb = new StringBuilder(Plain(action, name), 256); - string ruleText = rule.Length > 0 ? $"rule \"{rule}\"" : string.Empty; + // Rares mode has no rule: its reason shows as it is ("Rares mode: rare"). + string ruleText = rule.Length == 0 ? string.Empty + : rule.StartsWith(RynthAi.Loot.LootModes.RulePrefix, StringComparison.Ordinal) ? rule + : $"rule \"{rule}\""; if (where.Length > 0 && ruleText.Length > 0) sb.Append(" (").Append(where).Append(", ").Append(ruleText).Append(')'); else if (where.Length > 0 || ruleText.Length > 0) sb.Append(" (").Append(where).Append(ruleText).Append(')'); if (fields.Count > 0) sb.Append(": ").Append(string.Join(", ", fields)); diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs index b2bbd6a..1789fb4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs @@ -3,9 +3,13 @@ using System; namespace RynthCore.Plugin.RynthAi.ItemInfo; /// -/// Items RynthAi selects by itself (the looter picking an item up, a meta's selectitem), so the -/// selection-change handler can tell them from the player's own clicks: Item Info on select -/// prints only for the player's. goes right before Host.SelectItem. +/// Objects RynthAi selects by itself (the looter picking an item up, a meta's selectitem, combat's +/// native attack selecting its target), so the selection-change handler can tell them from the +/// player's own clicks: Item Info on select prints only for the player's, and "Fight the monster I +/// select" (CombatManager.SelectedTarget.cs) follows only the player's. goes +/// right before Host.SelectItem (or use ). +/// The last few marks are kept (not just one): combat re-selects its target on every native +/// attack, and a looter pick a moment later must not make that one look like the player's. /// internal static class SelfSelect { @@ -14,14 +18,54 @@ internal static class SelfSelect internal static Func Clock = () => Environment.TickCount64; - private static uint _id; - private static long _at; + private const int Slots = 8; + private static readonly uint[] _ids = new uint[Slots]; + private static readonly long[] _ats = new long[Slots]; + private static int _next; + private static readonly object _gate = new(); internal static void Mark(uint id) { - _at = Clock(); - _id = id; + if (id == 0) return; + lock (_gate) + { + long now = Clock(); + // The same id again refreshes its slot (native attacks mark the target every swing). + for (int i = 0; i < Slots; i++) + if (_ids[i] == id) { _ats[i] = now; return; } + _ids[_next] = id; + _ats[_next] = now; + _next = (_next + 1) % Slots; + } } - internal static bool IsOurs(uint id) => id != 0 && id == _id && Clock() - _at <= WindowMs; + internal static bool IsOurs(uint id) + { + if (id == 0) return false; + lock (_gate) + { + long now = Clock(); + for (int i = 0; i < Slots; i++) + if (_ids[i] == id && now - _ats[i] <= WindowMs) return true; + return false; + } + } + + /// Forgets every mark (tests). + internal static void Reset() + { + lock (_gate) + { + Array.Clear(_ids); + Array.Clear(_ats); + _next = 0; + } + } + + /// Marks as RynthAi's own pick, then selects it. + internal static bool SelectAsBot(this RynthCore.PluginSdk.RynthCoreHost host, uint id) + { + Mark(id); + return host.SelectItem(id); + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index ef824a8..710e717 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -55,6 +55,10 @@ internal sealed class LegacyAdvancedSettingsUi public void SetMissileCraftingManager(MissileCraftingManager mgr) => _missileCraftingManager = mgr; + /// The loot profile files ("None" first) and picking one: Settings > Looting's Loot Profile. + public Func? LootProfiles { get; init; } + public Action? SelectLootProfile { get; init; } + private Func? _autoVendorStatus; public void SetAutoVendorStatusProvider(Func status) => _autoVendorStatus = status; @@ -770,6 +774,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Target Lock", ref _settings.TargetLock); if (ImGui.IsItemHovered()) ImGui.SetTooltip("On: keeps the target it picked until it dies, leaves Monster Range, or a higher-priority monster shows up.\nOff: switches whenever another monster is clearly better by the Targeting rule."); + ImGui.Checkbox("Fight the monster I select", ref _settings.FightSelectedTarget); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip(LegacyUiSettings.FightSelectedTargetTip); ImGui.Spacing(); ImGui.Text("Corpse Acquisition (Yards)"); @@ -1064,17 +1071,38 @@ internal sealed class LegacyAdvancedSettingsUi case "Looting": ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting); + // The loot profile picker (the dashboard's LOOT list), and beside it Loot Mode, which + // decides whether that profile is used at all. + string[]? lootFiles = LootProfiles?.Invoke(); + if (lootFiles != null && lootFiles.Length > 0 && SelectLootProfile != null) + { + int lootIdx = Math.Clamp(_settings.LootProfileIdx, 0, lootFiles.Length - 1); + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("Loot Profile", ref lootIdx, lootFiles, lootFiles.Length) && lootIdx != _settings.LootProfileIdx) + SelectLootProfile(lootIdx); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip(Loot.LootModes.IsRares(_settings.LootMode) + ? "The loot profile. Not used while Loot Mode is Rares and needed mana stones only." + : "The loot profile: what corpses, chests and ground items give up."); + ImGui.SameLine(); + } + _settings.LootMode = Loot.LootModes.Clamp(_settings.LootMode); + ImGui.SetNextItemWidth(240); + ImGui.Combo("Loot Mode", ref _settings.LootMode, Loot.LootModes.Labels, Loot.LootModes.Labels.Length); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Profile: the loot profile picked on the dashboard (LOOT), with RynthAi's built-in keeps.\n" + + "Rares and needed mana stones only: the loot profile is not used. Every rare is looted, and\n" + + "mana stones while you have fewer than the Items panel's keep count (Mana Stone Tapping);\n" + + "nothing else (no salvage, no Learn Unknown Spells, no Mana Tap). Recover My Corpse still works.\n" + + "Also /ra loot mode profile|rares, and the meta setting LootMode (0 or 1)."); ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority); // "Loot Only Rare Corpses" is hidden: nothing reads LootOnlyRareCorpses. ImGui.Checkbox("Learn Unknown Spells", ref _settings.ReadUnknownScrolls); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too."); ImGui.Checkbox("Jump When Looting", ref _settings.LootJumpEnabled); - if (_settings.LootJumpEnabled) - { - ImGui.SetNextItemWidth(120); - ImGui.SliderInt("Jump Height", ref _settings.LootJumpHeight, 1, 100); - } + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Hop (the keyboard jump) just before each pickup,\nso the server skips the bend-down. The hop has a fixed height."); ImGui.Spacing(); ImGui.Text("Corpse Ownership"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs index d324870..7e80a1b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs @@ -21,7 +21,8 @@ internal readonly record struct DashboardReadout( uint Health, uint MaxHealth, uint Stamina, uint MaxStamina, uint Mana, uint MaxMana, bool Locked, float Opacity, string LootPath, - bool TargetIsFight = false); + bool TargetIsFight = false, + int LootMode = 0); /// The loaded-files pickers: each list, and the entry in use. internal sealed record DashboardFiles( @@ -30,7 +31,8 @@ internal sealed record DashboardFiles( string[] Loots, int LootIdx, string[] Metas, int MetaIdx, string[] Buffs, int BuffIdx, - string ProfileName, string NavName, string LootName, string MetaName, string BuffName); + string ProfileName, string NavName, string LootName, string MetaName, string BuffName, + int LootMode = 0); internal sealed partial class LegacyDashboardRenderer { @@ -47,7 +49,8 @@ internal sealed partial class LegacyDashboardRenderer _settings.ShowTargetStaminaMana, _targetStamina, _targetMaxStamina, _targetMana, _targetMaxMana, _playerHealth, _playerMaxHealth, _playerStamina, _playerMaxStamina, _playerMana, _playerMaxMana, _isLocked, _bgOpacity, - !string.IsNullOrEmpty(_vendorProfilePath?.Invoke()) ? _vendorProfilePath!.Invoke() : _settings.CurrentLootPath ?? string.Empty); + !string.IsNullOrEmpty(_vendorProfilePath?.Invoke()) ? _vendorProfilePath!.Invoke() : _settings.CurrentLootPath ?? string.Empty, + LootMode: Loot.LootModes.Clamp(_settings.LootMode)); } /// The five pickers' lists (copied under the lists' lock) and the entry in use. Any thread. @@ -71,9 +74,21 @@ internal sealed partial class LegacyDashboardRenderer buffs, _settings.BuffProfileIdx, profile, string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath), - string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath), + LootLineName(), string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath), - string.IsNullOrEmpty(_settings.CurrentBuffProfilePath) ? BuiltInBuffProfileLabel : Path.GetFileNameWithoutExtension(_settings.CurrentBuffProfilePath)); + string.IsNullOrEmpty(_settings.CurrentBuffProfilePath) ? BuiltInBuffProfileLabel : Path.GetFileNameWithoutExtension(_settings.CurrentBuffProfilePath), + Loot.LootModes.Clamp(_settings.LootMode)); + } + + /// + /// The LOOT line: the loot profile, or in rares mode what is looted instead (so a player can + /// see why nothing else is taken): "Rares + needed mana stones (LootSnob not used)". + /// + internal string LootLineName() + { + string profile = string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath); + if (!Loot.LootModes.IsRares(_settings.LootMode)) return profile; + return profile == "None" ? "Rares + needed mana stones" : $"Rares + needed mana stones ({profile} not used)"; } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 981fcfe..c9abe77 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -45,6 +45,8 @@ internal sealed partial class LegacyDashboardRenderer private readonly LegacyNavigationUi _navigationUi; private readonly LegacyWeaponsUi _weaponsUi; private readonly LegacyMetaUi _metaUi; + /// Every write of the meta file and its result (both editors; the engine panel reads it). + private readonly MetaSaver _metaSaver; private readonly DungeonMapUi _dungeonMapUi; private readonly RynthRadarUi _rynthRadarUi; private readonly RynthChatUi _rynthChatUi; @@ -245,10 +247,16 @@ internal sealed partial class LegacyDashboardRenderer public LegacyDashboardRenderer(RynthCoreHost host) { _host = host; - _advancedSettingsUi = new LegacyAdvancedSettingsUi(_settings); + _advancedSettingsUi = new LegacyAdvancedSettingsUi(_settings) + { + // Settings > Looting shows the loot profile picker beside Loot Mode. + LootProfiles = () => { lock (_profileListsLock) return _lootFiles.ToArray(); }, + SelectLootProfile = index => SelectProfileAtIndex(1, index), + }; _navigationUi = new LegacyNavigationUi(_settings, host); _weaponsUi = new LegacyWeaponsUi(_settings, host); - _metaUi = new LegacyMetaUi(_settings, _navFiles); + _metaSaver = new MetaSaver(_settings, line => _host.Log(line)); + _metaUi = new LegacyMetaUi(_settings, _navFiles) { Saver = _metaSaver }; _dungeonMapUi = new DungeonMapUi(); _rynthRadarUi = new RynthRadarUi(host, _settings); _rynthRadarUi.SetMapData(_dungeonMapUi); @@ -434,6 +442,9 @@ internal sealed partial class LegacyDashboardRenderer _settings.CurrentState = "Default"; _settings.BotAction = "Default"; + // The meta's rules come from its file, not from the copy this profile saved (2026-11-01). + if (!freshProfile && !holdUnreadable) SyncMetaWithFile("login"); + // Reload nav route from saved path if (!string.IsNullOrEmpty(_settings.CurrentNavPath) && File.Exists(_settings.CurrentNavPath)) { @@ -505,6 +516,65 @@ internal sealed partial class LegacyDashboardRenderer _settings.BotAction = "Default"; } + /// + /// The meta named by the profile (CurrentMetaPath) runs with its FILE's rules (2026-11-01). A settings + /// profile keeps its own copy of the meta's rules (MetaRules), and that copy, not the file, used to + /// be what ran after a login, a plugin reload or a profile switch. A meta changed anywhere else (in + /// another client, by the rmeta tool, in a text editor, by a save from another profile) kept running + /// the old rules here, and this client's next edit wrote that old copy, plus the edit, over the + /// newer file. Kept: the profile's copy when the file is missing or doesn't read, and when the last + /// save of an edit here failed (), so that edit isn't lost. + /// + internal void SyncMetaWithFile(string when) + { + string path = _settings.CurrentMetaPath ?? string.Empty; + if (path.Length == 0) return; + int mine; + lock (_settings.MetaRulesLock) mine = _settings.MetaRules.Count; + try + { + if (!File.Exists(path)) + { + _host.Log($"[RynthAi] Meta ({when}): {path} isn't there; running the copy of its rules kept with these settings ({mine} rules)."); + return; + } + if (_settings.MetaUnsaved) + { + _host.Log($"[RynthAi] Meta ({when}): the last change to {path} wasn't saved to the file; running the copy kept with these settings ({mine} rules). The next successful save writes it."); + _host.WriteToChat($"[RynthAi] Your last change to meta {Path.GetFileName(path)} wasn't saved to its file; using the copy kept with your settings. It is saved with your next change (or Save As).", 1); + return; + } + string ext = Path.GetExtension(path); + LoadedMeta loaded = ext.Equals(".met", StringComparison.OrdinalIgnoreCase) ? MetFileParser.Load(path) + : ext.Equals(".af", StringComparison.OrdinalIgnoreCase) ? AfFileParser.Load(path) + : new LoadedMeta(); + if (loaded.Rules.Count == 0 && !loaded.IsBlank) + { + _host.Log($"[RynthAi] Meta ({when}): {path} didn't read ({(loaded.Warnings.Count > 0 ? loaded.Warnings[0] : "no rules")}); running the copy kept with these settings ({mine} rules)."); + return; + } + var noNavs = new Dictionary>(); + string fileText = AfFileWriter.SaveToString(loaded.Rules, noNavs); + string mineText; + lock (_settings.MetaRulesLock) mineText = AfFileWriter.SaveToString(_settings.MetaRules, noNavs); + lock (_settings.MetaRulesLock) + { + if (fileText != mineText) _settings.MetaRules = loaded.Rules; + _settings.EmbeddedNavs.Clear(); + foreach (var kvp in loaded.EmbeddedNavs) _settings.EmbeddedNavs[kvp.Key] = kvp.Value; + } + if (fileText != mineText) + { + _settings.MetaRulesStructuralVersion++; + _host.Log($"[RynthAi] Meta ({when}): {path} differs from the copy kept with these settings ({mine} rules); running the file's {loaded.Rules.Count} rules."); + } + } + catch (Exception ex) + { + _host.Log($"[RynthAi] Meta ({when}): reading {path} failed ({ex.GetType().Name}: {ex.Message}); running the copy kept with these settings ({mine} rules)."); + } + } + public void SaveSettings() { if (string.IsNullOrEmpty(_settingsFilePath)) return; @@ -1254,6 +1324,7 @@ internal sealed partial class LegacyDashboardRenderer MonsterDisengageRange = s.MonsterDisengageRange, TargetSelection = s.TargetSelection, TargetLock = s.TargetLock, + FightSelectedTarget = s.FightSelectedTarget, RingRange = s.RingRange, ApproachRange = s.ApproachRange, CorpseApproachRangeMax = s.CorpseApproachRangeMax, @@ -1330,6 +1401,7 @@ internal sealed partial class LegacyDashboardRenderer LootOwnCorpse = s.LootOwnCorpse, EscapeHazards = s.EscapeHazards, TravelToOwnCorpse = s.TravelToOwnCorpse, + LootMode = s.LootMode, ItemInfoOnSelect = s.ItemInfoSettings.OnSelect, EnableAutostack = s.EnableAutostack, ReadUnknownScrolls = s.ReadUnknownScrolls, @@ -1515,6 +1587,7 @@ internal sealed partial class LegacyDashboardRenderer if (p.MonsterDisengageRange >= 0) s.MonsterDisengageRange = p.MonsterDisengageRange; // -1 = not sent if (p.TargetSelection is int targeting) s.TargetSelection = Math.Clamp(targeting, 0, 3); // absent = unchanged if (p.TargetLock is bool targetLock) s.TargetLock = targetLock; // absent = unchanged + if (p.FightSelectedTarget is bool fightSel) s.FightSelectedTarget = fightSel; // absent = unchanged s.RingRange = p.RingRange; s.ApproachRange = p.ApproachRange; s.CorpseApproachRangeMax = p.CorpseApproachRangeMax; @@ -1590,6 +1663,7 @@ internal sealed partial class LegacyDashboardRenderer if (p.EscapeHazards is bool escape) s.EscapeHazards = escape; // absent = unchanged if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged + if (p.LootMode is int lootMode) s.LootMode = Loot.LootModes.Clamp(lootMode); // absent = unchanged if (p.ItemInfoOnSelect is bool infoOnSelect) s.ItemInfoSettings.OnSelect = infoOnSelect; // absent = unchanged s.EnableAutostack = p.EnableAutostack; s.ReadUnknownScrolls = p.ReadUnknownScrolls; @@ -1829,6 +1903,7 @@ internal sealed partial class LegacyDashboardRenderer CopySettings(loaded!, _settings); _settings.SelectedProfile = newProfile; _lastSavedJson = json; + SyncMetaWithFile("profile " + newProfile); } else { @@ -1935,6 +2010,7 @@ internal sealed partial class LegacyDashboardRenderer dst.CurrentNavPath = tmp.CurrentNavPath; dst.CurrentLootPath = tmp.CurrentLootPath; dst.CurrentMetaPath = tmp.CurrentMetaPath; + dst.MetaUnsaved = tmp.MetaUnsaved; dst.MacroSettingsIdx = tmp.MacroSettingsIdx; dst.NavProfileIdx = tmp.NavProfileIdx; dst.LootProfileIdx = tmp.LootProfileIdx; @@ -2011,6 +2087,7 @@ internal sealed partial class LegacyDashboardRenderer dst.MonsterDisengageRange = tmp.MonsterDisengageRange; dst.TargetSelection = Math.Clamp(tmp.TargetSelection, 0, 3); dst.TargetLock = tmp.TargetLock; + dst.FightSelectedTarget = tmp.FightSelectedTarget; dst.RingRange = tmp.RingRange; dst.HandlerRingEvade = tmp.HandlerRingEvade; // obsolete (RynthILT's now): carried so the profile keeps it for RynthILT's one-time import dst.ApproachRange = tmp.ApproachRange; @@ -2046,6 +2123,7 @@ internal sealed partial class LegacyDashboardRenderer dst.EscapeHazards = tmp.EscapeHazards; dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse; dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses; + dst.LootMode = tmp.LootMode; // read through LootModes (an unknown value = Profile) dst.EnableGroundLoot = tmp.EnableGroundLoot; dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle; dst.RearmAfterVitals = tmp.RearmAfterVitals; @@ -3084,8 +3162,12 @@ internal sealed partial class LegacyDashboardRenderer AppendInt(sb, "selectedBuffIdx", _settings.BuffProfileIdx); sb.Append(','); AppendString(sb, "currentNavName", string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath)); sb.Append(','); + // Rares mode says so where the profile's name would be (the Classic look and the status + // agent show it, cut to 16 characters). AppendString(sb, "currentLootName", - string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath)); sb.Append(','); + Loot.LootModes.IsRares(_settings.LootMode) ? "Rares + stones" + : string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath)); sb.Append(','); + AppendString(sb, "lootMode", Loot.LootModes.Word(_settings.LootMode)); 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(','); @@ -3404,6 +3486,14 @@ internal sealed partial class LegacyDashboardRenderer AppendString(sb, "text", _metaApplyText); sb.Append('}'); + // The last write of the meta file, or the edit that wasn't applied (MetaSaver). The engine + // panel's "Saved" indicator follows this, not a timer. Seq 0 = nothing tried this session. + sb.Append(",\"saveResult\":{\"seq\":").Append(_metaSaver.Seq).Append(','); + AppendBool(sb, "ok", _metaSaver.LastOk); sb.Append(','); + AppendString(sb, "text", _metaSaver.LastText); sb.Append(','); + AppendString(sb, "path", _metaSaver.LastPath); + sb.Append('}'); + // The Meta Manager's rules and timers (built on the plugin tick; see MetaScheduler). string? schedule = ScheduleJsonProvider?.Invoke(); if (!string.IsNullOrEmpty(schedule)) @@ -3512,10 +3602,16 @@ internal sealed partial class LegacyDashboardRenderer private void ApplyMetaCommand(string json) { if (string.IsNullOrWhiteSpace(json)) return; + string op = "?"; try { var cmd = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MetaCommand); - if (cmd == null) return; + if (cmd == null) + { + _metaSaver.Refuse("Edit not applied: the Meta panel's command didn't read.", "command"); + return; + } + op = cmd.Op ?? "?"; // The Meta Manager (schedule) owns its own state; not the meta's rules. if (cmd.Op.StartsWith("mm_", System.StringComparison.Ordinal)) @@ -3558,22 +3654,22 @@ internal sealed partial class LegacyDashboardRenderer break; case "save_file": - if (!string.IsNullOrEmpty(cmd.Path)) + if (string.IsNullOrEmpty(cmd.Path)) + { + _metaSaver.Refuse("Not saved: no file name was given.", "save_file"); + break; + } { string savePath = cmd.Path; - bool saved; - string why; - lock (_settings.MetaRulesLock) - saved = DataWriteGuard.TrySave("the meta", savePath, - () => AfFileWriter.Save(savePath, _settings.MetaRules, _settings.EmbeddedNavs), out why, callerShows: true); - if (saved) + if (_metaSaver.SaveTo(savePath, "Save As", callerShows: true)) { _settings.CurrentMetaPath = savePath; + RefreshMetaFiles(); // the picker lists (and selects) the new file SaveSettings(); } else { - ReportMetaApply(false, $"Meta not saved to {savePath}: {why}"); + ReportMetaApply(false, "Meta " + _metaSaver.LastText); } } break; @@ -3595,7 +3691,7 @@ internal sealed partial class LegacyDashboardRenderer _settings.EmbeddedNavs.Clear(); foreach (var kvp in loaded.EmbeddedNavs) _settings.EmbeddedNavs[kvp.Key] = kvp.Value; _settings.ForceStateReset = true; - TryAutoSaveMetaCmd(); + TryAutoSaveMetaCmd("set_source"); ReportMetaApply(true, $"Applied source: {loaded.Rules.Count} rules{w}"); } else @@ -3610,27 +3706,27 @@ internal sealed partial class LegacyDashboardRenderer break; case "add_rule": - if (cmd.Rule != null) - { - _settings.MetaRules.Add(DtoToMetaRule(cmd.Rule)); - TryAutoSaveMetaCmd(); - } + if (cmd.Rule == null) { RefuseEdit(op, "the command carried no rule"); break; } + _settings.MetaRules.Add(DtoToMetaRule(cmd.Rule)); + TryAutoSaveMetaCmd($"add_rule (now {_settings.MetaRules.Count} rules)"); break; case "update_rule": // The engine's editor saves every change (2026-10-05): keep the running rule's // latch (no re-fire) and the fields the panel can't send (MetaRuleEdits). - if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule), - keepName: cmd.Rule.Name == null)) - TryAutoSaveMetaCmd(); + if (cmd.Rule == null) { RefuseEdit(op, "the command carried no rule"); break; } + if (!MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule), keepName: cmd.Rule.Name == null)) + { + RefuseEdit(op, NoSuchRule(cmd.Index)); + break; + } + TryAutoSaveMetaCmd($"update_rule {cmd.Index + 1}"); break; case "delete_rule": - if (cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) - { - _settings.MetaRules.RemoveAt(cmd.Index); - TryAutoSaveMetaCmd(); - } + if (!HasRule(cmd.Index)) { RefuseEdit(op, NoSuchRule(cmd.Index)); break; } + _settings.MetaRules.RemoveAt(cmd.Index); + TryAutoSaveMetaCmd($"delete_rule {cmd.Index + 1}"); break; case "move_up": @@ -3639,41 +3735,59 @@ internal sealed partial class LegacyDashboardRenderer // state, so "up" is the previous rule of the SAME state, not // the previous list entry (which may belong to another state). { + if (!HasRule(cmd.Index)) { RefuseEdit(op, NoSuchRule(cmd.Index)); break; } int other = SameStateNeighbour(cmd.Index, cmd.Op == "move_up" ? -1 : 1); if (other >= 0) { var tmp = _settings.MetaRules[other]; _settings.MetaRules[other] = _settings.MetaRules[cmd.Index]; _settings.MetaRules[cmd.Index] = tmp; - TryAutoSaveMetaCmd(); + TryAutoSaveMetaCmd($"{op} {cmd.Index + 1}"); } + else // already first / last in its state: nothing to write + _metaSaver.Note("Nothing to move: the rule is already at that end of its state.", _settings.CurrentMetaPath ?? ""); } break; case "duplicate_rule": - if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) + if (cmd.Rule == null) { RefuseEdit(op, "the command carried no rule"); break; } + if (!HasRule(cmd.Index)) { RefuseEdit(op, NoSuchRule(cmd.Index)); break; } { var copy = DtoToMetaRule(cmd.Rule); MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours if (cmd.Rule.Name == null) copy.Name = _settings.MetaRules[cmd.Index].Name; _settings.MetaRules.Insert(cmd.Index + 1, copy); - TryAutoSaveMetaCmd(); + TryAutoSaveMetaCmd($"duplicate_rule {cmd.Index + 1}"); } break; case "set_rule_enabled": - if (cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) - { - _settings.MetaRules[cmd.Index].Enabled = - string.Equals(cmd.Value, "true", System.StringComparison.OrdinalIgnoreCase); - TryAutoSaveMetaCmd(); - } + if (!HasRule(cmd.Index)) { RefuseEdit(op, NoSuchRule(cmd.Index)); break; } + _settings.MetaRules[cmd.Index].Enabled = + string.Equals(cmd.Value, "true", System.StringComparison.OrdinalIgnoreCase); + TryAutoSaveMetaCmd($"set_rule_enabled {cmd.Index + 1}"); + break; + + default: + _host.Log($"[RynthAi] Meta: unknown command '{op}' from the Meta panel ignored."); break; } } - catch { } + catch (System.Exception ex) + { + // Used to be swallowed: an edit that threw looked like one that saved. + _metaSaver.Refuse($"Edit not applied ({op}): {ex.GetType().Name}: {ex.Message}", op); + } } + private bool HasRule(int index) => index >= 0 && index < _settings.MetaRules.Count; + + private string NoSuchRule(int index) => + $"rule {index + 1} isn't in the meta any more (it has {_settings.MetaRules.Count}); the list was out of date, reopen the rule"; + + /// A rule command that changed nothing: said in the panel's status and the log, never silent. + private void RefuseEdit(string op, string why) => _metaSaver.Refuse($"Edit not applied: {why}.", op); + /// The nearest rule before (-1) or after (+1) in the same state, or -1. private int SameStateNeighbour(int index, int direction) { @@ -3686,23 +3800,15 @@ internal sealed partial class LegacyDashboardRenderer return -1; } - private void TryAutoSaveMetaCmd() + /// Writes the meta file after a rule command changed the rules (MetaSaver: logged, and the + /// result goes to the panel in the snapshot's saveResult). + private void TryAutoSaveMetaCmd(string change) { _settings.MetaRulesStructuralVersion++; // editor mutation → rebuild meta index - if (string.IsNullOrEmpty(_settings.CurrentMetaPath)) return; - try - { - string path = _settings.CurrentMetaPath; - if (System.IO.Path.GetExtension(path).Equals(".met", System.StringComparison.OrdinalIgnoreCase)) - { - path = System.IO.Path.ChangeExtension(path, ".af"); - _settings.CurrentMetaPath = path; - _host.WriteToChat($"[RynthAi] Converted .met → {System.IO.Path.GetFileName(path)} for editing (original .met left untouched).", 1); - } - lock (_settings.MetaRulesLock) - DataWriteGuard.TrySave("the meta", path, () => AfFileWriter.Save(path, _settings.MetaRules, _settings.EmbeddedNavs)); - } - catch { } + bool wasMet = System.IO.Path.GetExtension(_settings.CurrentMetaPath ?? "").Equals(".met", System.StringComparison.OrdinalIgnoreCase); + _metaSaver.SaveCurrent(change); + if (wasMet && _metaSaver.LastOk) + _host.WriteToChat($"[RynthAi] Converted .met → {System.IO.Path.GetFileName(_settings.CurrentMetaPath)} for editing (original .met left untouched).", 1); } private static MetaRule DtoToMetaRule(MetaRuleDto dto) diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs index 13d9151..53d151d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs @@ -63,8 +63,12 @@ internal sealed class LegacyMetaUi { _settings = settings; _navFiles = navFiles; + Saver = new MetaSaver(settings, null); } + /// Writes the meta file and keeps the result (the dashboard passes its own, which logs). + internal MetaSaver Saver { get; set; } + public void Render() { if (!DashWindows.ShowMacroRules) return; @@ -1078,7 +1082,11 @@ internal sealed class LegacyMetaUi _openSavePopup = true; // Status message - if (!string.IsNullOrEmpty(_statusMessage) && (RynthClock.Now - _statusTime).TotalSeconds < 5) + // A save that failed (or an edit that wasn't written) stays up, in red, until the next result. + bool unsaved = !Saver.LastOk && Saver.Seq > 0 && ReferenceEquals(_statusMessage, Saver.LastText); + if (unsaved) + SafeImGui.TextColored(new Vector4(1, 0.35f, 0.35f, 1), _statusMessage); + else if (!string.IsNullOrEmpty(_statusMessage) && (RynthClock.Now - _statusTime).TotalSeconds < 5) SafeImGui.TextColored(new Vector4(0, 1, 0, 1), _statusMessage); // Save popup @@ -1155,6 +1163,8 @@ internal sealed class LegacyMetaUi _settings.EmbeddedNavs.Clear(); } _settings.CurrentMetaPath = string.Empty; + _settings.MetaUnsaved = false; + Saver.Note("Macro cleared.", string.Empty); _settings.CurrentState = "Default"; _settings.ForceStateReset = true; _statusMessage = "Macro cleared."; @@ -1201,6 +1211,8 @@ internal sealed class LegacyMetaUi _settings.ForceStateReset = true; _settings.MetaCallStackReset = true; _settings.CurrentMetaPath = filePath; + _settings.MetaUnsaved = false; // the rules are the file's now + Saver.Note($"Loaded {Path.GetFileName(filePath)}", filePath); // an old save failure isn't this meta's string name = Path.GetFileNameWithoutExtension(filePath); int stateCount = loaded.Rules.Select(r => r.State).Distinct(StringComparer.OrdinalIgnoreCase).Count(); @@ -1231,32 +1243,20 @@ internal sealed class LegacyMetaUi } + /// Writes the meta file after an edit here (MetaSaver: logged); the status line says + /// whether it was saved, or why not (used to say nothing either way). private void TryAutoSaveMeta() { _settings.MetaRulesStructuralVersion++; // editor mutation → rebuild meta index - if (string.IsNullOrEmpty(_settings.CurrentMetaPath)) - return; - - try - { - string path = _settings.CurrentMetaPath; - - // .met files can't be written — save as .af alongside - if (Path.GetExtension(path).Equals(".met", StringComparison.OrdinalIgnoreCase)) - { - path = Path.ChangeExtension(path, ".af"); - _settings.CurrentMetaPath = path; - _statusMessage = $"Converted .met → {Path.GetFileName(path)} for editing (original .met left untouched)"; - _statusTime = RynthClock.Now; - } - - lock (_settings.MetaRulesLock) - RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the meta", path, - () => AfFileWriter.Save(path, _settings.MetaRules, _settings.EmbeddedNavs)); - } - catch { } + // .met files can't be written: SaveCurrent saves the .af alongside and switches to it. + Saver.SaveCurrent("Macro Rules edit"); + _statusMessage = Saver.LastText; + _statusTime = RynthClock.Now; } + /// The status line's text now (the last load, save or refusal; empty after a few seconds). + internal string StatusLine => _statusMessage ?? string.Empty; + private void SaveMacroFile() { try @@ -1269,19 +1269,14 @@ internal sealed class LegacyMetaUi } string filePath = Path.Combine(MetaFolder, _saveName + ".af"); - bool saved; - string why; - lock (_settings.MetaRulesLock) - saved = RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the meta", filePath, - () => AfFileWriter.Save(filePath, _settings.MetaRules, _settings.EmbeddedNavs), out why); - if (!saved) + if (!Saver.SaveTo(filePath, "Macro Rules Save")) { - _statusMessage = $"Couldn't save {filePath}: {why}"; + _statusMessage = Saver.LastText; _statusTime = RynthClock.Now; return; } - _statusMessage = $"Saved to {_saveName}.af"; + _statusMessage = Saver.LastText; _statusTime = RynthClock.Now; RefreshMacroFileList(); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 7769dbd..af4a22b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -87,6 +87,10 @@ public sealed class LegacyUiSettings public string CurrentNavPath = string.Empty; public string CurrentLootPath = string.Empty; public string CurrentMetaPath = string.Empty; + /// The meta's rules here differ from its file: the last save of an edit failed + /// (MetaSaver). At login this profile's copy of the rules is then used instead of the file's, + /// so the edit isn't lost; the next successful save clears it. + public bool MetaUnsaved; public int MacroSettingsIdx = 1; public int NavProfileIdx = 1; @@ -136,7 +140,7 @@ public sealed class LegacyUiSettings public int LootOpenRetryMs = LootBaseline.OpenRetryMs; public int LootCorpseTimeoutMs = LootBaseline.CorpseTimeoutMs; public bool LootJumpEnabled = false; - public int LootJumpHeight = 10; // 0–100; maps to 0.0–1.0 JumpNonAutonomous extent + public int LootJumpHeight = 10; // kept for old profiles and metas; jump-loot uses the keyboard tap jump (fixed height) public int SalvageOpenDelayFirstMs = 400; public int SalvageOpenDelayFastMs = 50; @@ -215,6 +219,18 @@ public sealed class LegacyUiSettings // when another is clearly better by Targeting. On by default; a profile saved before this // setting loads it as on. public bool TargetLock = true; + // Fight the monster I select (2026-11-01): a monster the PLAYER selects in game (a click, the + // radar, another plugin's Selection window) becomes the fight target ahead of the Targeting + // setting and the Priority tiers, until it dies, can't be reached, or the player selects + // another monster / deselects. The automatic form of /ra targetlock (CombatManager.SelectedTarget.cs). + // Off by default; a profile saved before this setting loads it as off. + public bool FightSelectedTarget; + internal const string FightSelectedTargetTip = + "On: in a fight, a monster YOU select (click it, or pick it on the radar or in a Selection window)\n" + + "is fought first, ahead of Targeting and Priority, until it dies, can't be reached, or you select\n" + + "another monster or deselect. The bot's own selections never count. Ignored (Priority 0) and\n" + + "never-attack monsters are not followed (/ra targetlock still forces them). Out to Disengage Range.\n" + + "/ra fightselected [on|off]"; public int RingRange = 5; // Obsolete since 2026-10-20 (unused here, kept so profiles still load and carry it): the Empyrean // Handler lethal-ring evade is Infinite Leaftide's and lives in RynthILT now (its ILT settings, @@ -302,6 +318,12 @@ public sealed class LegacyUiSettings /// Not read by the corpse looting (no rare-corpse check exists); kept so saved profiles /// round-trip. Hidden in Advanced Settings. The meta/MagTools option of that name sets Mine Only. public bool LootOnlyRareCorpses; + /// + /// Loot Mode (Loot.LootModes): 0 = Profile (the loot profile, the default), 1 = Rares and needed + /// mana stones only (the loot profile is not used; rares, and mana stones while the mana stone + /// keep count wants them). Per settings profile; the meta setting LootMode; /ra loot mode. + /// + public int LootMode; /// Also pick up loose ground items that match the loot profile, within the corpse max range. public bool EnableGroundLoot; public bool PeaceModeWhenIdle = true; @@ -1249,6 +1271,7 @@ public sealed class SettingsBridgePayload // Nullable: an engine that predates them doesn't send them, and its save must leave them alone. public int? TargetSelection { get; set; } public bool? TargetLock { get; set; } + public bool? FightSelectedTarget { get; set; } public int RingRange { get; set; } public int ApproachRange { get; set; } public double CorpseApproachRangeMax { get; set; } @@ -1337,6 +1360,7 @@ public sealed class SettingsBridgePayload public bool? LootOwnCorpse { get; set; } public bool? EscapeHazards { get; set; } public bool? TravelToOwnCorpse { get; set; } + public int? LootMode { get; set; } // Item info: describe an item in chat when it is selected (ItemInfoSettings.OnSelect). public bool? ItemInfoOnSelect { get; set; } public bool EnableAutostack { get; set; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaSaver.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaSaver.cs new file mode 100644 index 0000000..3c26f1c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaSaver.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +/// +/// Every write of the loaded meta's file (2026-11-01). Both editors save through here: the engine's +/// Meta panel (rule commands, TryAutoSaveMetaCmd; Save As, save_file) and RynthAi's own Macro Rules +/// window (TryAutoSaveMeta, SaveMacroFile). +/// +/// "Still having trouble editing metas and the changes not saving": none of the meta saves logged +/// anything, a save that didn't happen (no file, a rule index the meta no longer has, a command +/// that threw) returned without a word, and the engine panel showed "Saved" two and a half seconds +/// after every change whatever happened. Now each attempt has one result: +/// - saved: one log line (path, rule and state count) and "Saved name (N rules)"; +/// - failed or refused: one log line and a status that says why (the file couldn't be written, +/// the meta has no file, the rule isn't there any more...). +/// The engine panel reads the last result from the meta snapshot ("saveResult", by sequence number), +/// so its indicator says what really happened; the Macro Rules window shows it in its status line. +/// A failed write also marks the profile's copy of the rules as the newer one +/// (; see LegacyDashboardRenderer.SyncMetaWithFile). +/// +internal sealed class MetaSaver +{ + private readonly LegacyUiSettings _settings; + private readonly Action? _log; + + public MetaSaver(LegacyUiSettings settings, Action? log) + { + _settings = settings; + _log = log; + } + + /// Counts results (0 = nothing tried yet this session). + public long Seq { get; private set; } + public bool LastOk { get; private set; } = true; + /// What the last attempt did, in a few words ("Saved farm.af (12 rules)", "NOT saved: ..."). + public string LastText { get; private set; } = string.Empty; + /// The file the last attempt wrote or meant to write (empty: none). + public string LastPath { get; private set; } = string.Empty; + + /// + /// Writes the loaded meta () after an edit. A .met is + /// saved as the .af beside it (the .met is never written) and the meta switches to that .af. + /// names the edit for the log ("update_rule 4"). + /// + public bool SaveCurrent(string change) + { + string path = _settings.CurrentMetaPath ?? string.Empty; + if (path.Length == 0) + return Refuse("Not saved: this meta has no file yet. Save As names one; after that every change saves on its own.", change); + string note = string.Empty; + if (Path.GetExtension(path).Equals(".met", StringComparison.OrdinalIgnoreCase)) + { + path = Path.ChangeExtension(path, ".af"); + _settings.CurrentMetaPath = path; + note = $" (converted from the .met, which is left untouched)"; + } + return SaveTo(path, change, note); + } + + /// Writes the rules to . is added to the status. + /// : the caller puts a failure in chat itself (DataWriteGuard queues nothing). + public bool SaveTo(string path, string change, string note = "", bool callerShows = false) + { + int rules = 0, states = 0; + bool ok; + string why; + lock (_settings.MetaRulesLock) + { + rules = _settings.MetaRules.Count; + states = _settings.MetaRules.Select(r => r.State ?? "Default").Distinct(StringComparer.OrdinalIgnoreCase).Count(); + ok = DataWriteGuard.TrySave("the meta", path, + () => AfFileWriter.Save(path, _settings.MetaRules, _settings.EmbeddedNavs), out why, callerShows); + } + string name = Path.GetFileName(path); + if (ok) + { + _settings.MetaUnsaved = false; + Record(true, $"Saved {name} ({rules} rule{(rules == 1 ? "" : "s")}){note}", path); + Log($"[RynthAi] Meta saved: {path} ({rules} rules, {states} states; {change}){note}"); + return true; + } + _settings.MetaUnsaved = true; + Record(false, $"NOT saved to {name}: {why}", path); + Log($"[RynthAi] Meta NOT saved: {path} ({change}): {why}"); + return false; + } + + /// An edit that wasn't applied or written, and why. Logged and shown like a failed save. + public bool Refuse(string text, string change) + { + Record(false, text, _settings.CurrentMetaPath ?? string.Empty); + Log($"[RynthAi] Meta {change}: {text}"); + return false; + } + + /// A command that needed no write (a move at the end of its state) or a load: a result, + /// so the engine panel isn't left waiting for one. Not logged. + public void Note(string text, string path) => Record(true, text, path); + + private void Record(bool ok, string text, string path) + { + Seq++; + LastOk = ok; + LastText = text; + LastPath = path; + } + + private void Log(string line) + { + try { _log?.Invoke(line); } catch { } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootModes.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootModes.cs new file mode 100644 index 0000000..1f6c7d1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootModes.cs @@ -0,0 +1,88 @@ +using System.Globalization; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.Loot; + +/// +/// The loot mode (Settings > Looting, Loot Mode; meta setting LootMode; /ra loot mode). Profile is +/// the loot profile with RynthAi's built-in keeps, as always. Rares (owner, 2026-10-31: "a loot mode +/// that only loots mana stones when it needs them and rares") ignores the loot profile: corpses, +/// chests and ground items give up their rares and the mana stones the mana stone keep count still +/// wants, nothing else. +/// +internal static class LootModes +{ + public const int Profile = 0, Rares = 1; + + /// The Loot Mode combo's entries, by mode. + public static readonly string[] Labels = { "Profile", "Rares and needed mana stones only" }; + + /// A rule label in rares mode starts with this (LootChatLine shows it bare). + public const string RulePrefix = "Rares mode: "; + public const string RareRule = RulePrefix + "rare"; + public const string StoneRule = RulePrefix + "mana stone (needed)"; + + public static int Clamp(int mode) => mode == Rares ? Rares : Profile; + + public static bool IsRares(int mode) => mode == Rares; + + /// The command word: "profile" or "rares". + public static string Word(int mode) => IsRares(mode) ? "rares" : "profile"; + + /// The mode for a chat line: "Profile (the loot profile)" or "Rares and needed mana stones only". + public static string Describe(int mode) => IsRares(mode) ? Labels[Rares] : "Profile (the loot profile)"; + + /// profile | rares (also rare, and the numbers 0 and 1 a meta sends), any case. + public static bool TryParse(string? text, out int mode) + { + mode = Profile; + string t = (text ?? string.Empty).Trim().ToLowerInvariant(); + switch (t) + { + case "profile": mode = Profile; return true; + case "rares": case "rare": mode = Rares; return true; + } + if (double.TryParse(t, NumberStyles.Float, CultureInfo.InvariantCulture, out double n) && (n == Profile || n == Rares)) + { + mode = (int)n; + return true; + } + return false; + } +} + +/// +/// What makes an item a rare, on the client. Two marks, the same ones AutoVendor's never-sell +/// check uses: +/// * IconUnderlay (PropertyDataId 52) = 0x06005B0C, the rare plate behind the icon (UtilityBelt's +/// test). It is in the item's PublicWeenieDesc, so the create message carries it: a rare on a +/// corpse is known before any ID. +/// * RareId (PropertyInt 17) above 0. ACE sends it only with an appraisal (an AssessmentProperty), +/// so it decides only for an identified item. +/// +internal static class RareItems +{ + public const int RareIdKey = 17; + public const uint IconUnderlayKey = 52; + public const uint RareUnderlay = 23308; // 0x5B0C, the low 24 bits of 0x06005B0C + + /// True for a rare; says which mark showed it. + public static bool IsRare(RynthCoreHost host, WorldObject item, out string how) + { + how = string.Empty; + int rareId = item.Values(RareIdKey, 0); + if (rareId > 0) + { + how = "RareId " + rareId.ToString(CultureInfo.InvariantCulture); + return true; + } + if (host.HasGetObjectDataIdProperty + && host.TryGetObjectDataIdProperty(unchecked((uint)item.Id), IconUnderlayKey, out uint underlay) + && (underlay & 0x00FFFFFFu) == RareUnderlay) + { + how = "rare icon"; + return true; + } + return false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs index 0e08170..1a88392 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs @@ -5,7 +5,8 @@ namespace RynthCore.Plugin.RynthAi.Loot; /// /// /ra loot why: which rule of a VTank profile takes an item, and why the rules above it -/// didn't. Pure (no chat, no host calls beyond the context's reads), so tests can run it. +/// didn't, and the words for it (chat and the "Why this loot rule?" window). Pure (no chat, +/// no host calls beyond the context's reads), so tests can run it. /// internal static class LootWhy { @@ -20,6 +21,13 @@ internal static class LootWhy public string RuleName { get; init; } = string.Empty; public VTankLootAction Action { get; init; } public List NearMisses { get; } = new(); + /// + /// The first switched-off rule above the decision that would take the item if it were on + /// (), or -1. Only with the ID in. + /// + public int SwitchedOffIndex { get; init; } = -1; + public string SwitchedOffName { get; init; } = string.Empty; + public VTankLootAction SwitchedOffAction { get; init; } } public static string NameOf(VTankLootRule rule, int index) @@ -34,12 +42,17 @@ internal static class LootWhy public static Result Explain(VTankLootProfile profile, WorldObject item, VTankLootContext? ctx, bool hasIdData) { VTankLootVerdict verdict = VTankLootEvaluator.Decide(profile, item, ctx, hasIdData, out int index); + // Without the ID its stats read 0, so a switched-off rule can't be judged yet. + int off = hasIdData ? VTankLootEvaluator.FirstSwitchedOffMatch(profile, item, ctx, index) : -1; var result = new Result { Verdict = verdict, Index = index, RuleName = index >= 0 ? NameOf(profile.Rules[index], index) : string.Empty, Action = index >= 0 ? profile.Rules[index].Action : default, + SwitchedOffIndex = off, + SwitchedOffName = off >= 0 ? NameOf(profile.Rules[off], off) : string.Empty, + SwitchedOffAction = off >= 0 ? profile.Rules[off].Action : default, }; int end = index >= 0 ? index : profile.Rules.Count; @@ -63,6 +76,106 @@ internal static class LootWhy return result; } + /// + /// What /ra loot why answers and the "Why this loot rule?" window shows (immutable, so the + /// tick can hand it to the render thread). false: says + /// why there is no answer. : what the looter does with it ("[Keep] rule", + /// "left"). : a VTank profile, so names its + /// rule and lists the rules above it that came close. + /// + public sealed record Report(bool Ok, string Error, string ItemName, bool HasId, string Looter, string Decision, + bool RuleDetail, bool AskedForId, IReadOnlyList NearMisses) + { + public static Report Fail(string why) => + new(false, why, string.Empty, false, string.Empty, string.Empty, false, false, System.Array.Empty()); + + /// "'Item' (identified) -> [Keep] rule". + public string Headline => Ok ? $"'{ItemName}' ({IdNote(HasId)}) -> {Looter}" : Error; + + /// + /// A switched-off rule above the decision would take the item ("#12 '(W) War (Max 385)' [Keep]"), + /// or empty. Said ahead of the near misses: it is the usual answer to "why was this left?" + /// when the profile has the rule but it's off. + /// + public string SwitchedOff { get; init; } = string.Empty; + } + + /// "Switched off in the profile: #12 '(W) War (Max 385)' [Keep] would take it." + public static string SwitchedOffLine(string switchedOff) => + $"Switched off in the profile: {switchedOff} would take it. Switch that rule on in the Loot Editor to loot items like this."; + + /// "identified" / "not identified yet". + public static string IdNote(bool hasId) => hasId ? "identified" : "not identified yet"; + + /// + /// The report for : the looter's own verdict (: + /// "[Keep] rule" or "left", with a built-in keep), then, with (a VTank + /// profile, with rules), the rule that decides. + /// + public static Report Describe(string itemName, bool hasId, string looter, string file, int ruleCount, Result? why, bool askedForId) + { + if (why == null) + return new Report(true, string.Empty, itemName, hasId, looter, string.Empty, false, false, System.Array.Empty()); + string rule = why.Index >= 0 ? $"rule {why.Index + 1} of {ruleCount} '{why.RuleName}'" : string.Empty; + string decision = why.Verdict switch + { + VTankLootVerdict.Match => $"{file}: {rule} [{why.Action}]", + VTankLootVerdict.NeedsId => $"{file}: {rule} needs the item's ID to decide", + _ => $"{file}: no rule matches", + }; + string off = why.SwitchedOffIndex >= 0 ? $"#{why.SwitchedOffIndex + 1} '{why.SwitchedOffName}' [{why.SwitchedOffAction}]" : string.Empty; + return new Report(true, string.Empty, itemName, hasId, looter, decision, true, askedForId, why.NearMisses.ToArray()) + { + SwitchedOff = off, + }; + } + + /// + /// The report when the Loot Mode, not the profile, decides (rares mode): the looter's verdict + /// and , shown in place of the rule-by-rule detail. + /// + public static Report ModeOnly(string itemName, bool hasId, string looter, string modeNote) => + new(true, string.Empty, itemName, hasId, looter, modeNote, false, false, System.Array.Empty()); + + /// + /// /ra loot why's chat lines for , at most + /// near misses (the rest are counted; the log has them all). A failed report is one line. + /// + public static List ChatLines(Report r, int maxNearMisses) + { + var lines = new List(); + if (!r.Ok) + { + lines.Add("[RynthAi] loot why: " + r.Headline); + return lines; + } + if (!r.RuleDetail) + { + lines.Add(r.Decision.Length > 0 + ? $"[RynthAi] Loot why: {r.Headline}. {r.Decision}." + : $"[RynthAi] Loot why: {r.Headline}. (Rule-by-rule detail is for VTank .utl profiles.)"); + return lines; + } + lines.Add("[RynthAi] Loot why: " + r.Headline); + lines.Add("[RynthAi] " + r.Decision); + if (r.AskedForId) lines.Add("[RynthAi] Asked for its ID; /ra loot why again once it's in."); + if (r.SwitchedOff.Length > 0) lines.Add("[RynthAi] " + SwitchedOffLine(r.SwitchedOff)); + if (r.NearMisses.Count == 0) + { + lines.Add("[RynthAi] No rule above it came close (each failed on its first condition)."); + return lines; + } + lines.Add($"[RynthAi] {r.NearMisses.Count} rule(s) above it came close; the first condition each failed:"); + for (int i = 0; i < r.NearMisses.Count && i < maxNearMisses; i++) + lines.Add("[RynthAi] " + NearMissLine(r.NearMisses[i])); + if (r.NearMisses.Count > maxNearMisses) + lines.Add($"[RynthAi] ... {r.NearMisses.Count - maxNearMisses} more in the log ([LootWhy] lines)."); + return lines; + } + + /// "#3 'Good bows': ..." (chat, the log and the window). + public static string NearMissLine(NearMiss m) => $"#{m.Index + 1} '{m.RuleName}': {m.Failed}"; + private static bool IsDisabled(VTankLootRule rule) { foreach (VTankLootCondition c in rule.Conditions) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhyWindow.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhyWindow.cs new file mode 100644 index 0000000..9cba4f6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhyWindow.cs @@ -0,0 +1,130 @@ +// ============================================================================ +// RynthAi - Loot/LootWhyWindow.cs +// "Why this loot rule?" (2026-10-31, the owner: buttons on the UI, not only +// commands): /ra loot why's answer in a small window, opened by the Loot +// Editor's and the Classic Loot tab's "Why this loot rule?" buttons, the +// Selection window's right-click menu (RynthDefective) and /ra loot why window. +// +// the item its name, identified or not, and what the looter does with it +// the rule for a VTank profile: the rule that takes it (or none), then +// every rule above it that came close and the first condition +// each failed, with the value it read +// Check again asks again for whatever is selected now (an ID that came in, +// another item); Close. +// +// AC's render thread: it draws the report the tick built (LootWhy.Report, an +// immutable record) and queues Check again for the tick. Looks: Shared/RynthUi. +// ============================================================================ +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; +using RynthCore.Plugin.Shared.RynthUi; +using RynthCore.PluginSdk; +using static RynthCore.Plugin.Shared.RynthUi.RynthUi; + +namespace RynthCore.Plugin.RynthAi.Loot; + +internal sealed class LootWhyWindow +{ + public const string Title = "Why this loot rule?##rynthai_lootwhy"; + + private readonly Action _checkAgain; + + public LootWhyWindow(Action checkAgain) => _checkAgain = checkAgain; + + /// Draws the window for ; goes false when it is closed. Render thread. + public void Render(LootWhy.Report r, ref bool open) + { + float k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f); + float wrap = 440 * k; + Vector2 mouse = ImGui.GetIO().MousePos, display = ImGui.GetIO().DisplaySize; + // Where it was asked for (the button under the mouse), kept on the screen. + ImGui.SetNextWindowPos(new Vector2(Math.Clamp(mouse.X + 12, 0, Math.Max(0, display.X - wrap - 30)), + Math.Clamp(mouse.Y + 12, 0, Math.Max(0, display.Y - 260 * k))), ImGuiCond.Appearing); + + ImGui.PushStyleColor(ImGuiCol.WindowBg, WithAlpha(Background, 0xF2)); + ImGui.PushStyleColor(ImGuiCol.TitleBg, Color(RynthUiColor.TitleBar)); + ImGui.PushStyleColor(ImGuiCol.TitleBgActive, Color(RynthUiColor.TitleBar)); + ImGui.PushStyleColor(ImGuiCol.Border, Accent); + ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGui.PushStyleColor(ImGuiCol.ChildBg, Field); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10 * k, 8 * k)); + bool visible = ImGui.Begin(Title, ref open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoSavedSettings); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(6); + if (!visible) { ImGui.End(); return; } + try + { + using (PushFont(RynthUiFont.Ui11)) + { + ImGui.PushTextWrapPos(ImGui.GetCursorPosX() + wrap); + Body(r, wrap); + ImGui.PopTextWrapPos(); + Buttons(ref open, k); + } + } + finally { ImGui.End(); } + } + + private static void Body(LootWhy.Report r, float wrap) + { + if (!r.Ok) + { + Label(Sentence(r.Error), Highlight); + return; + } + using (PushFont(RynthUiFont.UiBold11)) Label(r.ItemName, Accent); + Label(r.HasId ? "Identified." : "Not identified yet: rules that read its ID details can't decide.", Mute); + ImGui.Dummy(new Vector2(0, 2)); + ImGui.TextUnformatted("The looter: " + r.Looter); + if (!r.RuleDetail) + { + Label(r.Decision.Length > 0 ? r.Decision + "." + : "Rule-by-rule detail is for VTank .utl profiles; this profile is RynthAi's own (.json).", Mute); + return; + } + ImGui.TextUnformatted("The profile: " + r.Decision); + if (r.AskedForId) Label("Asked the server for its ID: Check again once it's in.", Highlight); + if (r.SwitchedOff.Length > 0) Label(LootWhy.SwitchedOffLine(r.SwitchedOff), Highlight); + ImGui.Dummy(new Vector2(0, 4)); + if (r.NearMisses.Count == 0) + { + Label("No rule above it came close (each failed on its first condition).", Mute); + return; + } + Label(r.NearMisses.Count == 1 + ? "1 rule above it came close; the first condition it failed:" + : r.NearMisses.Count.ToString(CultureInfo.InvariantCulture) + " rules above it came close; the first condition each failed:", Mute); + // A long list scrolls; a short one is as tall as it needs. + float lineH = ImGui.GetTextLineHeightWithSpacing(); + float h = Math.Min(r.NearMisses.Count * lineH * 1.6f + 8, lineH * 12); + ImGui.BeginChild("##lootwhy_misses", new Vector2(wrap, h), ImGuiChildFlags.Borders); + ImGui.PushTextWrapPos(0); + foreach (LootWhy.NearMiss m in r.NearMisses) + SafeImGui.TextWrapped(LootWhy.NearMissLine(m)); + ImGui.PopTextWrapPos(); + ImGui.EndChild(); + } + + private void Buttons(ref bool open, float k) + { + ImGui.Dummy(new Vector2(0, 4 * k)); + Vector2 p = ImGui.GetCursorScreenPos(); + float h = 22 * k; + const string Again = "Check again", Close = "Close"; + float aw = ButtonWidth(Again), cw = ButtonWidth(Close); + if (Button("##lootwhy_again", Again, p, new Vector2(aw, h), Text, AccentFill)) + _checkAgain(); + SafeImGui.SetItemTooltip("Ask again for the item selected now (select another one first, or wait for its ID). Also: /ra loot why"); + if (Button("##lootwhy_close", Close, new Vector2(p.X + aw + 6 * k, p.Y), new Vector2(cw, h), Text, ButtonFill)) + open = false; + ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h)); + ImGui.Dummy(new Vector2(aw + cw + 6 * k, 2 * k)); + } + + /// "select an item first" -> "Select an item first". + private static string Sentence(string s) => + s.Length == 0 ? s : char.ToUpperInvariant(s[0]) + s.Substring(1); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/PackRefusals.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/PackRefusals.cs index 6cff4c1..6e1cabd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/PackRefusals.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/PackRefusals.cs @@ -17,25 +17,44 @@ namespace RynthCore.Plugin.RynthAi.Loot; /// dropped when the item is done (). Quick unanswered retries /// on a slow server had marked one good pack after another full for 5 min, until looting /// "locked up" with nothing left to put loot into. +/// +/// 2026-11-01 (#rynth-issues "Stopped looting", Conquest treasure maps with pickup timers): an +/// item the server refuses for itself, not for room, was refused by every pack it tried, and +/// each one was marked full: the next item had nowhere to go, so it was selected and never +/// picked up, corpse after corpse. A confirmed mark remembers the item whose refusals made it; +/// an item refused in two or more packs takes its marks back with it (). +/// A pack another item was refused in as well stays marked: then it is the pack. /// internal sealed class PackRefusals { /// How long a refusing pack is left out (time to free some room, or open it). public const long HoldMs = 5 * 60_000; - private readonly Dictionary _until = new(); + // Item: the one item whose refusals made the mark; 0 = more than one item's (or not said). + private readonly Dictionary _until = new(); + // Marks taken back with their item (Withdraw): another item refused there too confirms the pack. + private readonly Dictionary _withdrawn = new(); /// /// The server took none of the tries into . : /// it said so (refusals after the pickup ran); false: the tries went unanswered. A confirmed - /// mark is never weakened by a later unconfirmed one. + /// mark is never weakened by a later unconfirmed one. : the item + /// refused (0: not said, the mark is never withdrawn). /// - public void Refuse(int packId, long nowMs, bool confirmed = true) + public void Refuse(int packId, long nowMs, bool confirmed = true, int itemId = 0) { if (packId == 0) return; - if (_until.TryGetValue(packId, out var old) && old.Confirmed && !confirmed && nowMs < old.Until) - return; - _until[packId] = (nowMs + HoldMs, confirmed); + int by = itemId; + if (_until.TryGetValue(packId, out var old) && nowMs < old.Until) + { + if (old.Confirmed && !confirmed) + return; + if (old.Confirmed && old.Item != itemId) + by = 0; // another item was refused here too + } + if (confirmed && by != 0 && _withdrawn.TryGetValue(packId, out var w) && nowMs < w.Until && w.Item != itemId) + by = 0; // so was the item that took its mark back + _until[packId] = (nowMs + HoldMs, confirmed, by); } /// True while is left out. @@ -52,7 +71,30 @@ internal sealed class PackRefusals IsRefused(packId, nowMs) && _until.TryGetValue(packId, out var mark) && mark.Confirmed; /// An item landed in : it has room after all. - public void Accepted(int packId) => _until.Remove(packId); + public void Accepted(int packId) + { + _until.Remove(packId); + _withdrawn.Remove(packId); + } + + /// + /// The server refused in every pack it tried: it is refusing the item, + /// not the packs. Takes back the confirmed marks that item's refusals alone made and returns + /// those packs (a mark another item's refusals back as well stays). + /// + public List Withdraw(int itemId, long nowMs) + { + var packs = new List(); + if (itemId == 0) return packs; + foreach (var kv in _until) + if (kv.Value.Confirmed && kv.Value.Item == itemId && nowMs < kv.Value.Until) packs.Add(kv.Key); + foreach (int id in packs) + { + _until.Remove(id); + _withdrawn[id] = (nowMs + HoldMs, itemId); + } + return packs; + } /// Drops the marks no refusal backed (the item that made them is done). public void ClearUnconfirmed() @@ -65,5 +107,9 @@ internal sealed class PackRefusals foreach (int id in drop) _until.Remove(id); } - public void Clear() => _until.Clear(); + public void Clear() + { + _until.Clear(); + _withdrawn.Clear(); + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs index cd9ac03..1241247 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs @@ -232,6 +232,41 @@ public static class VTankLootEvaluator return VTankLootVerdict.NoMatch; } + /// + /// The first switched-off rule before (-1: all of them) that would take + /// the item if it were on: every condition but its DisabledRule node passes, the item's ID taken + /// as in. -1 when none would. A rule that is only a DisabledRule node (LootSnob's "leave this + /// disabled" separators have a name condition too) never counts. For /ra loot why and the + /// looter's log: a wand left because "(W) War (Max 385)" is switched off in the player's copy of + /// LootSnob read the same as one no rule wants (2026-11-01). : Keep + /// and Keep # rules only (LootSnob ships its Salvage rules off, so nearly every item with a + /// material has a switched-off Salvage rule that would take it). + /// + public static int FirstSwitchedOffMatch(VTankLootProfile profile, WorldObject? item, VTankLootContext? ctx, int end = -1, bool keepsOnly = false) + { + if (item is null) return -1; + uint itemId = unchecked((uint)item.Id); + int stop = end < 0 || end > profile.Rules.Count ? profile.Rules.Count : end; + for (int i = 0; i < stop; i++) + { + VTankLootRule rule = profile.Rules[i]; + if (rule.Enabled) continue; + if (keepsOnly && rule.Action != VTankLootAction.Keep && rule.Action != VTankLootAction.KeepUpTo) continue; + bool any = false, failed = false; + foreach (var cond in rule.Conditions) + { + if (cond.NodeType == VTankNodeTypes.DisabledRule) continue; + any = true; + bool ok; + try { ok = Match(cond, item, itemId, ctx); } + catch { ok = false; } + if (!ok) { failed = true; break; } + } + if (any && !failed) return i; + } + return -1; + } + // STypeInts the CreateObject message carries (the engine answers them before any ID: // RynthCore PwdLayout.IntStypes). Everything else, workmanship (105) included, comes with the ID. private static readonly HashSet CreateIntKeys = new() diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index 191ab43..64c8fd8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3677,6 +3677,7 @@ internal sealed partial class ExpressionEngine // Targeting: 0 lowest health, 1 closest, 2 farthest, 3 least turning. ["TargetSelection"] = (() => I(s.TargetSelection), v => { if (int.TryParse(v, out int i)) s.TargetSelection = Math.Clamp(i, 0, 3); }), ["TargetLock"] = (() => B(s.TargetLock), v => s.TargetLock = ToDouble(v) != 0), + ["FightSelectedTarget"] = (() => B(s.FightSelectedTarget), v => s.FightSelectedTarget = ToDouble(v) != 0), ["RingRange"] = (() => I(s.RingRange), v => { if (int.TryParse(v, out int i)) s.RingRange = i; }), ["ApproachRange"] = (() => I(s.ApproachRange), v => { if (int.TryParse(v, out int i)) s.ApproachRange = i; }), ["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }), @@ -3740,6 +3741,8 @@ internal sealed partial class ExpressionEngine ["NavGuideLine"] = (() => B(s.NavGuideLine), v => s.NavGuideLine = ToDouble(v) != 0), ["CurrentNavPath"] = (() => s.CurrentNavPath, v => s.CurrentNavPath = v), ["CurrentLootPath"] = (() => s.CurrentLootPath, v => s.CurrentLootPath = v), + // Loot Mode: 0 = profile, 1 = rares and needed mana stones only (the words work too). + ["LootMode"] = (() => I(Loot.LootModes.Clamp(s.LootMode)), v => { if (Loot.LootModes.TryParse(v, out int m)) s.LootMode = m; }), ["CurrentMetaPath"] = (() => s.CurrentMetaPath, v => s.CurrentMetaPath = v), ["OpenDoors"] = (() => B(s.OpenDoors), v => s.OpenDoors = ToDouble(v) != 0), ["NavRecoveryEnabled"] = (() => B(s.NavRecoveryEnabled), v => s.NavRecoveryEnabled = ToDouble(v) != 0), diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 6b779dd..8490fd7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -125,6 +125,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra lootcheckinv — test the loot profile against inventory"); ChatLine("[RynthAi] /ra lootcheck — classify selected item (on|off = auto on click)"); ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't"); + ChatLine("[RynthAi] /ra loot mode [profile|rares] — loot by the loot profile, or rares and needed mana stones only"); ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item"); ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)"); ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot"); @@ -1511,6 +1512,25 @@ public sealed partial class RynthAiPlugin RynthLog.Write(LogCat.Looting, countMessage); } + // A rule with no conditions is unconditional (VTank's too): it takes every item that reaches + // it. R-20261101-133624-7eeb (Conquest, 2026-11-01): every item on every corpse was kept by + // 'Trade Note', which in LootSnob is a Name match; one that has lost its condition does + // exactly that, silently. Said at load, with where it stands, so it can be fixed. + var unconditional = profile.Rules + .Select((r, i) => (Rule: r, Index: i)) + .Where(x => x.Rule.Conditions.Count == 0) // a disabled rule carries a DisabledRule node, so it isn't one + .ToList(); + if (unconditional.Count > 0) + { + var first = unconditional[0]; + string names = string.Join(", ", unconditional.Take(3).Select(x => $"'{(string.IsNullOrWhiteSpace(x.Rule.Name) ? "#" + (x.Index + 1) : x.Rule.Name.Trim())}' (rule {x.Index + 1}, {x.Rule.Action})")); + string uncMessage = $"[RynthAi] Loot profile '{fileName}': {unconditional.Count} rule(s) have no conditions, so they take every item that reaches them: {names}" + + (unconditional.Count > 3 ? $" and {unconditional.Count - 3} more" : "") + + $". Every item that no rule above rule {first.Index + 1} takes will be {first.Rule.Action}. Add a condition in the Loot Editor, or disable the rule."; + ChatLine(uncMessage); + RynthLog.Write(LogCat.Looting, uncMessage); + } + var bad = new List(); foreach (VTankLootRule rule in profile.Rules) { @@ -1700,15 +1720,27 @@ public sealed partial class RynthAiPlugin string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty; if (sub == "why") { - HandleLootWhyCommand(); + string how = parts.Length >= 4 ? parts[3].ToLowerInvariant() : string.Empty; + if (how.Length > 0 && how is not ("window" or "show")) + { + ReplyFail($"[RynthAi] loot why: '{parts[3]}'? Usage: /ra loot why [window] (window: the answer in the Loot why window)."); + return; + } + HandleLootWhyCommand(window: how.Length > 0); + return; + } + if (sub == "mode") + { + HandleLootModeCommand(parts); return; } if (sub != "add") { - ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't"); + ChatLine("[RynthAi] /ra loot mode [profile|rares] — what is looted: the loot profile, or rares and needed mana stones only"); + ChatLine("[RynthAi] /ra loot why [window] — which loot rule takes the selected item, and why the rules above it didn't (window: in the Loot why window)"); ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use"); ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing."); - ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor."); + ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor; 'Why this loot rule?' there and on the Selection window's right-click."); return; } @@ -1756,70 +1788,129 @@ public sealed partial class RynthAiPlugin // An add's own chat line comes from OnLootRuleAdded. } + /// + /// /ra loot mode [profile|rares]: the Loot Mode (Loot.LootModes), saved with the settings + /// profile. No word: says the mode now. + /// + private void HandleLootModeCommand(string[] parts) + { + const string usage = "/ra loot mode profile|rares (profile: the loot profile; rares: rares and needed mana stones only)"; + var dash = _dashboard; + LegacyUiSettings? s = dash?.Settings; + if (s == null) { ReplyFail("[RynthAi] loot mode: settings aren't loaded yet (log in first). Usage: " + usage); return; } + if (parts.Length < 4) + { + ChatLine($"[RynthAi] Loot Mode: {LootModeLine(s)}. Usage: {usage}"); + return; + } + string arg = string.Join(" ", parts, 3, parts.Length - 3); + if (!Loot.LootModes.TryParse(arg, out int mode)) + { + ReplyFail($"[RynthAi] loot mode: '{arg}'? Loot Mode is still {LootModeLine(s)}. Usage: {usage}"); + return; + } + s.LootMode = mode; + dash!.SaveSettings(); + ReplyOk($"[RynthAi] Loot Mode: {LootModeLine(s)}."); + } + + /// The dashboard's LOOT picker set the Loot Mode. Plugin tick. + internal void SetLootModeFromPanel(int mode) + { + var dash = _dashboard; + LegacyUiSettings? s = dash?.Settings; + if (s == null) return; + mode = Loot.LootModes.Clamp(mode); + if (s.LootMode == mode) return; + s.LootMode = mode; + dash!.SaveSettings(); + ChatLine($"[RynthAi] Loot Mode: {LootModeLine(s)}."); + } + + /// The mode for a chat line, with what it means for the loot profile. + private static string LootModeLine(LegacyUiSettings s) + { + int mode = Loot.LootModes.Clamp(s.LootMode); + if (!Loot.LootModes.IsRares(mode)) return Loot.LootModes.Describe(mode); + string profile = string.IsNullOrEmpty(s.CurrentLootPath) ? "" : $"; the loot profile {System.IO.Path.GetFileName(s.CurrentLootPath)} is not used"; + return $"{Loot.LootModes.Describe(mode)} (mana stones up to the keep count, {s.ManaStoneKeepCount}{profile})"; + } + private const int LootWhyChatLines = 10; /// - /// /ra loot why: the selected item's loot decision, from the looter itself (built-in keeps and - /// Keep # caps included), then, for a VTank profile, the rule that takes it and, for the rules - /// above it that came close, the first condition that failed and the value it read. The full - /// list goes to the log. An item without its ID says which rule waits for it and asks for it. + /// /ra loot why [window]: the selected item's loot decision () in + /// chat, or (: window, the "Why this loot rule?" buttons) in the Loot why + /// window, which then says it all instead. /// - private void HandleLootWhyCommand() + private void HandleLootWhyCommand(bool window = false) { - if (!Host.HasGetSelectedItemId) { ReplyFail("[RynthAi] loot why: this engine can't tell RynthAi the selected item."); return; } + Loot.LootWhy.Report report = BuildLootWhyReport(window); + if (window) + { + // The window is the answer ("Why this loot rule?" buttons, /ra loot why window). + ShowLootWhyWindow(report); + return; + } + List lines = Loot.LootWhy.ChatLines(report, LootWhyChatLines); + if (!report.Ok) + { + ReplyFail(lines[0]); + return; + } + foreach (string line in lines) ChatLine(line); + } + + /// + /// The selected item's loot decision, from the looter itself (built-in keeps and Keep # caps + /// included), then, for a VTank profile, the rule that takes it and the rules above it that came + /// close (all of them in the log, [LootWhy] lines). An item without its ID: asks for it. + /// : for the window, so a failure says what to do there. Pump thread. + /// + private Loot.LootWhy.Report BuildLootWhyReport(bool window) + { + if (!Host.HasGetSelectedItemId) return Loot.LootWhy.Report.Fail("this engine can't tell RynthAi the selected item."); uint selected = Host.GetSelectedItemId(); - if (selected == 0) { ReplyFail("[RynthAi] loot why: select an item first (on a corpse, the ground or in a pack), then /ra loot why."); return; } + if (selected == 0) + return Loot.LootWhy.Report.Fail(window + ? "select an item first (on a corpse, the ground or in a pack), then Check again." + : "select an item first (on a corpse, the ground or in a pack), then /ra loot why."); WorldObject? item = _objectCache?[unchecked((int)selected)]; - if (item == null) { ReplyFail($"[RynthAi] loot why: item 0x{selected:X8} isn't known yet; select it again in a moment."); return; } + if (item == null) return Loot.LootWhy.Report.Fail($"item 0x{selected:X8} isn't known yet; select it again in a moment."); LegacyUiSettings? settings = _dashboard?.Settings; - if (settings == null) { ReplyFail("[RynthAi] loot why: settings aren't loaded yet (log in first)."); return; } + if (settings == null) return Loot.LootWhy.Report.Fail("settings aren't loaded yet (log in first)."); + string path = (settings.CurrentLootPath ?? string.Empty).Trim().Trim('"'); + if (path.Length == 0) return Loot.LootWhy.Report.Fail("no loot profile is selected. Pick one on the dashboard (Loot)."); + if (!System.IO.File.Exists(path)) return Loot.LootWhy.Report.Fail("the loot profile in use isn't there: " + path); bool hasId = !Host.HasHasAppraisalData || Host.HasAppraisalData(selected); - string idNote = hasId ? "identified" : "not identified yet"; - bool taken = ClassifyLootItem(item, settings, preview: true, out string action, out _, out string ruleLabel, out string builtIn); string looter = taken ? $"[{action}] {ruleLabel}" : "left"; if (builtIn.Length > 0) looter += " (" + builtIn + ")"; - if (TryLoadNativeLootProfile(out _, out _)) + // Rares mode: its verdict is the whole answer (the loot profile isn't used). + if (Loot.LootModes.IsRares(settings.LootMode)) { - ChatLine($"[RynthAi] Loot why: '{item.Name}' ({idNote}) -> {looter}. (Rule-by-rule detail is for VTank .utl profiles.)"); - return; + Host.Log($"[LootWhy] '{item.Name}' 0x{selected:X8} {Loot.LootWhy.IdNote(hasId)} -> {looter}; Loot Mode rares"); + return Loot.LootWhy.ModeOnly(item.Name, hasId, looter, $"Loot Mode: {LootModeLine(settings)} (the loot profile isn't used)"); } - if (!TryLoadLootProfile(string.Empty, out VTankLootProfile profile, out string path)) - return; // it said why + + if (TryLoadNativeLootProfile(out _, out _)) + return Loot.LootWhy.Describe(item.Name, hasId, looter, string.Empty, 0, null, false); + if (!TryLoadLootProfile(string.Empty, out VTankLootProfile profile, out path)) + return Loot.LootWhy.Report.Fail("the loot profile in use couldn't be read (chat says why)."); VTankLootContext ctx = new(Host, _playerId) { Cache = _objectCache }; Loot.LootWhy.Result why = Loot.LootWhy.Explain(profile, item, ctx, hasId); - string file = System.IO.Path.GetFileName(path); - string rule = why.Index >= 0 ? $"rule {why.Index + 1} of {profile.Rules.Count} '{why.RuleName}'" : string.Empty; - string decision = why.Verdict switch - { - VTankLootVerdict.Match => $"{file}: {rule} [{why.Action}]", - VTankLootVerdict.NeedsId => $"{file}: {rule} needs the item's ID to decide", - _ => $"{file}: no rule matches", - }; - ChatLine($"[RynthAi] Loot why: '{item.Name}' ({idNote}) -> {looter}"); - ChatLine($"[RynthAi] {decision}"); - Host.Log($"[LootWhy] '{item.Name}' 0x{selected:X8} {idNote} -> {looter}; {decision}"); - if (why.Verdict == VTankLootVerdict.NeedsId && Host.HasRequestId && Host.RequestId(selected)) - ChatLine("[RynthAi] Asked for its ID; /ra loot why again once it's in."); - - if (why.NearMisses.Count == 0) - { - ChatLine("[RynthAi] No rule above it came close (each failed on its first condition)."); - return; - } - ChatLine($"[RynthAi] {why.NearMisses.Count} rule(s) above it came close; the first condition each failed:"); - for (int i = 0; i < why.NearMisses.Count; i++) - { - var m = why.NearMisses[i]; - string line = $"#{m.Index + 1} '{m.RuleName}': {m.Failed}"; - Host.Log("[LootWhy] " + line); - if (i < LootWhyChatLines) ChatLine("[RynthAi] " + line); - } - if (why.NearMisses.Count > LootWhyChatLines) - ChatLine($"[RynthAi] ... {why.NearMisses.Count - LootWhyChatLines} more in the log ([LootWhy] lines)."); + bool asked = why.Verdict == VTankLootVerdict.NeedsId && Host.HasRequestId && Host.RequestId(selected); + Loot.LootWhy.Report report = Loot.LootWhy.Describe(item.Name, hasId, looter, System.IO.Path.GetFileName(path), + profile.Rules.Count, why, asked); + Host.Log($"[LootWhy] '{item.Name}' 0x{selected:X8} {Loot.LootWhy.IdNote(hasId)} -> {looter}; {report.Decision}"); + if (report.SwitchedOff.Length > 0) + Host.Log("[LootWhy] " + Loot.LootWhy.SwitchedOffLine(report.SwitchedOff)); + foreach (Loot.LootWhy.NearMiss m in report.NearMisses) + Host.Log("[LootWhy] " + Loot.LootWhy.NearMissLine(m)); + return report; } private bool TryLoadNativeLootProfile(out RynthCore.Loot.LootProfile profile, out string loadedPath) @@ -1885,11 +1976,27 @@ public sealed partial class RynthAiPlugin ChatLine($"[RynthAi] enableCombat={s.EnableCombat} busy={s.BusyCount} facing={s.FacingTarget}"); ChatLine($"[RynthAi] targets: total={total} ring={ring} possible={poss} losBlk={losBlk} scanned={s.ScannedCount}"); ChatLine($"[RynthAi] active=0x{(uint)s.ActiveTargetId:X8} locked=0x{(uint)s.LockedTargetId:X8}"); + int forced = _combatManager.ForcedTargetId; + bool bySelection = _combatManager.ForcedBySelection; + if (forced != 0) + { + string forcedName = _objectCache?[forced]?.Name ?? $"0x{(uint)forced:X8}"; + ChatLine(bySelection + ? $"[RynthAi] fighting the monster you selected: {forcedName} (Fight the monster I select{(forced == s.ActiveTargetId ? "" : "; not in reach yet")})" + : $"[RynthAi] target lock (/ra targetlock): {forcedName}{(forced == s.ActiveTargetId ? "" : " (not in reach yet)")}"); + } // D4 record-only skip reasons: why the last combat/buff cycle did (or didn't) cast. ChatLine($"[RynthAi] combatSkip='{s.LastCombatSkipReason}'" + (_buffManager != null ? $" buffSkip='{_buffManager.GetStateSnapshot().LastBuffSkipReason}'" : "")); if (s.ScannedCount > 0) ChatLine($"[RynthAi] closest: '{s.ClosestScannedName}' @ {s.ClosestScannedDist:0.0}yd"); + // A higher-priority monster the target was picked over, and why: often just Monster Range + // (a setting), sometimes a wall. Only monsters inside Monster Range are candidates. + string? passedOver = _combatManager.DescribeHigherPriorityPassedOver(); + if (passedOver != null) + ChatLine($"[RynthAi] higher priority not targeted: {passedOver}" + + (passedOver.Contains("beyond Monster Range", StringComparison.Ordinal) + ? " - raise Monster Range (Advanced settings, Ranges) to fight it from farther" : "")); ChatLine($"[RynthAi] melee/missile: lastSwing={_combatManager.LastSwingEvidenceDescription} attackRebinds={_combatManager.AttackRebinds} " + $"stallWatch episodes={_combatManager.StallEpisodes} recovered={_combatManager.StallRecoveries}"); @@ -1924,7 +2031,11 @@ public sealed partial class RynthAiPlugin !s.IsMacroRunning ? "macro is STOPPED (start it from the panel / command)." : !s.EnableCombat ? "combat is disabled in settings." : s.BusyCount > 0 ? "AC busy>0 — waiting on a server action (cast/use/move); try /ra clearbusy if stuck." : - total < 0 ? "no combat scan has run yet (cold start / just logged in)." : + forced != 0 && forced == s.ActiveTargetId && bySelection + ? "fighting the monster you selected (Fight the monster I select: Settings > Ranges)." : + forced != 0 && forced == s.ActiveTargetId + ? "fighting the target-locked monster (/ra targetlock; /ra targetlock off releases it)." : + total < 0 ? "no combat scan has run yet (cold start / just logged in)." : total == 0 ? "no monsters in the object cache (respawn-blind, or wrong area)." : ring == 0 ? "monsters exist but ALL out of engage range (nav not closing distance?)." : poss == 0 && losBlk > 0 ? "monsters in range but LOS-blocked (behind walls)." : diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs index 5393461..1453b29 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs @@ -217,8 +217,11 @@ public sealed partial class RynthAiPlugin { LegacyUi.LegacyUiSettings? settings = _dashboard?.Settings; WorldObject? wo = _objectCache?[itemId]; - if (!_lootInspectMode || settings == null || wo == null || string.IsNullOrEmpty(settings.CurrentLootPath)) return ""; - if (!ClassifyLootItem(wo, settings, preview: true, out string action, out _, out string rule, out string builtIn)) + bool rares = settings != null && Loot.LootModes.IsRares(settings.LootMode); + if (!_lootInspectMode || settings == null || wo == null || (!rares && string.IsNullOrEmpty(settings.CurrentLootPath))) return ""; + bool taken = ClassifyLootItem(wo, settings, preview: true, out string action, out _, out string rule, out string builtIn); + if (!taken && rares) return " | Loot: leave" + (builtIn.Length > 0 ? " - " + builtIn : ""); + if (!taken) // A rule can match and still not take it (its Keep # reached, a Read rule on a non-scroll). return rule.Length > 0 ? $" | Loot: leave ({rule} matched, not taken)" : " | Loot: no rule matched"; if (builtIn.Length > 0) return $" | Loot: [{action}] built-in - {builtIn}"; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs index 3a1cfe7..429cb1e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs @@ -251,7 +251,9 @@ internal sealed class DashboardBridge : IDashboardHost public void AdjustOpacity(float delta) => Queue(() => { _p.DashboardRenderer?.AdjustOpacity(delta); _p.ScheduleDashSave(); }); public void ToggleLock() => Queue(() => { _p.DashboardRenderer?.TogglePanelLock(); _p.ScheduleDashSave(); }); public void SelectProfile(int kind, int index) => Queue(() => _p.DashboardRenderer?.SelectProfileAtIndex(kind, index)); + public void SetLootMode(int mode) => Queue(() => _p.SetLootModeFromPanel(mode)); public int AutoSort => _p.DashAutoSort; + public bool FightSelectedTarget => _p.DashboardRenderer?.Settings.FightSelectedTarget == true; public void SetAutoSort(bool on) => Queue(() => _p.SetDashAutoSort(on)); public void ToggleSortWindow() => Queue(() => _p.SendSortCommand(string.Empty)); public void StartPatrol() => Queue(_p.HandleDungeonNavPatrol); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs index 908367a..3990699 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -278,6 +278,7 @@ public sealed partial class RynthAiPlugin _miniRemote?.Render(); _huds?.Render(); RenderTranslateWindow(); + RenderLootWhyWindow(); } catch (Exception ex) { @@ -325,6 +326,7 @@ public sealed partial class RynthAiPlugin _navOverlay?.Render(); _itemInfoUi?.Render(); _spellsUi?.Render(); + RenderLootWhyWindow(); } catch (Exception ex) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootWhy.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootWhy.cs new file mode 100644 index 0000000..5d70c4d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootWhy.cs @@ -0,0 +1,38 @@ +// ============================================================================ +// RynthAi - RynthAiPlugin.LootWhy.cs +// The "Why this loot rule?" window (Loot/LootWhyWindow.cs): /ra loot why's +// answer on the screen. Asked for by the remote command "lootwhy" (the engine's +// Loot Editor and Classic Loot tab buttons; RynthDefective's Selection menu, +// through SendPluginCommand) and by /ra loot why window. The tick builds the +// report (BuildLootWhyReport, RynthAiCommands.cs); the render thread draws it. +// ============================================================================ +using RynthCore.Plugin.RynthAi.Loot; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// The remote command (action) that opens the window on the selected item's answer. + internal const string LootWhyAction = "lootwhy"; + + private LootWhyWindow? _lootWhyWindow; // render thread + private volatile LootWhy.Report? _lootWhyReport; // the tick writes, the render thread reads + private volatile bool _lootWhyShown; + + /// Pump thread: the window shows (opening it if it was closed). + private void ShowLootWhyWindow(LootWhy.Report report) + { + _lootWhyReport = report; + _lootWhyShown = true; + } + + /// Render thread, inside OnRender / OnRenderOverlay (the context is set). + private void RenderLootWhyWindow() + { + if (!_lootWhyShown || _lootWhyReport is not { } report) return; + _lootWhyWindow ??= new LootWhyWindow(() => EnqueueRemoteCommand(LootWhyAction, "show")); + bool open = true; + _lootWhyWindow.Render(report, ref open); + if (!open) _lootWhyShown = false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs index 9e2acb4..541af83 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs @@ -11,6 +11,7 @@ namespace RynthCore.Plugin.RynthAi; // // /ra setmetastate Meta: switch the meta state (no state: list them) // /ra targetlock [off] Target lock attack the selected monster (again / off: release) +// /ra fightselected [on|off] Fight the monster I select (no argument: toggle) // /ra meleelow|meleemid|meleehigh melee attack height // /ra navaddpt NavAddPt waypoint at your position (same as /ra addnavpt) // /ra testitem TestItem the selected item against the loot profile @@ -52,6 +53,8 @@ public sealed partial class RynthAiPlugin case "setmetastate": case "metastate": HandleSetMetaStateCommand(parts); return true; case "targetlock": HandleTargetLockCommand(parts); return true; + case "fightselected": + case "fightselect": HandleFightSelectedCommand(parts); return true; case "meleelow": SetMeleeAttackHeight(0); return true; case "meleemid": case "meleemedium": SetMeleeAttackHeight(1); return true; @@ -82,6 +85,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] VTank-style commands (also hotkeys: Settings > Hotkeys, VTank-style):"); ChatLine("[RynthAi] /ra setmetastate - switch the meta state (no state: list the loaded meta's states)"); ChatLine("[RynthAi] /ra targetlock [off] - attack the selected monster first; the same one again, or off, releases it"); + ChatLine("[RynthAi] /ra fightselected [on|off] - Fight the monster I select: the monster you select is fought first (toggle)"); ChatLine("[RynthAi] /ra meleelow | meleemid | meleehigh - melee attack height"); ChatLine("[RynthAi] /ra navaddpt - add a waypoint at your position to the loaded route"); ChatLine("[RynthAi] /ra testitem - check the selected item against the loot profile"); @@ -145,6 +149,13 @@ public sealed partial class RynthAiPlugin uint selected = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : _currentTargetId; int id = unchecked((int)selected); + // Already fought because the player selected it (Fight the monster I select): now the + // explicit lock, which later selections don't move. + if (cm.PromoteSelectedToTargetLock(id)) + { + ReplyOk($"[RynthAi] Target lock: attacking {_objectCache?[id]?.Name ?? $"0x{selected:X8}"} (selecting another monster no longer moves it)."); + return; + } if (id != 0 && id == current) { cm.ClearForcedTarget(); @@ -165,6 +176,35 @@ public sealed partial class RynthAiPlugin ReplyOk($"[RynthAi] Target lock: attacking {name}{note}."); } + // ── Fight the monster I select ─────────────────────────────────────────── + + private void HandleFightSelectedCommand(string[] parts) + { + var dash = _dashboard; + var s = dash?.Settings; + if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; } + string arg = parts.Length >= 3 ? parts[2].ToLowerInvariant() : ""; + bool? set = arg switch + { + "" or "toggle" => !s.FightSelectedTarget, + "on" or "1" or "true" => true, + "off" or "0" or "false" => false, + _ => null, + }; + if (set is not bool on) + { + ReplyFail($"[RynthAi] Fight the monster I select: unknown '{arg}'. Usage: /ra fightselected [on|off] (now {(s.FightSelectedTarget ? "on" : "off")})."); + return; + } + s.FightSelectedTarget = on; + dash!.SaveSettings(); + // Off: a monster it was fighting because you selected it is let go now. + var cm = _combatManager; + if (!on && cm != null && cm.ForcedBySelection) cm.ClearForcedTarget(); + ReplyOk(on ? "[RynthAi] Fight the monster I select: on (the monster you select in a fight is fought first)." + : "[RynthAi] Fight the monster I select: off."); + } + // ── Melee attack height ────────────────────────────────────────────────── private void SetMeleeAttackHeight(int height) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 4701928..6db4750 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -1034,6 +1034,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "settingsprofile": if (int.TryParse(value, out int si)) dash.SelectProfileAtIndex(3, si); break; case "buffprofile": if (int.TryParse(value, out int bi)) dash.SelectProfileAtIndex(4, bi); break; case "spells": HandleSpellsCommand(value); break; // dashboard Spells button: toggle|show|hide + case LootWhyAction: HandleLootWhyCommand(window: true); break; // "Why this loot rule?" buttons case "forcerebuff": dash.RequestForceRebuff(); break; case "cancelrebuff": dash.RequestCancelForceRebuff(); break; case "clearbusy": HandleClearBusyCommand(); break; @@ -2320,6 +2321,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { _currentTargetId = currentTargetId; _dashboard?.SetSelectedTarget(currentTargetId); + // Fight the monster I select: the player's selection (not one RynthAi just made) of a + // monster becomes the fight target (CombatManager.SelectedTarget.cs). Off: nothing. + _combatManager?.OnSelectionChanged(currentTargetId, ItemInfo.SelfSelect.IsOurs(currentTargetId)); if (currentTargetId != 0) { @@ -2486,6 +2490,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { try { _combatManager?.OnObjectCreated(objectId); } catch { } _sessionStats?.OnCreateObject(objectId); + _autoVendor?.OnCreateObject(objectId); // a stack split's new stack try { _objectCache?.OnCreateObject(objectId); diff --git a/Plugins/RynthCore.Plugin.RynthAi/StatusInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/StatusInterface.cs index 04b940d..7bd33b8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/StatusInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/StatusInterface.cs @@ -66,7 +66,7 @@ internal static unsafe class StatusInterface public sealed partial class RynthAiPlugin { - /// {macro,action,state,combat,buff,nav,loot,meta,navFile,metaFile,lootFile}; null before login. + /// {macro,action,state,combat,buff,nav,loot,meta,navFile,metaFile,lootFile,lootMode}; null before login. internal string? BuildBotStatusJson() { var st = _dashboard?.Settings; @@ -86,6 +86,7 @@ public sealed partial class RynthAiPlugin w.WriteString("navFile", FileName(st.CurrentNavPath)); w.WriteString("metaFile", FileName(st.CurrentMetaPath)); w.WriteString("lootFile", FileName(st.CurrentLootPath)); + w.WriteString("lootMode", Loot.LootModes.Word(st.LootMode)); w.WriteEndObject(); } return System.Text.Encoding.UTF8.GetString(buffer.WrittenSpan); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs index f2d2300..b9dd984 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs @@ -90,10 +90,40 @@ internal sealed class AutoVendorManager private readonly HashSet _expectSold = new(); private long _confirmDeadline; - private string _splitName = string.Empty; - private int _splitAmount; - private HashSet _splitBefore = new(); - private long _splitDeadline; + private string _splitName = string.Empty; // the item being split or merged (status line) + private long _splitDeadline; // merges + + // ── Splits (2026-11-01) ── + // A split is one PendingSplit until its result is seen: an object the server CREATED after the + // send (OnCreateObject), else a stack of the same item that grew by the amount (the split went + // onto the stack at the target slot). It outlives the session, so a vendor closed mid-split + // still learns where the units went, and the next open picks up from there instead of + // splitting again. Before, the wait ended at the first new 1-count stack in a polled list and + // the next plan split again at once; that second split went onto the first one's stack, and + // "made no new stack" (Master Raiden Stormcaller, 2026-11-01). + private sealed class PendingSplit + { + public uint SourceId; + public int SourceBefore; + public int Amount; + public string Name = string.Empty; + public uint Wcid; + public string RuleName = string.Empty; + public HashSet Before = new(); + public Dictionary Siblings = new(); // same-item stacks and their counts at the send + public long SentAt; + public long Deadline; + public long NextPollAt; + } + private volatile PendingSplit? _pendingSplit; + private readonly ConcurrentQueue _created = new(); + private readonly HashSet _createdSinceSplit = new(); + // Stacks a split made to be sold, and the rule that sold the stack they came from: sold even when + // a rule matches them differently at their new size ("Value = 250,000" on a one-note stack). + private readonly Dictionary _splitOffForSale = new(); + // Identifies AutoVendor asks for outside the session's ID pass (a split-off stack, a loose note). + private readonly Dictionary _extraIds = new(); + private readonly HashSet _waitIdLogged = new(); // A split or merge that never shows up (no new stack / nothing moved): MaxFailures in a row ends the // session instead of retrying every 10 s forever. private int _tidyFails; @@ -155,6 +185,13 @@ internal sealed class AutoVendorManager public void SetPlayerId(uint id) { if (id != 0) _playerId = id; } + /// The server created an object (any thread). Only kept while a split waits for its stack. + public void OnCreateObject(uint id) + { + if (id != 0 && _pendingSplit != null && _created.Count < 4096) + _created.Enqueue(id); + } + // ════════════════════════════════════════════════════════════════════════ // Vendor events (tick thread) // ════════════════════════════════════════════════════════════════════════ @@ -383,6 +420,7 @@ internal sealed class AutoVendorManager long now = Now(); TickOpener(now); TickAddSell(now, busyCount); + TickPendingSplit(now); // also between sessions: a split sent before the vendor closed if (_phase == Phase.Idle) { @@ -426,6 +464,12 @@ internal sealed class AutoVendorManager _cart.ClearBuy(); _cart.ClearSell(); while (_commands.TryDequeue(out _)) { } + _pendingSplit = null; + while (_created.TryDequeue(out _)) { } + _createdSinceSplit.Clear(); + _splitOffForSale.Clear(); + _extraIds.Clear(); + _waitIdLogged.Clear(); _status = "Idle"; } @@ -478,6 +522,7 @@ internal sealed class AutoVendorManager _failures = 0; _sessionSkip.Clear(); _sellSkipLogged.Clear(); + _waitIdLogged.Clear(); _bailAt = Now(); _nextActionAt = 0; _host.Log($"[RynthAi] AutoVendor: {_vendorName} [0x{merchantId:X8}] profile '{path}' ({_profile.Rules.Count} rules)"); @@ -614,12 +659,39 @@ internal sealed class AutoVendorManager return; } + // A split from earlier (this session or one the vendor closed on) still has no result: wait for + // it rather than plan a second split onto the first one's stack. + if (_pendingSplit != null) + { + _phase = Phase.WaitSplit; + return; + } + var inv = Inventory(); var ctx = NewContext(); List wants = CollectWants(v, inv, ctx); - List sells = AutoVendorPlanner.SortSells(v, CollectSells(v, inv, ctx, null)); + var spareNotes = new List(); + var needId = new List(); + List sells = AutoVendorPlanner.SortSells(v, CollectSells(v, inv, ctx, null, spareNotes, needId)); PackState pack = ReadPack(v, vi, inv); - VendorPlan plan = AutoVendorPlanner.PlanNext(v, wants, sells, pack); + VendorPlan plan = AutoVendorPlanner.PlanNext(v, wants, sells, pack, spareNotes); + + // About to split or merge while a loose stack of the same item (a split's result, a note split + // off by hand) is still being identified: it may be the very stack the plan needs, so wait. + // The same before giving up on a buy: the stack may be what pays for it. + bool tidy = plan.Kind is PlanKind.Split or PlanKind.Merge && plan.SplitItem != null; + if (tidy || (plan.Kind == PlanKind.Done && wants.Count > 0)) + { + foreach (SellItem w in needId) + { + if ((tidy && !SameItem(w, plan.SplitItem!)) || !AwaitId(w.Id, now)) continue; + if (_waitIdLogged.Add(w.Id)) + _host.Log($"[RynthAi] AutoVendor: waiting for the ID of {w.Name} 0x{w.Id:X8} (x{w.StackSize}) before {(tidy ? $"another split or merge of {plan.SplitItem!.Name}" : "ending the session")}"); + _nextActionAt = now + 500; + _bailAt = now; + return; + } + } // Splits and merges only get the stacks ready for a trade: a run of them with no trade between // is going in circles (split-merge-split, 2026-10-19), so it ends the session. @@ -638,6 +710,8 @@ internal sealed class AutoVendorManager switch (plan.Kind) { case PlanKind.Done: + if (!string.IsNullOrEmpty(plan.Message)) + SayWhy(plan.Message); Stop(false); break; @@ -837,34 +911,119 @@ internal sealed class AutoVendorManager Stop(false); return; } + // One split at a time: a second one sent before the first's result is seen lands on the first's + // new stack (the split targets slot 0 of the main pack and joins a same-item stack there). + if (_pendingSplit is { } busy) + { + _host.Log($"[RynthAi] AutoVendor: not splitting {item.Name} yet: the split of {busy.Amount} off {busy.Name} sent {now - busy.SentAt} ms ago has no result yet"); + _phase = Phase.WaitSplit; + return; + } uint player = PlayerId(); - _splitBefore = new HashSet(inv.Select(w => unchecked((uint)w.Id))); + var ps = new PendingSplit + { + SourceId = item.Id, + SourceBefore = item.StackSize, + Amount = amount, + Name = item.Name, + Wcid = item.Wcid, + RuleName = item.RuleName, + Before = new HashSet(inv.Select(w => unchecked((uint)w.Id))), + SentAt = now, + Deadline = now + SplitWaitMs, + NextPollAt = now + PollMs, + }; + foreach (var wo in inv) + if (SameItem(wo, item.Name, item.Wcid)) + ps.Siblings[unchecked((uint)wo.Id)] = StackOf(wo); _splitName = item.Name; - _splitAmount = amount; _host.Log($"[RynthAi] AutoVendor DoSplit {item.Name}:{item.Id:X8} old: {item.StackSize} new: {amount} ({why})"); + while (_created.TryDequeue(out _)) { } + _createdSinceSplit.Clear(); + _pendingSplit = ps; // before the send: a create that arrives at once is kept if (player == 0 || !_host.SplitStackInternal(item.Id, player, 0, amount)) { + _pendingSplit = null; TradeFailed(isBuy: false, $"could not split {item.Name}", now); return; } Tool($"splitting {amount} off {item.Name} ({why})"); - _splitDeadline = now + SplitWaitMs; - _nextPollAt = now + PollMs; _bailAt = now; _phase = Phase.WaitSplit; } private void TickWaitSplit(long now) { - if (now < _nextPollAt) return; - _nextPollAt = now + PollMs; - if (FindNewStack(Inventory(), _splitBefore, _splitName, _splitAmount) != 0) - { - _tidyFails = 0; + // TickPendingSplit (every tick, any phase) moves the session on when the split resolves. + if (_pendingSplit == null) _phase = Phase.Ready; + } + + /// + /// Watches the split in flight: done when the server created a stack of the item after the send, + /// or (no create) when a stack of the item that was there grew by the amount while the source + /// shrank: the split went onto it. Failed when neither shows up in SplitWaitMs. + /// + private void TickPendingSplit(long now) + { + var ps = _pendingSplit; + if (ps == null) + { + while (_created.TryDequeue(out _)) { } + return; + } + while (_created.TryDequeue(out uint c)) + if (!ps.Before.Contains(c)) _createdSinceSplit.Add(c); + if (now < ps.NextPollAt) return; + ps.NextPollAt = now + PollMs; + + var byId = new Dictionary(); + foreach (var wo in Inventory()) + byId[unchecked((uint)wo.Id)] = wo; + int sourceNow = byId.TryGetValue(ps.SourceId, out var src) ? StackOf(src) : 0; + + SplitOutcome outcome = AutoVendorSplits.Resolve( + ps.Amount, ps.SourceBefore, sourceNow, ps.Siblings, _createdSinceSplit, + byId.Where(kv => SameItem(kv.Value, ps.Name, ps.Wcid)).Select(kv => (kv.Key, StackOf(kv.Value), ps.Before.Contains(kv.Key))), + now > ps.Deadline); + + switch (outcome.Kind) + { + case SplitOutcomeKind.Pending: + return; + + case SplitOutcomeKind.NewStack: + case SplitOutcomeKind.JoinedStack: + _pendingSplit = null; + _createdSinceSplit.Clear(); + // Only a stack the split made is sold past the rules; one it joined was already + // there and keeps whatever the profile says about it. + if (outcome.Kind == SplitOutcomeKind.NewStack && outcome.StackCount == ps.Amount) + _splitOffForSale[outcome.StackId] = ps.RuleName; + _host.Log(outcome.Kind == SplitOutcomeKind.NewStack + ? $"[RynthAi] AutoVendor: split {ps.Amount} off {ps.Name}: new stack 0x{outcome.StackId:X8} (x{outcome.StackCount}) after {now - ps.SentAt} ms" + : $"[RynthAi] AutoVendor: split {ps.Amount} off {ps.Name}: no new object; the units went onto stack 0x{outcome.StackId:X8} (now x{outcome.StackCount}) at the split's slot"); + if (!Appraised(outcome.StackId)) AwaitId(outcome.StackId, now); + if (_phase == Phase.WaitSplit) + { + if (outcome.Kind == SplitOutcomeKind.NewStack) _tidyFails = 0; + _phase = Phase.Ready; + _nextActionAt = 0; + } + return; + + default: // failed + _pendingSplit = null; + _createdSinceSplit.Clear(); + string what = sourceNow == ps.SourceBefore + ? $"splitting {ps.Amount} off {ps.Name} changed nothing (the server didn't split it; still x{sourceNow})" + : $"splitting {ps.Amount} off {ps.Name} made no stack we can find (source x{ps.SourceBefore} -> x{sourceNow})"; + if (_phase == Phase.WaitSplit) + TidyFailed(what); + else + _host.Log($"[RynthAi] AutoVendor: {what}"); + return; } - else if (now > _splitDeadline) - TidyFailed($"splitting {_splitAmount} off {_splitName} made no new stack"); } private void DoMerge(SellItem source, SellItem target, string why, long now) @@ -941,7 +1100,12 @@ internal sealed class AutoVendorManager } /// Test mode: items a Sell rule points at that are held back, with why. - private List CollectSells(VendorView v, List inv, VTankLootContext ctx, List? heldBack) + /// Filled with loose single notes that pass the safety checks but no Sell rule + /// took (see AutoVendorPlanner.PlanNext): one of them is sold before another note is split off. + /// Filled with split-off stacks and loose single notes that still need an ID + /// before they can be sold. + private List CollectSells(VendorView v, List inv, VTankLootContext ctx, List? heldBack, + List? spareNotes = null, List? needId = null) { var result = new List(); if (!_settings.AutoVendorEnableSelling || _profile == null) @@ -950,13 +1114,30 @@ internal sealed class AutoVendorManager uint player = PlayerId(); var packOrder = PackOrder(inv, player); var unitValues = TrueUnitValues(inv); + + // Split-off stacks that were sold or merged away are forgotten. + if (_splitOffForSale.Count > 0) + { + var have = new HashSet(inv.Select(w => unchecked((uint)w.Id))); + foreach (uint gone in _splitOffForSale.Keys.Where(k => !have.Contains(k)).ToList()) + _splitOffForSale.Remove(gone); + } + foreach (var wo in inv) { uint id = unchecked((uint)wo.Id); if (_sessionSkip.Contains(id)) continue; + uint type = ItemType(wo); + int stack = StackOf(wo); + bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0; + bool splitOff = _splitOffForSale.TryGetValue(id, out string? splitRule); + bool looseNote = isNote && stack <= 1; + SafetyFacts safety = ReadSafety(wo, player); string? unsafeWhy = AutoVendorPlanner.UnsafeReason(safety, _settings.AutoVendorOnlyFromMainPack); + if (!safety.Appraised && (splitOff || looseNote) && needId != null) + needId.Add(new SellItem { Id = id, Name = wo.Name, Class = wo.ObjectClass, ItemType = type, StackSize = stack, Wcid = WcidOf(id) }); if (unsafeWhy != null && heldBack == null) { if (!_sellSkipLogged.Contains(wo.Name)) @@ -970,9 +1151,6 @@ internal sealed class AutoVendorManager continue; } - uint type = ItemType(wo); - int stack = StackOf(wo); - bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0; int unitValue = stack > 1 ? safety.Value / stack : safety.Value; // A stack keeps its old Value after a split (100 peas' worth on a stack of 2 read "1,250,000 // each", 2026-10-19), which hid it from the sell list and from the split planner. Use the @@ -1006,8 +1184,41 @@ internal sealed class AutoVendorManager heldBack!.Add($"{wo.Name} - {unsafeWhy}"); continue; } + + SellItem Make(string ruleName) + { + bool main = InMainPack(wo, player); + int packIdx = main ? 0 : (packOrder.TryGetValue(wo.DirectContainerId, out int pi) ? pi : 99); + string packName = main ? "Main Pack" : (_cache[wo.DirectContainerId]?.Name ?? "Pack"); + return new SellItem + { + Id = id, + Name = wo.Name, + Class = wo.ObjectClass, + ItemType = type, + StackSize = stack, + Value = stackValue, + RuleName = ruleName, + Location = main ? "Main Pack" : $"{packName} #{packIdx}", + SortSlot = main ? Math.Max(0, wo.DirectSlot) : 1000 + 100 * packIdx + Math.Max(0, wo.DirectSlot), + MaxStack = InventoryManager.GetMaxStackSize(wo), + Wcid = WcidOf(id), + }; + } + if (!sd.Sell) { + // Split off to be sold, from a stack a Sell rule took: sold even if a rule reads the + // smaller stack differently (a Keep rule for the vendor's "Value = 250,000" listing + // also matches a one-note stack, 2026-11-01). + if (splitOff) + { + result.Add(Make(string.IsNullOrEmpty(splitRule) ? "split off to sell" : $"{splitRule} (split off to sell)")); + continue; + } + // A loose single note: kept unless one note has to pay for a buy (PlanNext). + if (looseNote && spareNotes != null) + spareNotes.Add(Make(string.IsNullOrEmpty(sd.RuleName) ? "loose note" : $"loose note, rule '{sd.RuleName}' alone keeps it")); if (heldBack != null && verdict.Rule?.Action == VTankLootAction.Sell) heldBack.Add($"{wo.Name} - {sd.Reason}"); else if (heldBack == null && verdict.Rule?.Action == VTankLootAction.Sell && _sellSkipLogged.Add(wo.Name)) @@ -1015,33 +1226,45 @@ internal sealed class AutoVendorManager continue; } - bool main = InMainPack(wo, player); - int packIdx = main ? 0 : (packOrder.TryGetValue(wo.DirectContainerId, out int pi) ? pi : 99); - string packName = main ? "Main Pack" : (_cache[wo.DirectContainerId]?.Name ?? "Pack"); - result.Add(new SellItem - { - Id = id, - Name = wo.Name, - Class = wo.ObjectClass, - ItemType = type, - StackSize = stack, - Value = stackValue, - RuleName = sd.RuleName, - Location = main ? "Main Pack" : $"{packName} #{packIdx}", - SortSlot = main ? Math.Max(0, wo.DirectSlot) : 1000 + 100 * packIdx + Math.Max(0, wo.DirectSlot), - MaxStack = InventoryManager.GetMaxStackSize(wo), - Wcid = _host.HasGetObjectWcid && _host.TryGetObjectWcid(id, out uint wcid) ? wcid : 0, - }); + result.Add(Make(sd.RuleName)); } return result; } + private uint WcidOf(uint id) => _host.HasGetObjectWcid && _host.TryGetObjectWcid(id, out uint wcid) ? wcid : 0; + + /// Same item for stacking: the weenie when both are known, else the exact name. + private bool SameItem(WorldObject wo, string name, uint wcid) + { + uint w = WcidOf(unchecked((uint)wo.Id)); + return wcid != 0 && w != 0 ? w == wcid : string.Equals(wo.Name, name, StringComparison.Ordinal); + } + + private static bool SameItem(SellItem a, SellItem b) + => a.Wcid != 0 && b.Wcid != 0 ? a.Wcid == b.Wcid : string.Equals(a.Name, b.Name, StringComparison.Ordinal); + + /// + /// Asks for 's ID (outside the session's ID pass) and says whether it is worth + /// waiting for: true while a request is out or another may be sent, false once it is identified + /// or IdMaxAttempts went unanswered. + /// + private bool AwaitId(uint id, long now) + { + if (Appraised(id)) return false; + _extraIds.TryGetValue(id, out var st); + if (st.Attempts > 0 && now - st.LastAt < IdResendMs) return true; + if (st.Attempts >= IdMaxAttempts) return false; + if (!_host.HasRequestId || !_host.RequestId(id)) return false; + _extraIds[id] = (st.Attempts + 1, now); + return true; + } + // ── Test mode (UB DoTestMode) ── private void DoTestMode() { Chat("AutoVendor TEST MODE"); - if (!TryGetVendor(out VendorView v, out _)) + if (!TryGetVendor(out VendorView v, out VendorInfo tvi)) { Chat(" (no vendor open)"); return; @@ -1057,10 +1280,33 @@ internal sealed class AutoVendorManager Chat("Sell Items:"); var held = new List(); - var sells = CollectSells(v, inv, ctx, held).OrderBy(s => s.SortSlot).ToList(); + var spare = new List(); + var sells = CollectSells(v, inv, ctx, held, spare).OrderBy(s => s.SortSlot).ToList(); foreach (var s in sells) Chat($" {s.Location}: {s.Name}{(s.StackSize > 1 ? $" x{s.StackSize}" : string.Empty)} - {s.RuleName}"); if (sells.Count == 0) Chat(" (Nothing)"); + if (spare.Count > 0) + { + Chat("Loose notes (one is sold when a note has to pay for a buy):"); + foreach (var s in spare.Take(10)) Chat($" {s.Location}: {s.Name} - {s.RuleName}"); + if (spare.Count > 10) Chat($" ...and {spare.Count - 10} more"); + } + + // What the next step would be, and why nothing would be bought. + { + PackState pack = ReadPack(v, tvi, inv); + VendorPlan plan = AutoVendorPlanner.PlanNext(v, wants, AutoVendorPlanner.SortSells(v, sells), pack, spare); + string step = plan.Kind switch + { + PlanKind.Buy => "buy " + string.Join(", ", plan.Buys.Select(b => $"{b.Amount:n0}x {b.Item.Name}")), + PlanKind.Sell => "sell " + string.Join(", ", plan.Sells.Select(s => s.Name)), + PlanKind.Split => $"split {plan.SplitAmount} off {plan.SplitItem?.Name}", + PlanKind.Merge => $"merge {plan.SplitItem?.Name} stacks", + PlanKind.Fatal => plan.Message, + _ => string.IsNullOrEmpty(plan.Message) ? "done" : $"done - {plan.Message}", + }; + Chat($"Next step: {step}"); + } if (held.Count > 0) { @@ -1341,10 +1587,7 @@ internal sealed class AutoVendorManager retained = true; // BF_RETAINED if (!retained && _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(id, 91 /* Retained */, out bool ret) && ret) retained = true; - bool rare = wo.Values(17 /* RareId */, 0) > 0; - if (!rare && _host.HasGetObjectDataIdProperty && _host.TryGetObjectDataIdProperty(id, 52 /* IconUnderlay */, out uint underlay) - && (underlay & 0x00FFFFFFu) == 23308u) - rare = true; // UB: IconUnderlay 23308 = rare + bool rare = Loot.RareItems.IsRare(_host, wo, out _); // RareId, or UB's IconUnderlay 23308 return new SafetyFacts { @@ -1370,6 +1613,7 @@ internal sealed class AutoVendorManager IsVendorListing = false, Appraised = appraised, ObjectClass = wo.ObjectClass, + ItemType = ItemType(wo), HasSpellData = appraised && _host.HasGetObjectSpellIds, HasPalettes = _host.HasGetObjectPalettes, HasCharacterSkills = _host.HasGetObjectSkill, @@ -1381,6 +1625,7 @@ internal sealed class AutoVendorManager IsVendorListing = true, Appraised = false, ObjectClass = l.Class, + ItemType = l.ItemType, HasCharacterSkills = _host.HasGetObjectSkill, HasCharacterLevel = _host.HasGetObjectIntProperty, }; @@ -1611,6 +1856,9 @@ internal sealed class AutoVendorManager /// UB Util.ThinkOrWrite: a /tell to yourself when Think is on (metas watch for it). private void ThinkOrWrite(string msg) { + // In RynthCore.log too: a session's end (finished, Fatal) only reached chat, so a log showed + // vendor opens with no buy, sell or split and no reason (2026-11-01). + _host.Log($"[RynthAi] {msg}"); uint player = PlayerId(); if (_settings.AutoVendorThink && _host.HasInvokeChatParser && player != 0 && _host.TryGetObjectName(player, out string me) && !string.IsNullOrWhiteSpace(me)) @@ -1621,6 +1869,13 @@ internal sealed class AutoVendorManager Chat(msg); } + /// Why a session ends without buying what the profile wants: chat and RynthCore.log. + private void SayWhy(string why) + { + _host.Log($"[RynthAi] AutoVendor: {why}"); + Error(why); + } + private void SayNeedsUpdate() => Error($"needs a RynthCore update: vendor trading is plugin API v67, this engine is v{_host.Version}."); @@ -1644,5 +1899,8 @@ internal sealed class AutoVendorManager _status = s; } - private static long Now() => Environment.TickCount64; + /// The manager's clock in ms (tests move it by hand). + internal static Func Clock = () => Environment.TickCount64; + + private static long Now() => Clock(); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs index b64b77a..8de5ee6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs @@ -119,6 +119,8 @@ internal sealed class VendorPlan public string Message { get; init; } = string.Empty; public static VendorPlan Done() => new() { Kind = PlanKind.Done }; + /// Done, with why a wanted item wasn't bought (empty when nothing was wanted). + public static VendorPlan Done(string whyNotBought) => new() { Kind = PlanKind.Done, Message = whyNotBought ?? string.Empty }; 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 }; @@ -179,6 +181,9 @@ internal static class AutoVendorPlanner /// What you pay for one created stack worth . public static long PlayerPays(VendorView v, bool isNote, long stackValue) { + // A vendor rate of exactly 0 is a free vendor (a storage vault): it costs 0, no 1-per-stack floor, + // as the engine prices it (RynthCore VendorRatePolicy, AwfulWaffle's PR #10). + if (v.SellRate == 0f) return 0; float rate = isNote ? 1.15f : v.SellRate; float product = rate * stackValue; return Math.Max(1L, (long)Math.Ceiling(product - 0.1)); @@ -187,6 +192,7 @@ internal static class AutoVendorPlanner /// What the vendor pays for one item (whole stack) worth . public static long VendorPays(VendorView v, bool isNote, long value) { + if (v.BuyRate == 0f) return 0; // a free vendor pays 0 (see PlayerPays) float rate = isNote ? 1.0f : v.BuyRate; float product = rate * value; return Math.Max(1L, (long)Math.Floor(product + 0.1)); @@ -341,7 +347,15 @@ internal static class AutoVendorPlanner /// From BuildBuyWants (already sorted). /// From SortSells. - public static VendorPlan PlanNext(VendorView v, IReadOnlyList wants, IReadOnlyList sells, PackState p) + /// + /// Loose single trade notes that passed the safety checks but no Sell rule took on their own: + /// usually a Keep rule written for the vendor's listing ("Value = 250,000") that a one-note stack + /// also matches. Notes are interchangeable, so when one note of the same kind has to be sold to + /// pay for a buy, one of these goes before any split. Without this a hand-split single (or the + /// stack the last split made) was never sold and every plan split another note off (2026-11-01). + /// + public static VendorPlan PlanNext(VendorView v, IReadOnlyList wants, IReadOnlyList sells, PackState p, + IReadOnlyList? spareNotes = null) { // ── Buy first ── var buys = new List(); @@ -432,10 +446,7 @@ internal static class AutoVendorPlanner 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; } + SellItem? single = FindSingleNote(sells, item) ?? (spareNotes != null ? FindSingleNote(spareNotes, item) : null); if (single != null) return new VendorPlan { Kind = PlanKind.Sell, Sells = new List { single }, Total = VendorPays(v, true, single.Value) }; @@ -463,7 +474,57 @@ internal static class AutoVendorPlanner if (chosen.Count > 0) return new VendorPlan { Kind = PlanKind.Sell, Sells = chosen, Total = totalValue }; - return VendorPlan.Done(); + return VendorPlan.Done(ExplainUnmetBuy(v, wants, sells, p, spareNotes)); + } + + private static SellItem? FindSingleNote(IReadOnlyList list, SellItem like) + { + foreach (var s in list) + if (s.IsNote && s.StackSize <= 1 && (SameItem(s, like) || string.Equals(s.Name, like.Name, StringComparison.Ordinal))) + return s; + return null; + } + + /// + /// The session ends with a want still unbought: one line saying why, for chat and the log. A + /// session that bought nothing and said nothing looked like AutoVendor ignoring the vendor + /// (Prismatic Tapers at Master Raiden Stormcaller, 2026-11-01). Empty when nothing is wanted. + /// + internal static string ExplainUnmetBuy(VendorView v, IReadOnlyList wants, IReadOnlyList sells, PackState p, + IReadOnlyList? spareNotes = null) + { + // A Keep rule buys "all you can afford": running out of money is how it ends, not a failure. + // Only a Keep # count still short is worth a line. + BuyWant? w = null; + foreach (var x in wants) + if (x.Amount != int.MaxValue) { w = x; break; } + if (w == null) return string.Empty; + Listing item = w.Item; + string what = $"{w.Amount.ToString("n0", CultureInfo.InvariantCulture)}x {item.Name}"; + string currency = v.UsesAltCurrency ? "currency" : "pyreals"; + long price = UnitPrice(v, item); + string rule = string.IsNullOrEmpty(w.RuleName) ? string.Empty : $" (rule '{w.RuleName}')"; + + bool fits = item.NeedsContainerSlot ? p.FreeContainerSlots > 0 : p.FreeMainSlots > (item.IsNote ? 0 : 1); + if (!fits) + return item.NeedsContainerSlot + ? $"can't buy {what}{rule}: no free container slot" + : $"can't buy {what}{rule}: only {p.FreeMainSlots} free main-pack slot(s), one stays free"; + + if (price > p.Funds) + { + string head = string.Format(CultureInfo.InvariantCulture, "can't buy {0}{1}: {2:n0} {3} each, you have {4:n0}", + what, rule, price, currency, p.Funds); + if (v.UsesAltCurrency) return head + " (selling can't pay an alt-currency vendor)"; + if (item.IsNote) return head + " (notes are never sold to buy notes)"; + bool anyNote = false, anyOther = false; + foreach (var s in sells) { if (s.IsNote) anyNote = true; else anyOther = true; } + if (!anyNote && spareNotes is { Count: > 0 }) + return head + $", and no Sell rule matches a note stack here: the loose {spareNotes[0].Name} ({spareNotes[0].RuleName}) stays"; + if (!anyNote && !anyOther) return head + ", and nothing the profile sells is here to pay for it"; + return head; + } + return $"can't buy {what}{rule}"; } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs index f95bb48..cc25d65 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs @@ -31,6 +31,8 @@ internal readonly struct ItemFacts /// Inventory item with appraisal (ID) data. public bool Appraised { get; init; } public AcObjectClass ObjectClass { get; init; } + /// The item's ITEM_TYPE flags (0 = not read). + public uint ItemType { get; init; } /// The item's spell list can be read (appraised and the host exposes spell ids). public bool HasSpellData { get; init; } public bool HasPalettes { get; init; } @@ -169,11 +171,34 @@ internal static class AutoVendorRules } } + // Decal gives these classes from one ITEM_TYPE bit each (RynthAi too: WorldObjectCache.ClassifyByItemType + // checks them before any coarse class). An item whose type lacks the bit is never that class. + internal static readonly Dictionary TypeBitClasses = new() + { + [AcObjectClass.TradeNote] = 0x00040000, // TYPE_PROMISSORY_NOTE + [AcObjectClass.ManaStone] = 0x00080000, // TYPE_MANASTONE + [AcObjectClass.SpellComponent] = 0x00001000, // TYPE_SPELL_COMPONENTS + [AcObjectClass.Gem] = 0x00000800, // TYPE_GEM + }; + /// ObjectClass test without the evaluator: unknown for classes Decal splits further. - public static Tri JudgeObjectClass(VTankLootCondition cond, AcObjectClass itemClass) + public static Tri JudgeObjectClass(VTankLootCondition cond, AcObjectClass itemClass) => JudgeObjectClass(cond, itemClass, 0); + + /// + /// As above, and with the item's ITEM_TYPE known a coarse class still answers No for a class that + /// needs a type bit the item lacks: a server's custom letter (Book, a writable) is never a TradeNote. + /// The owner's "S: Trade Note" rule (ObjectClass = TradeNote) read Unknown for 'Scarlet Red Letter' + /// and logged "needs Object Class data we don't have" at every vendor open (2026-11-01). + /// + public static Tri JudgeObjectClass(VTankLootCondition cond, AcObjectClass itemClass, uint itemType) { if (!TryKey(cond.DataLines, 0, out int target)) return Tri.Unknown; - if (CoarseClasses.Contains(itemClass)) return Tri.Unknown; + if (CoarseClasses.Contains(itemClass)) + { + if (itemType != 0 && TypeBitClasses.TryGetValue((AcObjectClass)target, out uint bit) && (itemType & bit) == 0) + return Tri.No; + return Tri.Unknown; + } return (int)itemClass == target ? Tri.Yes : Tri.No; } @@ -184,7 +209,7 @@ internal static class AutoVendorRules public static Tri JudgeCondition(VTankLootCondition cond, in ItemFacts f, Func match) { if (!CanJudge(cond, f)) return Tri.Unknown; - if (cond.NodeType == VTankNodeTypes.ObjectClass) return JudgeObjectClass(cond, f.ObjectClass); + if (cond.NodeType == VTankNodeTypes.ObjectClass) return JudgeObjectClass(cond, f.ObjectClass, f.ItemType); try { return match(cond) ? Tri.Yes : Tri.No; } catch { return Tri.Unknown; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorSplits.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorSplits.cs new file mode 100644 index 0000000..c9a6d1f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorSplits.cs @@ -0,0 +1,70 @@ +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.Vendor; + +// Pure judging of where a stack split went, for AutoVendorManager's PendingSplit. No host calls: +// the manager hands in what it saw (objects the server created since the send, the stacks of the +// item now and their counts at the send). Dependency-free so the AutoVendor test project can link it. + +internal enum SplitOutcomeKind : byte +{ + Pending = 0, + /// The server created a stack of the item after the send: the split-off stack. + NewStack = 1, + /// No new object, but a stack of the item that was already there grew by the amount + /// while the source shrank: the split went onto that stack (it sat at the split's target slot). + JoinedStack = 2, + /// Neither showed up in time. + Failed = 3, +} + +internal readonly record struct SplitOutcome(SplitOutcomeKind Kind, uint StackId, int StackCount); + +internal static class AutoVendorSplits +{ + /// Units split off. + /// The source stack's count when the split was sent. + /// Its count now (0 = gone). + /// Every stack of the item at the send (the source included) and its count. + /// Objects the server created since the send. + /// Every stack of the item now: id, count, and whether it existed at the send. + /// The wait is over. + public static SplitOutcome Resolve(int amount, int sourceBefore, int sourceNow, + IReadOnlyDictionary siblingsBefore, IReadOnlySet created, + IEnumerable<(uint Id, int Count, bool Existed)> stacksNow, bool timedOut) + { + var now = new List<(uint Id, int Count, bool Existed)>(stacksNow); + + // 1. A create the server sent after the split, of this item: the split-off stack. The right + // count first (a hand split of another amount could land in the same wait). + (uint Id, int Count)? createdAny = null; + foreach (var s in now) + { + if (s.Existed || !created.Contains(s.Id)) continue; + if (s.Count == amount) return new SplitOutcome(SplitOutcomeKind.NewStack, s.Id, s.Count); + createdAny ??= (s.Id, s.Count); + } + // Another count: its count may not be readable yet. It is the split's once the source shrank by + // the amount, or when the wait is over and nothing better showed up. + if (createdAny is { } ca && (sourceBefore - sourceNow == amount || timedOut)) + return new SplitOutcome(SplitOutcomeKind.NewStack, ca.Id, ca.Count); + + // 2. The create event was missed: a stack that wasn't there, holding exactly the amount. + foreach (var s in now) + if (!s.Existed && s.Count == amount) + return new SplitOutcome(SplitOutcomeKind.NewStack, s.Id, s.Count); + + // 3. No new object: the units went onto a stack that was there (the source shrank by them). + if (sourceNow > 0 && sourceNow <= sourceBefore - amount) + { + foreach (var s in now) + { + if (!s.Existed || !siblingsBefore.TryGetValue(s.Id, out int before)) continue; + if (s.Count - before == amount && sourceBefore - sourceNow == amount) + return new SplitOutcome(SplitOutcomeKind.JoinedStack, s.Id, s.Count); + } + } + + return timedOut ? new SplitOutcome(SplitOutcomeKind.Failed, 0, 0) : new SplitOutcome(SplitOutcomeKind.Pending, 0, 0); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.Selection.cs b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.Selection.cs index be95e12..45eddcd 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.Selection.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.Selection.cs @@ -9,6 +9,11 @@ // landblock coordinates: 192 units a landblock; the facing from the player's // pose, as RynthAi's combat turns), and its health from AC's health updates // (OnUpdateHealth), asked for when a creature is selected and every 2 s after. +// An item's mana (2026-11-01, Tom: "a bar that reports the mana status"): its +// ItemCurMana / ItemMaxMana from the last identify (AC identifies what is +// selected; asked once if it hasn't 1.5 s later), identified again every 15 s +// while it stays selected, so a worn item's bar follows it down. +// Its right-click menu's "Why this loot rule?" asks RynthAi (AskLootWhy). // ============================================================================ using System; @@ -24,7 +29,8 @@ public sealed partial class RynthDefectivePlugin private SelectionWindow? _selectionWindow; // render thread private volatile SelectionView _selectionView = SelectionView.NotReady; - private long _selectionDrawnMs = long.MinValue / 2, _nextSelectionMs, _nextHealthQueryMs; + private long _selectionDrawnMs = long.MinValue / 2, _nextSelectionMs, _nextHealthQueryMs, _nextManaQueryMs; + private bool _manaAsked; // the selection had no identify, and one was asked for private uint _selectionId; private int _selectionFailures; @@ -52,6 +58,7 @@ public sealed partial class RynthDefectivePlugin { Quantity = _qty, QuantityAction = (click, n) => QueueBar(() => RunQuantityClick(click, n)), + LootWhy = Host.HasSendPluginCommand ? _ => QueueBar(AskLootWhy) : null, }; wantHeight = _selectionWindow.Draw(_selectionView); _selectionFailures = 0; @@ -90,6 +97,32 @@ public sealed partial class RynthDefectivePlugin Host.QueryHealth(sel); } + // An item's mana, from its identify. + float mana = -1f; + uint manaCur = 0, manaMax = 0; + if (changed) { _manaAsked = false; _nextManaQueryMs = now + 1500; } + if (!creature) + { + if (Host.TryGetObjectIntProperty(sel, ItemMaxManaProperty, out int most) && most > 0) + { + Host.TryGetObjectIntProperty(sel, ItemCurManaProperty, out int cur); + manaMax = (uint)most; + manaCur = (uint)Math.Clamp(cur, 0, most); + mana = manaCur / (float)most; + if (changed) _nextManaQueryMs = now + ManaRefreshMs; // AC identifies a new selection itself + else if (now >= _nextManaQueryMs) + { + _nextManaQueryMs = now + ManaRefreshMs; + Host.RequestId(sel); + } + } + else if (!_manaAsked && now >= _nextManaQueryMs && !(Host.HasHasAppraisalData && Host.HasAppraisalData(sel))) + { + _manaAsked = true; // not identified by now: once, so an item with mana gets its bar + Host.RequestId(sel); + } + } + // The quantity box (a stack, or an item in the open vendor's list). Quantity.QuantityView? qty = QuantityViewNow(); @@ -121,10 +154,25 @@ public sealed partial class RynthDefectivePlugin HealthSeen? h = _health; float health = h != null && h.Id == sel ? h.Ratio : -1f; - return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0) { Qty = qty }; + return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0) + { + Qty = qty, Creature = creature, Mana = mana, ManaCur = manaCur, ManaMax = manaMax, + }; + } + + /// + /// The Selection menu's "Why this loot rule?": RynthAi answers for the item selected now, in its + /// own window (its remote command "lootwhy", the one /ra loot why window runs). Plugin tick. + /// + private void AskLootWhy() + { + if (!Host.SendPluginCommand("RynthAi", "lootwhy", "show")) + PrintFail("Why this loot rule? needs RynthAi, which isn't loaded."); } private const uint StackSizeProperty = 12; // PropertyInt.StackSize + private const uint ItemCurManaProperty = 107, ItemMaxManaProperty = 108; // PropertyInt.ItemCurMana / ItemMaxMana + private const long ManaRefreshMs = 15000; /// A carried item's line: how many in the stack or uses left, and where (in your pack, in hand, worn). private static string CarriedText(Items.CarriedItem it) diff --git a/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/SelectionWindow.cs b/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/SelectionWindow.cs index ef06b84..f3f7894 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/SelectionWindow.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/ShortcutBar/SelectionWindow.cs @@ -3,12 +3,15 @@ // What is selected, as the retail toolbar showed it (Tom 2026-10-22: "people // use it all the time to find things near them: doors, monsters"): its // picture and name, how far and which way it is (an arrow from where you -// face, and the compass point), and the health bar of a creature or player. +// face, and the compass point), and the health bar of a creature or player, +// or the mana bar of an item with mana (2026-11-01, as retail showed it). // USE uses it (opens a door, talks to an NPC). AC's own selection keys still // pick what is selected; this only shows it. // // the name row drag to move; Ctrl+wheel: bigger or smaller (30-250%); -// right-click: hide it (Settings > UI > Toolbar, /rdef selection). +// right-click: a menu (2026-10-31): "Why this loot rule?" for +// an item (RynthAi's /ra loot why, in its window) and hide it +// (Settings > UI > Toolbar, /rdef selection show it again). // the quantity under a stack or a vendor's item (2026-10-30): how many, and // Split / Give / Buy that many (SelectionWindow.Quantity.cs). // @@ -42,6 +45,14 @@ internal sealed record SelectionView( /// The quantity box for a stack or a vendor's item; null = none. public QuantityView? Qty { get; init; } + + /// A creature or player (no loot rule applies to it). + public bool Creature { get; init; } + + /// An item's mana, 0-1, or -1 when it has none known; with its points (0 = unknown). + public float Mana { get; init; } = -1f; + public uint ManaCur { get; init; } + public uint ManaMax { get; init; } } internal sealed partial class SelectionWindow @@ -73,6 +84,7 @@ internal sealed partial class SelectionWindow private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent; private static readonly uint HealthColor = Argb(0xFFE0564E), HealthHigh = Argb(0xFF73D885), White = Argb(0xFFFFFFFF); + private static readonly uint ManaColor = Argb(0xFF4F8DF0); private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f)); /// Draws the selection into the host's window; returns the height it needs (pixels). Render thread. @@ -110,10 +122,11 @@ internal sealed partial class SelectionWindow ImGui.SetCursorScreenPos(origin); ImGui.InvisibleButton("##sel_drag", new Vector2(Math.Max(1, width - useW - (hasUse ? pad : 0)), height)); _host.PanelDragWithLastItem(); - if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) ImGui.OpenPopup(MenuId); SafeImGui.SetItemTooltip(v.Id == 0 - ? "Nothing selected. Select with a click or the game's selection keys (- and = go through what's near you).\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: hide." - : $"{v.Name}{(v.Where.Length > 0 ? " - " + v.Where : "")}\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: hide."); + ? "Nothing selected. Select with a click or the game's selection keys (- and = go through what's near you).\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: the menu (hide it)." + : $"{v.Name}{(v.Where.Length > 0 ? " - " + v.Where : "")}\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: the menu (why this loot rule, hide it)."); + Menu(v); // The picture. Vector2 ip = origin + new Vector2(pad, pad); @@ -135,7 +148,7 @@ internal sealed partial class SelectionWindow return height; } - // Name, then the health bar (a creature or player) and where it is. + // Name, then the bar (a creature's or player's health, an item's mana) and where it is. Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y), _text, v.Name, right - tx); float lineY = ip.Y + icon - Fs(sf); float x = tx; @@ -145,16 +158,21 @@ internal sealed partial class SelectionWindow Arrow(dl, new Vector2(x + s * 0.5f, lineY + s * 0.5f), s * 0.5f, v.Relative, _accent); x += s + Px(3); } - if (v.Health >= 0f) + bool mana = v.Health < 0f && v.Mana >= 0f; + if (v.Health >= 0f || mana) { float barY = ip.Y + Fs(nf) + Px(3); float barW = right - tx, barH = Px(BarH); Vector2 b0 = new(tx, barY), b1 = new(tx + barW, barY + barH); dl.AddRectFilled(b0, b1, _inset, Px(2)); - float f = Math.Clamp(v.Health, 0f, 1f); - if (f > 0f) dl.AddRectFilled(b0, new Vector2(tx + barW * f, barY + barH), f > 0.6f ? A(HealthHigh, 0.9f) : HealthColor, Px(2)); + float f = Math.Clamp(mana ? v.Mana : v.Health, 0f, 1f); + uint fill = mana ? ManaColor : f > 0.6f ? A(HealthHigh, 0.9f) : HealthColor; + if (f > 0f) dl.AddRectFilled(b0, new Vector2(tx + barW * f, barY + barH), fill, Px(2)); dl.AddRect(b0, b1, _line, Px(2)); - string pct = (v.Max > 0 ? $"{v.Current}/{v.Max} " : "") + MathF.Round(f * 100f).ToString(CultureInfo.InvariantCulture) + "%"; + string points = mana + ? v.ManaMax > 0 ? v.ManaCur.ToString("N0", CultureInfo.InvariantCulture) + "/" + v.ManaMax.ToString("N0", CultureInfo.InvariantCulture) + " " : "" + : v.Max > 0 ? $"{v.Current}/{v.Max} " : ""; + string pct = points + MathF.Round(f * 100f).ToString(CultureInfo.InvariantCulture) + "%"; float pw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, pct).X; dl.AddText(sf, Fs(sf), new Vector2(right - pw, lineY), _dim, pct); Clip(dl, sf, Fs(sf), new Vector2(x, lineY), _dim, v.Where, right - pw - Px(6) - x); @@ -181,6 +199,42 @@ internal sealed partial class SelectionWindow return height + qtyH; } + private const string MenuId = "##sel_menu"; + + /// "Why this loot rule?" for the selected item (RynthAi answers in its window); null = no RynthAi item. + public Action? LootWhy { get; set; } + + /// The right-click menu: why this loot rule (an item, not a creature), hide the window. Render thread. + private void Menu(SelectionView v) + { + if (!ImGui.IsPopupOpen(MenuId)) return; + ImGui.PushStyleColor(ImGuiCol.PopupBg, A(_bg, 0.98f)); + ImGui.PushStyleColor(ImGuiCol.Border, _line); + ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4)); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(6), Px(5))); + bool open = ImGui.BeginPopup(MenuId); + ImGui.PopStyleVar(2); + ImGui.PopStyleColor(2); + if (!open) return; + try + { + if (v.Id != 0) SafeImGui.TextDisabled(v.Name); + else ImGui.TextDisabled("Nothing selected"); + ImGui.Separator(); + bool item = v.Ready && v.Id != 0 && !v.Creature; + if (LootWhy != null) + { + if (ImGui.MenuItem("Why this loot rule?", null, false, item)) LootWhy(v.Id); + SafeImGui.SetItemTooltip(item + ? "RynthAi's loot profile: which rule takes this item, and why the rules above it didn't (/ra loot why)." + : "Select an item (on a corpse, the ground or in a pack) first."); + } + if (ImGui.MenuItem("Hide the Selection window")) _host.SetPanelOpen(Title, RynthPanelOpen.Close); + SafeImGui.SetItemTooltip("/rdef selection, or Settings > UI > Toolbar > Selection, shows it again."); + } + finally { ImGui.EndPopup(); } + } + /// Text cut with "..." to pixels. private static void Clip(ImDrawListPtr dl, ImFontPtr f, float size, Vector2 pos, uint color, string text, float room) { diff --git a/Plugins/RynthCore.Plugin.RynthNav/AtlasStore.cs b/Plugins/RynthCore.Plugin.RynthNav/AtlasStore.cs index a0832db..d456fad 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/AtlasStore.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/AtlasStore.cs @@ -29,6 +29,12 @@ internal sealed class AtlasStore public List Recent { get; } = new(); public int Version { get; private set; } + // What this client changed since its last save. Every game client runs RynthNav and saves the + // whole file, so a save first re-reads it and applies only these (MergeInto): a favorite added on + // one client is no longer wiped by another client's next recent place (2026-11-01). + private readonly List _addedFavs = new(), _removedFavs = new(), _touched = new(); + private bool _recentCleared; + public bool IsFavorite(SavedPlace p) => Favorites.Exists(f => f.SameAs(p)); /// Adds it if it isn't there, removes it if it is. Returns true when it is now a favorite. @@ -36,9 +42,11 @@ internal sealed class AtlasStore { int i = Favorites.FindIndex(f => f.SameAs(p)); Version++; - if (i >= 0) { Favorites.RemoveAt(i); return false; } - if (Favorites.Count >= MaxFavorites) Favorites.RemoveAt(Favorites.Count - 1); + if (i >= 0) { NoteRemoved(Favorites[i]); Favorites.RemoveAt(i); return false; } + if (Favorites.Count >= MaxFavorites) { NoteRemoved(Favorites[^1]); Favorites.RemoveAt(Favorites.Count - 1); } Favorites.Add(p); + _removedFavs.RemoveAll(f => f.SameAs(p)); + _addedFavs.Add(p); return true; } @@ -46,11 +54,41 @@ internal sealed class AtlasStore { int i = Favorites.FindIndex(f => f.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (i < 0) return false; + NoteRemoved(Favorites[i]); Favorites.RemoveAt(i); Version++; return true; } + private void NoteRemoved(SavedPlace p) + { + _addedFavs.RemoveAll(f => f.SameAs(p)); + _removedFavs.Add(p); + } + + /// + /// The favorite called (any case), or null. A favorite named with a tag in + /// brackets ("Abandoned Experiment (Conquest)") answers to the name without it too. + /// + public SavedPlace? FindFavorite(string name) + { + name = name.Trim(); + if (name.Length == 0) return null; + foreach (var f in Favorites) + if (f.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return f; + foreach (var f in Favorites) + if (Untagged(f.Name).Equals(name, StringComparison.OrdinalIgnoreCase)) return f; + return null; + } + + private static string Untagged(string name) + { + string n = name.TrimEnd(); + if (!n.EndsWith(')')) return n; + int open = n.LastIndexOf(" (", StringComparison.Ordinal); + return open > 0 ? n.Substring(0, open).TrimEnd() : n; + } + /// Puts it first in Recent (an arrow target or a trip). public void Touch(SavedPlace p) { @@ -59,6 +97,8 @@ internal sealed class AtlasStore if (i > 0) Recent.RemoveAt(i); Recent.Insert(0, p); while (Recent.Count > MaxRecent) Recent.RemoveAt(Recent.Count - 1); + _touched.RemoveAll(r => r.SameAs(p)); + _touched.Insert(0, p); Version++; } @@ -66,9 +106,38 @@ internal sealed class AtlasStore { if (Recent.Count == 0) return; Recent.Clear(); + _touched.Clear(); + _recentCleared = true; Version++; } + /// + /// Before a save: makes this store the file on disk (, what the other clients + /// saved) with this client's changes since its last save applied — favorites it added or removed, + /// the places it went to (first in Recent), a Clear — then forgets those changes. Afterwards this + /// client also has the other clients' favorites. + /// + public void MergeInto(AtlasStore disk) + { + var favs = new List(); + foreach (var f in disk.Favorites) + if (!_removedFavs.Exists(r => r.SameAs(f)) && !favs.Exists(x => x.SameAs(f))) favs.Add(f); + foreach (var f in _addedFavs) + if (!favs.Exists(x => x.SameAs(f))) favs.Add(f); + while (favs.Count > MaxFavorites) favs.RemoveAt(0); + + var recent = new List(_touched); + if (!_recentCleared) + foreach (var r in disk.Recent) + if (!recent.Exists(x => x.SameAs(r))) recent.Add(r); + while (recent.Count > MaxRecent) recent.RemoveAt(recent.Count - 1); + + Favorites.Clear(); Favorites.AddRange(favs); + Recent.Clear(); Recent.AddRange(recent); + _addedFavs.Clear(); _removedFavs.Clear(); _touched.Clear(); + _recentCleared = false; + } + // ── atlas.txt ──────────────────────────────────────────────────────────── // fav\tname\tns\tew\ttype / recent\tname\tns\tew\ttype (newest first) diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs index c789f8c..7a84561 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs @@ -657,6 +657,14 @@ public sealed partial class RynthNavPlugin if (at != null && given.Length > 0) { type = at.Type; _resolvedPlace = at; } return true; } + // A favorite by its name first: places of your own the Atlas doesn't have (a custom server's + // dungeon: "/rnav fav 42.45N, 56.05E Abandoned Experiment (Conquest)"). + SavedPlace? fav = _store.FindFavorite(text); + if (fav != null) + { + name = fav.Name; type = fav.Type; ns = fav.Ns; ew = fav.Ew; + return true; + } bool hasPos = PlayerMapPos(out double pns, out double pew); AtlasLocation? best = _atlas.FindBest(text, hasPos, pns, pew); if (best == null) @@ -852,6 +860,13 @@ public sealed partial class RynthNavPlugin if (_store.Version != _savedStoreVersion || force) { _savedStoreVersion = _store.Version; + // Every client saves this file: apply this one's changes to what is on disk now, not over it. + try + { + string path = NavFile("atlas.txt"); + if (File.Exists(path)) _store.MergeInto(AtlasStore.Parse(File.ReadAllText(path))); + } + catch (Exception ex) { Host.Log($"[RynthNav] atlas.txt (merging before a save): {ex.Message}"); } WriteLater("atlas.txt", _store.Serialize()); } if (_memory.Version != _savedMemoryVersion || force) diff --git a/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersWindow.cs b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersWindow.cs index 3d68f57..fcfd12c 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersWindow.cs +++ b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersWindow.cs @@ -57,7 +57,7 @@ internal sealed class CharactersWindow "follow me, stop following, start or stop the macro. They go through RynthNet, so the other client's " + "remote command setting (/rn remote) decides whether they run.\n\n" + "The arrows-in button (or /rn view minimal) shows one line per character without the frame; " + - "hover it for the pencil (or /rn view full) to come back here. Kept per character.\n\n" + + "its pencil (or /rn view full) comes back here. Kept per character.\n\n" + "/rc characters opens and closes this window."; private float _k = 1f; @@ -70,7 +70,7 @@ internal sealed class CharactersWindow private bool _openMenu; public CharactersWindow(RynthCoreHost host, Action select, Action tell, Action followMeAll, - Func<(bool, float)> heading, Action setView) + Func<(bool, float)> heading, Action setView, Action? useSelectionAll = null) { _host = host; _select = select; @@ -78,8 +78,12 @@ internal sealed class CharactersWindow _followMeAll = followMeAll; _heading = heading; _setView = setView; + _useSelectionAll = useSelectionAll; } + // "Everyone: use my selection" (/rn usesel); null = not offered. + private readonly Action? _useSelectionAll; + /// /// Draws the window body into the current ImGui window in 's look. /// : the engine gave the window no frame (v90), so the full look paints @@ -247,13 +251,13 @@ internal sealed class CharactersWindow } } - // The pencil: back to the full look (shown while the mouse is on the window). - if (windowHot) + // The pencil: back to the full look. Always there (2026-10-31: a control you can see, not + // one that shows on hover), faint until the mouse is on the window. { float bs = rowH - 2; var bp = new Vector2(Math.Min(start.X + lineW + Px(4), origin.X + width - bs - 2), start.Y + 1); - if (IconButton("##chars_full", RynthIcons.PencilSimple, bp, new Vector2(bs, bs), Text, WithAlpha(Background, 0xE0), - font: RynthUiFont.Ui11)) + if (IconButton("##chars_full", RynthIcons.PencilSimple, bp, new Vector2(bs, bs), windowHot ? Text : Faded(Text), + WithAlpha(Background, windowHot ? 0xE0u : 0x70u), font: RynthUiFont.Ui11)) _setView(CharactersViewMode.Full); ImGui.SetItemTooltip("Edit: the full window with every column, to move or resize it (/rn view full)"); } @@ -632,6 +636,14 @@ internal sealed class CharactersWindow } if (ImGui.MenuItem("Everyone: follow me", "", false, canFollow)) _followMeAll(); ImGui.SetItemTooltip("/rn followme"); + if (_useSelectionAll != null) + { + bool hasSelection = _host.HasGetSelectedItemId && _host.GetSelectedItemId() != 0; + if (ImGui.MenuItem("Everyone: use my selection", "", false, hasSelection)) _useSelectionAll(); + SafeImGui.SetItemTooltip(hasSelection + ? "The other clients use what you have selected (a portal, a door, an NPC): /rn usesel" + : "Select something first (a portal, a door, an NPC). /rn usesel"); + } ImGui.TextDisabled("The other client's /rn remote setting decides."); } finally diff --git a/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.Characters.cs b/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.Characters.cs index 79c3e28..e48b577 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.Characters.cs +++ b/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.Characters.cs @@ -61,7 +61,8 @@ public sealed partial class RynthNetPlugin tell: (name, command) => _localCommands.Enqueue(("/rn tell " + name + ", " + command, false)), followMeAll: () => _localCommands.Enqueue(("/rn followme", false)), heading: CompassHeading, - setView: mode => _uiActions.Enqueue(() => SetCharactersView(mode, quiet: true))); + setView: mode => _uiActions.Enqueue(() => SetCharactersView(mode, quiet: true)), + useSelectionAll: () => _localCommands.Enqueue(("/rn usesel", false))); wantHeight = _charsWindow.Draw(_charsView, CharsLook, FramelessWindows, popped); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs b/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs index c5fd1ad..67abec0 100644 --- a/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs +++ b/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs @@ -134,6 +134,9 @@ internal sealed class SortPanel uint id = p.Id; w.SmallButton("+ Add rule", $"add.{id:X8}", () => AddRule(rules, view, number)); w.Tooltip("A rule sends items to this pack: items of any of its classes, or with any of its names in their name. A name beats a class."); + w.SameLine(); + w.SmallButton("Empty this pack", $"unpack.{id:X8}", () => _c.StartUnpack(number)); + w.Tooltip($"Move everything in pack {number} into the main pack. Turns auto-sort off first, so nothing moves back. Also: /rsort unpack {number}"); int on = 0; foreach (SortRule r in packRules) if (r.On && !r.IsEmpty) on++; if (on >= 2) diff --git a/Plugins/Shared/RynthAiStatusApi.cs b/Plugins/Shared/RynthAiStatusApi.cs index 8102e90..7c98a91 100644 --- a/Plugins/Shared/RynthAiStatusApi.cs +++ b/Plugins/Shared/RynthAiStatusApi.cs @@ -25,8 +25,9 @@ public unsafe struct RynthAiStatusApiV1 /// /// The bot's state as one JSON object: - /// {macro,action,state,combat,buff,nav,loot,meta,navFile,metaFile,lootFile} - /// (action = what it is doing now: Default/Combat/Looting/Navigating/Buffing...; state = meta state). + /// {macro,action,state,combat,buff,nav,loot,meta,navFile,metaFile,lootFile,lootMode} + /// (action = what it is doing now: Default/Combat/Looting/Navigating/Buffing...; state = meta state; + /// lootMode = "profile" or "rares", rares and needed mana stones only, since 2026-10-31). /// 1 = ok, 0 = not ready (not logged in yet). /// public delegate* unmanaged[Cdecl] GetStatusJson; diff --git a/Tools/RynthCore.AutoVendorTests/Program.cs b/Tools/RynthCore.AutoVendorTests/Program.cs index 61e841e..d30624b 100644 --- a/Tools/RynthCore.AutoVendorTests/Program.cs +++ b/Tools/RynthCore.AutoVendorTests/Program.cs @@ -45,6 +45,7 @@ internal static class Program TestPlanBuy(); TestPlanSell(); TestPlanNotes(); + TestLooseNotesAndSplits(); TestPrices(); TestSafety(); TestVendorWillBuy(); @@ -480,6 +481,89 @@ internal static class Program Eq(p6.Kind, PlanKind.Done, "alt currency: notes kept"); } + // 2026-11-01, Master Raiden Stormcaller: a one-note stack matches the profile's Keep rule for the + // vendor's listing ("ObjectClass TradeNote, Value = 250,000"), so a loose single never reached the + // sell list and every plan split another note off. Loose singles now pay first; a split's result + // is judged from what the server did; a session that can't buy says why. + private static void TestLooseNotesAndSplits() + { + Console.WriteLine("\n-- loose notes, split results, why nothing was bought --"); + var v = Vendor(buy: 0.7f, sell: 1.15f); + SellItem Note(uint id, int stack, string rule = "S: Trade Note") => new() + { + Id = id, Name = "Trade Note (250,000)", Value = 250_000 * stack, StackSize = stack, Class = AcObjectClass.TradeNote, + ItemType = 0x40000, RuleName = rule, MaxStack = 250, Wcid = 20630, + }; + var tapers = new List { new() { Item = L(10, "Prismatic Taper", 115, value: 100, maxStack: 5000), Amount = 36, RuleName = "B: Prismatic Tapers" } }; + + // The owner's profile, as RynthAi judges an identified note stack. + var keepListing = Rule("B: Trade Note (250,000)", VTankLootAction.Keep, null, Cond(7, "15"), Cond(12, "250000", "19")); + var sellNotes = Rule("S: Trade Note", VTankLootAction.Sell, null, Cond(7, "15")); + var rules = new List { keepListing, sellNotes }; + var noteFacts = new ItemFacts { Appraised = true, ObjectClass = AcObjectClass.TradeNote, ItemType = 0x40000 }; + var forty = AutoVendorRules.Decide(rules, JudgeFake(noteFacts, "Trade Note (250,000)", new() { [19] = 10_000_000 })); + Check(AutoVendorRules.JudgeSell(forty).Sell, "40 notes (10,000,000): the Sell rule takes them"); + var one = AutoVendorRules.Decide(rules, JudgeFake(noteFacts, "Trade Note (250,000)", new() { [19] = 250_000 })); + Eq(one.Rule?.Name, "B: Trade Note (250,000)", "one note (250,000): the listing's Keep rule matches it"); + Check(!AutoVendorRules.JudgeSell(one).Sell, "so a single note is never on the sell list"); + + // A loose single (kept by that rule) pays before any split. + var big = Note(1, 39); + var loose = Note(2, 1, "loose note"); + var p1 = AutoVendorPlanner.PlanNext(v, tapers, new List { big }, Pack(0), new List { loose }); + Eq(p1.Kind, PlanKind.Sell, "a loose note is sold..."); + Eq(p1.Sells.Single().Id, 2u, "...the loose one"); + var p2 = AutoVendorPlanner.PlanNext(v, tapers, new List { big }, Pack(0), new List()); + Eq(p2.Kind, PlanKind.Split, "none loose: split one off"); + var otherNote = new SellItem { Id = 3, Name = "Trade Note (100,000)", Value = 100_000, StackSize = 1, Class = AcObjectClass.TradeNote, ItemType = 0x40000, MaxStack = 250, Wcid = 2626 }; + var p3 = AutoVendorPlanner.PlanNext(v, tapers, new List { big }, Pack(0), new List { otherNote }); + Eq(p3.Kind, PlanKind.Split, "a loose note of another kind doesn't stand in"); + var p4 = AutoVendorPlanner.PlanNext(v, new List(), new List { big }, Pack(0), new List { loose }); + Eq(p4.Kind, PlanKind.Done, "nothing to buy: loose notes stay too"); + + // Why nothing was bought. + var p5 = AutoVendorPlanner.PlanNext(v, tapers, new List(), Pack(0)); + Eq(p5.Kind, PlanKind.Done, "can't pay: done"); + Eq(p5.Message, "can't buy 36x Prismatic Taper (rule 'B: Prismatic Tapers'): 115 pyreals each, you have 0, and nothing the profile sells is here to pay for it", "...and says why"); + var p6 = AutoVendorPlanner.PlanNext(v, tapers, new List(), Pack(0), new List { loose }); + Check(p6.Message.Contains("no Sell rule matches a note stack here: the loose Trade Note (250,000) (loose note) stays"), "only loose notes, no sellable note stack: says they stay"); + var keepAll = new List { new() { Item = L(11, "Trade Note (250,000)", 287_500, 250_000, cls: AcObjectClass.TradeNote, type: 0x40000), Amount = int.MaxValue } }; + Eq(AutoVendorPlanner.PlanNext(v, keepAll, new List(), Pack(0)).Message, string.Empty, "a Keep (all you can afford) running out of money is no failure"); + Check(AutoVendorPlanner.PlanNext(v, tapers, new List(), Pack(1_000_000, free: 1)).Kind == PlanKind.Done + && AutoVendorPlanner.ExplainUnmetBuy(v, tapers, new List(), Pack(1_000_000, free: 1)).Contains("only 1 free main-pack slot(s)"), "no room: says so"); + + // Where a split went. + var sibs = new Dictionary { [1] = 40, [5] = 1 }; + var none = new HashSet(); + var made = AutoVendorSplits.Resolve(1, 40, 39, sibs, new HashSet { 9 }, new[] { (1u, 39, true), (5u, 1, true), (9u, 1, false) }, false); + Eq(made.Kind, SplitOutcomeKind.NewStack, "a create of the item: the new stack"); + Eq(made.StackId, 9u, "its id"); + var unread = AutoVendorSplits.Resolve(25, 100, 100, sibs, new HashSet { 9 }, new[] { (1u, 100, true), (9u, 1, false) }, false); + Eq(unread.Kind, SplitOutcomeKind.Pending, "created but the count unreadable and the source unchanged: wait"); + var unreadLater = AutoVendorSplits.Resolve(25, 100, 75, sibs, new HashSet { 9 }, new[] { (1u, 75, true), (9u, 1, false) }, false); + Eq(unreadLater.Kind, SplitOutcomeKind.NewStack, "...until the source shrank by the amount"); + var missed = AutoVendorSplits.Resolve(1, 40, 39, sibs, none, new[] { (1u, 39, true), (9u, 1, false) }, false); + Eq(missed.Kind, SplitOutcomeKind.NewStack, "create missed: a new id with exactly the amount"); + var joined = AutoVendorSplits.Resolve(1, 40, 39, sibs, none, new[] { (1u, 39, true), (5u, 2, true) }, false); + Eq(joined.Kind, SplitOutcomeKind.JoinedStack, "no new object, a stack that was there grew: joined"); + Eq(joined.StackId, 5u, "the stack it joined"); + Eq(joined.StackCount, 2, "now 2"); + Eq(AutoVendorSplits.Resolve(1, 40, 40, sibs, none, new[] { (1u, 40, true), (5u, 1, true) }, false).Kind, SplitOutcomeKind.Pending, "nothing yet: pending"); + Eq(AutoVendorSplits.Resolve(1, 40, 40, sibs, none, new[] { (1u, 40, true), (5u, 1, true) }, true).Kind, SplitOutcomeKind.Failed, "nothing in time: failed"); + Eq(AutoVendorSplits.Resolve(1, 40, 39, sibs, none, new[] { (1u, 39, true), (5u, 1, true) }, false).Kind, SplitOutcomeKind.Pending, "the source shrank but the units aren't seen yet: wait"); + + // A server's custom letter (a writable, so Book) is never a TradeNote. + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "15"), AcObjectClass.Book, 0x2000), Tri.No, "Book with its type read: not a TradeNote"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "15"), AcObjectClass.Book, 0), Tri.Unknown, "type unread: still unknown"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "42"), AcObjectClass.Book, 0x2000), Tri.Unknown, "Book may still be a Scroll"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "29"), AcObjectClass.Misc, 0x80), Tri.Unknown, "Misc may still be a healing kit"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "16"), AcObjectClass.Misc, 0x80), Tri.No, "Misc is never a ManaStone"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "15"), AcObjectClass.Unknown, 0x10000000), Tri.No, "an unclassified type without the note bit: not a TradeNote"); + var letterFacts = new ItemFacts { Appraised = true, ObjectClass = AcObjectClass.Book, ItemType = 0x2000 }; + var letter = AutoVendorRules.Decide(rules, JudgeFake(letterFacts, "Scarlet Red Letter", new() { [19] = 5 })); + Check(letter.Rule == null && letter.Certain, "the letter: no rule matches, nothing to log"); + } + private static void TestPrices() { Console.WriteLine("\n-- prices --"); diff --git a/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj b/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj index 2a65bf4..e491faa 100644 --- a/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj +++ b/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj @@ -21,6 +21,7 @@ + diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index cac790e..d0720ab 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -103,6 +103,8 @@ internal static unsafe class FakeHost /// Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in . public static bool TapJumpCalls; public static int TapJumps; + /// Jumps and item moves in the order they were called ("tapjump", "jump", "move:XXXXXXXX"). + public static readonly List Order = new(); /// TapJump returns 0 (the client refused the jump); the call still counts in TapJumps. public static bool TapJumpRefuse; public static int Turns; @@ -305,7 +307,7 @@ internal static unsafe class FakeHost Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatTypes.Clear(); ChatCommands.Clear(); AfterCastSpell = null; - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1; RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; @@ -894,10 +896,10 @@ internal static unsafe class FakeHost } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int JumpNonAutonomous(float extent) { Jumps++; return 1; } + private static int JumpNonAutonomous(float extent) { Jumps++; Order.Add("jump"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int TapJump() { TapJumps++; return TapJumpRefuse ? 0 : 1; } + private static int TapJump() { TapJumps++; Order.Add("tapjump"); return TapJumpRefuse ? 0 : 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int CastSpell(uint target, int spellId) { if (CastRefused) { CastsRefused++; return 0; } Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); AfterCastSpell?.Invoke(); return 1; } @@ -994,7 +996,7 @@ internal static unsafe class FakeHost private static uint GetGroundContainerId() => GroundContainer; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int MoveItemExternal(uint id, uint target, int amount) { ExternalMoves.Add((id, target, amount)); return 1; } + private static int MoveItemExternal(uint id, uint target, int amount) { ExternalMoves.Add((id, target, amount)); Order.Add($"move:{id:X8}"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SalvagePanelOpen(uint tool) => 1; diff --git a/Tools/RynthCore.RynthAiHostTests/Fixtures/lootsnob-excerpt.utl b/Tools/RynthCore.RynthAiHostTests/Fixtures/lootsnob-excerpt.utl index 313930b..a263043 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fixtures/lootsnob-excerpt.utl +++ b/Tools/RynthCore.RynthAiHostTests/Fixtures/lootsnob-excerpt.utl @@ -1,6 +1,6 @@ UTL 1 -135 +179 ***** Melee Weapons ***** 0;1;1 @@ -1371,6 +1371,371 @@ true 24 leave this disabled 1 +(W) No Wield (29MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.29 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 +(W) No Wield (28MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.28 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 +(W) No Wield (27MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.27 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 +(W) No Wield (26MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.26 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 +(W) No Wield (25MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.25 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 +(W) No Wield (24MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.24 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 +(W) No Wield (23MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.23 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 +(W) No Wield (22MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.22 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 +(W) No Wield (21MD) + +0;1;7;2005;13;13;13;1;13 +4 +31 +10 +1.21 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 + (W) No Wield (20MD + 4MgcD) + +0;1;7;2005;5;1;13;13;13;13 +4 +31 +9 +1.2 +29 +11 +1.04 +150 +27 +Orb|Wand|Sceptre|Staff +1 +10 +375 +160 +10 +355 +160 +10 +330 +160 +10 +385 +160 + (W) No Wield (20MD + 10MC) + +0;1;7;2005;13;13;13;2005;1;13 +4 +31 +9 +1.2 +29 +10 +375 +160 +10 +355 +160 +10 +330 +160 +10 +0.1 +144 +27 +Orb|Wand|Sceptre|Staff +1 +10 +385 +160 + (W) No Wield (Creature Cantrip) + +0;1;7;2005;1;13;13;13;0;2005;13;9999 +4 +31 +10 +1.15 +29 +27 +Orb|Wand|Sceptre|Staff +1 +10 +375 +160 +10 +355 +160 +10 +330 +160 +49 +Major Creature|Epic Creature|Legendary Creature +10 +0.5 +144 +10 +385 +160 +6 +true + (W) No Wield (Life Cantrip) + +0;1;7;2005;1;13;13;13;0;2005;13;9999 +4 +31 +10 +1.15 +29 +27 +Orb|Wand|Sceptre|Staff +1 +10 +375 +160 +10 +355 +160 +10 +330 +160 +37 +Major Life|Epic Life|Legendary Life +10 +0.5 +144 +10 +385 +160 +6 +true + (W) No Wield (Item Cantrip) + +0;1;7;2005;1;13;13;13;9;2005;13;9999 +4 +31 +10 +1.15 +29 +27 +Orb|Wand|Sceptre|Staff +1 +10 +375 +160 +10 +355 +160 +10 +330 +160 +46 +Major Item|Epic Item|Legendary Item +Tink +1 +10 +0.5 +144 +10 +385 +160 +6 +true + (W) Orb (Healer's Heart) + +0;1;7;1;9;9999 +4 +31 +8 +Orb +1 +38 +Adja's Gift|Incantation of Heal + +1 +6 +true (W) Void (OD +7) 0;1;7;2005;1 @@ -1733,6 +2098,361 @@ Nether 10 355 160 + + +0;1;9999;1 +6 +true +24 +leave this disabled +1 +(W) War (OD +7) + +0;1;7;2005;1 +4 +31 +11 +1.25 +152 +24 +Baton|Sceptre|Staff +1 +(W) War (OD +6) + +0;1;7;2005;1 +4 +31 +11 +1.24 +152 +24 +Baton|Sceptre|Staff +1 +(W) War (OD +5) + +0;1;7;2005;1 +4 +31 +11 +1.23 +152 +24 +Baton|Sceptre|Staff +1 +(W) War (OD +4) + +0;1;7;2005;1 +4 +31 +11 +1.22 +152 +24 +Baton|Sceptre|Staff +1 +(W) War (OD +3) + +0;1;7;2005;1 +4 +31 +11 +1.21 +152 +24 +Baton|Sceptre|Staff +1 +(W) War (OD +2) + +0;1;7;2005;1 +4 +31 +10 +1.2 +152 +24 +Baton|Sceptre|Staff +1 +(W) War (OD +1) + +0;1;7;2005;1 +4 +31 +11 +1.19 +152 +24 +Baton|Sceptre|Staff +1 +(W) War (amazing 355) + +0;1;7;2005;1;2005;12 +4 +31 +11 +1.17 +152 +24 +Baton|Sceptre|Staff +1 +10 +1.25 +29 +10 +355 +160 + (W) War (18pvm + 20md) + +0;1;7;2005;1;2005 +4 +31 +11 +1.18 +152 +24 +Baton|Sceptre|Staff +1 +9 +1.2 +29 + (W) War (18pvm + 19md) + +0;1;7;2005;1;2005 +4 +31 +11 +1.18 +152 +24 +Baton|Sceptre|Staff +1 +10 +1.19 +29 + (W) War (18pvm + 18md) + +0;1;7;2005;1;2005 +4 +31 +11 +1.18 +152 +24 +Baton|Sceptre|Staff +1 +10 +1.18 +29 + (W) War (18pvm + 17md) + +0;1;7;2005;1;2005 +4 +31 +11 +1.18 +152 +24 +Baton|Sceptre|Staff +1 +10 +1.17 +29 + (W) War (18pvm + 16md) + +0;1;7;2005;1;2005 +4 +31 +11 +1.18 +152 +24 +Baton|Sceptre|Staff +1 +10 +1.16 +29 + (W) War (18pvm + 15md) + +0;1;7;2005;1;2005 +4 +31 +11 +1.18 +152 +24 +Baton|Sceptre|Staff +1 +10 +1.15 +29 + (W) War (18pvm + 4MgcD) + +0;1;7;2005;1;5 +4 +31 +11 +1.18 +152 +24 +Baton|Sceptre|Staff +1 +11 +1.04 +150 + (W) War (20md + 4MgcD) + +0;1;7;5;1;2005 +4 +31 +11 +1.04 +150 +24 +Baton|Sceptre|Staff +1 +9 +1.2 +29 + (W) War (29MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.29 +29 + (W) War (28MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.28 +29 + (W) War (27MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.27 +29 + (W) War (26MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.26 +29 + (W) War (25MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.25 +29 + (W) War (24MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.24 +29 + (W) War (23MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.23 +29 + (W) War (22MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.22 +29 + (W) War (21MD) + +0;1;7;1;2005 +4 +31 +24 +Baton|Sceptre|Staff +1 +10 +1.21 +29 + (W) War (Max 385) + +0;1;7;2005;1;12 +4 +31 +11 +1.18 +152 +24 +Baton|Sceptre|Staff +1 +10 +385 +160 + (W) War (Max 375) + +0;1;7;2005;1;12 +4 +31 +11 +1.15 +152 +24 +Baton|Sceptre|Staff +1 +10 +375 +160 + (W) War (Max 355) + +0;1;7;2005;1;12 +4 +31 +11 +1.13 +152 +24 +Baton|Sceptre|Staff +1 +10 +355 +160 ***** Salvage ***** 0;1;1;9999 diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 21ae352..e805a58 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -60,6 +60,8 @@ internal static class Program VTankLootTests.Register(runner); LootRuleMatchTests.Register(runner); LootLateIdTests.Register(runner); + LootWandTests.Register(runner); + LootRaresModeTests.Register(runner); LootChatLineTests.Register(runner); LootSurveyTests.Register(runner); PropertyDumpTests.Register(runner); @@ -119,6 +121,8 @@ internal static class Program InstallPathsTests.Register(runner); PetRefillTests.Register(runner); AutoStackTests.Register(runner); + AutoVendorSplitTests.Register(runner); + AutoVendorZeroRateTests.Register(runner); BackAwayTests.Register(runner); ServerPluginForwardTests.Register(runner); IgnoreMonsterTests.Register(runner); @@ -147,6 +151,7 @@ internal static class Program DeathRecallTests.Register(runner); InventoryAttributeFilterTests.Register(runner); StuckCastTests.Register(runner); + KillNoticeTests.Register(runner); PacerEdgeTests.Register(runner); RecoveryRetryTests.Register(runner); HpFailsafeTests.Register(runner); @@ -155,8 +160,10 @@ internal static class Program ShieldBuffTests.Register(runner); RebuffWhenIdleTests.Register(runner); LootPacingTests.Register(runner); + LootJumpTests.Register(runner); CorpseCloseTests.Register(runner); VTankHotkeyTests.Register(runner); + FightSelectedTests.Register(runner); OneTouchHealTests.Register(runner); SaveFailureTests.Register(runner); EnvironmentImpactTests.Register(runner); @@ -176,6 +183,7 @@ internal static class Program ChoresInFightTests.Register(runner); CommandReplyTests.Register(runner); MonsterStatsTests.Register(runner); + MetaSaveTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorSplitTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorSplitTests.cs new file mode 100644 index 0000000..45b4e52 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorSplitTests.cs @@ -0,0 +1,392 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Vendor; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-11-01, Master Raiden Stormcaller (Conquest): AutoVendor had to sell one Trade Note (250,000) +// to pay for Prismatic Tapers. It split one note off, saw the new stack and split again 0.3 s later: +// the profile's "B: Trade Note (250,000)" Keep rule (ObjectClass TradeNote, Value = 250,000; written +// for the vendor's listing) also matches a one-note stack, so the new stack (and any note split off +// by hand) never made the sell list. The second split went onto the first one's stack: "made no new +// stack". Now a split's result is known from the server's create (or the stack it joined), the stack +// it made is sold past the rules, loose single notes count as "already have one", one split is in +// flight at a time, and a split the vendor closed on is picked up at the next open. +// +// The manager's clock (AutoVendorManager.Clock) is moved by hand; the "server" answers in the fakes. +internal static unsafe class AutoVendorSplitTests +{ + private const uint Player = 0x50000A01; + private const uint Vendor = 0x70000001; // FakeHost's open vendor id + private const uint Taper = 0x70000101; // the vendor's listing + private const uint Notes = 0x80A00001, Tapers = 0x80A00002, Letter = 0x80A00003; + private const uint NewStack = 0x80A00101, HandSingle = 0x80A00102; + private const uint NoteWcid = 20630, TaperWcid = 20631; + private const uint TypeNote = 0x00040000, TypeComp = 0x00001000, TypeWritable = 0x00002000; + private const int NoteValue = 250_000; + + public static void Register(Runner r) + { + r.Add("autovendor split: the split-off note is identified and sold, never split twice, then the buy goes through", SplitOffNoteIsSold); + r.Add("autovendor split: a note split off by hand is sold before any split", HandSplitSingleIsSold); + r.Add("autovendor split: a split the vendor closed on is picked up at the next open, no second split", SplitResumesNextOpen); + r.Add("autovendor split: a split that went onto another stack is recognised, not 'made no new stack'", SplitJoinedStack); + r.Add("autovendor split: no second split while one is in flight", NoSecondSplitInFlight); + r.Add("autovendor split: a session that can't buy says why (chat and log)", CantBuySaysWhy); + r.Add("autovendor split: a custom letter is no TradeNote (no 'needs Object Class data' line)", LetterIsNoTradeNote); + } + + // ── The fake vendor and server ──────────────────────────────────────────── + + private static int _coins; + private static uint _lastRequest; + private static readonly List<(uint Id, uint Container, int Slot, int Amount)> Splits = new(); + private static readonly List Sells = new(); + private static readonly List<(uint Id, int Amount)[]> Buys = new(); + private static Action? _onSplit; + private static Action? _onSell; + private static Action<(uint Id, int Amount)[]>? _onBuy; + + private static void Configure(ref RynthCoreApiNative api) + { + api.Version = Math.Max(api.Version, 82u); + api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorInfo; + api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorItems; + api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl])&VendorBuy; + api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl])&VendorSell; + api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorTradeStatus; + api.SplitStackInternalFn = (IntPtr)(delegate* unmanaged[Cdecl])&SplitStackInternal; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetVendorInfo(VendorInfoNative* info) + { + *info = default; + info->VendorId = Vendor; + info->ItemTypes = TypeNote | TypeComp | TypeWritable; + info->MaxValue = 1_000_000; + info->BuyRate = 0.7f; + info->SellRate = 1.15f; + info->PlayerCoins = _coins; + info->ItemCount = 1; + info->Flags = 1; // trading available + byte[] name = Encoding.ASCII.GetBytes("Town Vendor"); + for (int i = 0; i < name.Length; i++) info->Name[i] = name[i]; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetVendorItems(VendorItemNative* items, int max) + { + if (items == null || max < 1) return 1; + items[0] = default; + items[0].ObjectId = Taper; + items[0].ItemType = TypeComp; + items[0].Amount = -1; + items[0].StackSize = 1; + items[0].MaxStackSize = 5000; + items[0].Value = 100; + items[0].UnitValue = 100; + items[0].UnitPrice = 115; + items[0].Flags = 1 | 2; // unlimited, stackable + byte[] name = Encoding.ASCII.GetBytes("Prismatic Taper"); + for (int i = 0; i < name.Length; i++) items[0].Name[i] = name[i]; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint VendorBuy(uint vendor, VendorTradeEntryNative* entries, int count) + { + var list = new (uint, int)[count]; + for (int i = 0; i < count; i++) list[i] = (entries[i].ObjectId, entries[i].Amount); + Buys.Add(list); + _onBuy?.Invoke(list); + return ++_lastRequest; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint VendorSell(uint vendor, uint* ids, int count) + { + var list = new uint[count]; + for (int i = 0; i < count; i++) list[i] = ids[i]; + Sells.Add(list); + _onSell?.Invoke(list); + return ++_lastRequest; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetVendorTradeStatus(VendorTradeStatusNative* status) + { + *status = default; + if (_lastRequest == 0) return 0; + status->RequestId = _lastRequest; + status->State = (int)VendorTradeState.Done; + status->Result = (int)VendorTradeResult.Accepted; + status->VendorId = Vendor; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SplitStackInternal(uint id, uint container, int slot, int amount) + { + Splits.Add((id, container, slot, amount)); + _onSplit?.Invoke(id, amount); + return 1; + } + + // ── World ───────────────────────────────────────────────────────────────── + + private const string Profile = + "UTL\r\n1\r\n3\r\n" + + "B: Prismatic Tapers\r\n\r\n0;10;7;1\r\n3000\r\n4\r\n12\r\n20\r\nPrismatic Taper\r\n1\r\n" + + "B: Trade Note (250,000)\r\n\r\n0;1;7;12\r\n4\r\n15\r\n12\r\n250000\r\n19\r\n" + + "S: Trade Note\r\n\r\n0;3;7\r\n4\r\n15\r\n"; + + private static long _now; + + private static void AddStack(uint id, string name, uint type, uint wcid, int count, int unitValue, int max, bool appraised = true) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = type; + FakeHost.Wcids[id] = wcid; + FakeHost.Containers[id] = Player; + SetCount(id, count, unitValue); + FakeHost.Ints[(id, 11)] = max; + if (appraised) FakeHost.Appraised.Add(id); + } + + private static void SetCount(uint id, int count, int unitValue) + { + FakeHost.Ints[(id, 12)] = count; + FakeHost.Ints[(id, 19)] = count * unitValue; + } + + private static int Count(uint id) => FakeHost.Ints.TryGetValue((id, 12), out int c) ? c : 0; + + private static void Remove(uint id) + { + FakeHost.Containers.Remove(id); + FakeHost.Names.Remove(id); + } + + private sealed class Rig + { + public AutoVendorManager M = null!; + public WorldObjectCache Cache = null!; + public LegacyUiSettings Settings = null!; + public string ProfilePath = string.Empty; + } + + /// 40 notes and 2,964 of 3,000 wanted tapers in the pack, no pyreals. + private static Rig World(bool withNotes = true) + { + FakeHost.Reset(); + Splits.Clear(); Sells.Clear(); Buys.Clear(); + _onSplit = null; _onSell = null; _onBuy = null; + _coins = 0; _lastRequest = 0; + FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData + FakeHost.ContentsCalls = true; // the pack walk + FakeHost.Names[Player] = "Test Trader"; + FakeHost.Names[Vendor] = "Town Vendor"; + if (withNotes) AddStack(Notes, "Trade Note (250,000)", TypeNote, NoteWcid, 40, NoteValue, 250); + AddStack(Tapers, "Prismatic Taper", TypeComp, TaperWcid, 2964, 100, 5000); + FakeHost.ConfigureApi = Configure; + RynthCoreHost host = FakeHost.Create(Player); + + var rig = new Rig(); + rig.Cache = new WorldObjectCache(host); + rig.Cache.SetPlayerId(Player); + rig.Settings = new LegacyUiSettings { AutoVendorEnabled = true, AutoVendorTestMode = false, AutoVendorShowMerchantInfo = false }; + // The character folder is the first place a vendor's profile is looked for: the test's + // profile there, named for the vendor, is the one every open loads. + string charDir = Path.Combine(Program.TempRoot, "autovendor-char"); + Directory.CreateDirectory(Path.Combine(charDir, AutoVendorManager.ProfileSubfolder)); + rig.ProfilePath = Path.Combine(charDir, AutoVendorManager.ProfileSubfolder, "Town Vendor.utl"); + File.WriteAllText(rig.ProfilePath, Profile); + rig.M = new AutoVendorManager(host, rig.Settings, rig.Cache, Player, () => charDir); + return rig; + } + + /// The vendor opens (or its list is re-sent): AutoVendor starts when it isn't running. + private static void Open(Rig rig) => rig.M.OnVendorOpen(Vendor); + + private static readonly FieldInfo ScanAt = typeof(WorldObjectCache).GetField("_lastDirectInventoryScan", BindingFlags.Instance | BindingFlags.NonPublic)!; + + /// Moves the clock and ticks; the pack walk always reads the fakes fresh. + private static void Run(Rig rig, int ticks, long stepMs = 100) + { + for (int i = 0; i < ticks; i++) + { + _now += stepMs; + ScanAt.SetValue(rig.Cache, DateTime.MinValue); + rig.M.Tick(0); + } + } + + private static void Clocked(Action body) + { + var old = AutoVendorManager.Clock; + _now = 50_000_000; + AutoVendorManager.Clock = () => _now; + try { body(); } + finally { AutoVendorManager.Clock = old; FakeHost.ConfigureApi = null; } + } + + /// The server's split: a new stack of , not identified yet. + private static void ServerSplitsToNewStack(Rig rig, uint source, int amount, uint newId) + { + SetCount(source, Count(source) - amount, NoteValue); + AddStack(newId, "Trade Note (250,000)", TypeNote, NoteWcid, amount, NoteValue, 250, appraised: false); + rig.M.OnCreateObject(newId); + } + + /// Selling a note pays 250,000 and the note leaves the pack; a taper buy lands. + private static void ServerTrades() + { + _onSell = ids => { foreach (uint id in ids) { _coins += NoteValue * Math.Max(1, Count(id)); Remove(id); } }; + _onBuy = lines => { foreach (var (id, amount) in lines) if (id == Taper) { SetCount(Tapers, Count(Tapers) + amount, 100); _coins -= 115 * amount; } }; + } + + // ── Tests ───────────────────────────────────────────────────────────────── + + private static void SplitOffNoteIsSold() => Clocked(() => + { + var rig = World(); + ServerTrades(); + _onSplit = (id, amount) => ServerSplitsToNewStack(rig, id, amount, NewStack); + Open(rig); + Run(rig, 10); + + Check.Eq(Splits.Count, 1, "one split sent"); + Check.Eq(Splits[0].Id, Notes, "off the 40-note stack"); + Check.Eq(Splits[0].Amount, 1, "one note"); + Check.True(FakeHost.Logs.Any(l => l.Contains("new stack 0x80A00101")), "the new stack is known from the server's create"); + Check.True(FakeHost.IdRequests.Contains(NewStack), "the new stack is identified"); + Check.Eq(Sells.Count, 0, "nothing sold before the ID"); + + // Still no ID: AutoVendor waits instead of splitting a second note onto the first one's stack. + Run(rig, 10); + Check.Eq(Splits.Count, 1, "no second split while the split-off note is being identified"); + Check.True(FakeHost.Logs.Any(l => l.Contains("waiting for the ID of Trade Note (250,000) 0x80A00101")), "the wait is logged"); + + FakeHost.Appraised.Add(NewStack); + Run(rig, 20); + Check.Eq(Sells.Count, 1, "one sale"); + Check.True(Sells.Count > 0 && Sells[0].SequenceEqual(new[] { NewStack }), "the split-off note, though the Keep rule matches a one-note stack"); + Check.Eq(Buys.Count, 1, "then the buy"); + Check.True(Buys.Count > 0 && Buys[0].SequenceEqual(new[] { (Taper, 36) }), "36 tapers: 3,000 - 2,964"); + Check.Eq(Splits.Count, 1, "still one split"); + Check.Eq(Count(Notes), 39, "39 notes left"); + Check.False(FakeHost.Logs.Any(l => l.Contains("made no new stack") || l.Contains("made no stack")), "no split failure"); + }); + + private static void HandSplitSingleIsSold() => Clocked(() => + { + var rig = World(); + ServerTrades(); + AddStack(HandSingle, "Trade Note (250,000)", TypeNote, NoteWcid, 1, NoteValue, 250); // split off by hand + _onSplit = (id, amount) => ServerSplitsToNewStack(rig, id, amount, NewStack); + Open(rig); + Run(rig, 20); + + Check.Eq(Splits.Count, 0, "no split: a single note is already there"); + Check.True(Sells.Count > 0 && Sells[0].SequenceEqual(new[] { HandSingle }), "the loose note is sold"); + Check.Eq(Buys.Count, 1, "and the tapers bought"); + Check.Eq(Count(Notes), 40, "the 40-note stack untouched"); + }); + + private static void SplitResumesNextOpen() => Clocked(() => + { + var rig = World(); + ServerTrades(); + Open(rig); + Run(rig, 5); + Check.Eq(Splits.Count, 1, "the split was sent"); + + // The vendor closes before the server answers; the new stack arrives afterwards. + rig.M.OnVendorClose(Vendor); + Run(rig, 2); + ServerSplitsToNewStack(rig, Notes, 1, NewStack); + FakeHost.Appraised.Add(NewStack); + Run(rig, 5); + Check.True(FakeHost.Logs.Any(l => l.Contains("new stack 0x80A00101")), "the stack is recognised with no session running"); + + // Next open: the split-off note is sold, nothing split again. + Open(rig); + Run(rig, 25); + Check.Eq(Splits.Count, 1, "no second split at the next open"); + Check.True(Sells.Count > 0 && Sells[0].SequenceEqual(new[] { NewStack }), "the note split off last time is sold"); + Check.Eq(Buys.Count, 1, "and the buy goes through"); + }); + + private static void SplitJoinedStack() => Clocked(() => + { + var rig = World(); + ServerTrades(); + // A loose note (split off by hand) sits at the split's slot, and its ID never comes back. + AddStack(HandSingle, "Trade Note (250,000)", TypeNote, NoteWcid, 1, NoteValue, 250, appraised: false); + bool resolvedBeforeSecond = true; + _onSplit = (id, amount) => + { + if (Splits.Count >= 2 && !FakeHost.Logs.Any(l => l.Contains("went onto stack 0x80A00102"))) + resolvedBeforeSecond = false; + // The server puts the split-off units onto the stack at the slot: no new object. + SetCount(id, Count(id) - amount, NoteValue); + SetCount(HandSingle, Count(HandSingle) + amount, NoteValue); + }; + Open(rig); + Run(rig, 200); // the session's ID pass and the loose note's IDs run out first (~9 s) + + Check.True(Splits.Count >= 1, "the split was sent once the loose note's ID gave up"); + Check.True(FakeHost.Logs.Any(l => l.Contains("waiting for the ID of Trade Note (250,000) 0x80A00102")), "it waited for that ID first"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no new object; the units went onto stack 0x80A00102 (now x2)")), "the joined stack is recognised"); + Check.False(FakeHost.Logs.Any(l => l.Contains("made no new stack")), "not the old 'made no new stack'"); + Check.True(resolvedBeforeSecond, "a later split only after the first one's result was known"); + }); + + private static void NoSecondSplitInFlight() => Clocked(() => + { + var rig = World(); + ServerTrades(); + _onSplit = null; // the server never answers + Open(rig); + Run(rig, 50); // 5 s: the split's 10 s wait is not over + Check.Eq(Splits.Count, 1, "one split in flight, no second one"); + Run(rig, 60); // 11 s: the wait is over, the failure says what happened, one retry + Check.True(FakeHost.Logs.Any(l => l.Contains("changed nothing (the server didn't split it; still x40)")), "the failure names the cause"); + Check.Eq(Splits.Count, 2, "a retry only after the first split's wait ended"); + }); + + private static void CantBuySaysWhy() => Clocked(() => + { + var rig = World(withNotes: false); + Open(rig); + Run(rig, 10); + string want = "can't buy 36x Prismatic Taper (rule 'B: Prismatic Tapers'): 115 pyreals each, you have 0"; + Check.True(FakeHost.Logs.Any(l => l.Contains(want)), "the log says why"); + Check.True(FakeHost.Chat.Any(l => l.Contains(want)), "so does chat"); + Check.True(FakeHost.Logs.Any(l => l.Contains("AutoVendor finished: Town Vendor")), "the session end is in the log"); + }); + + private static void LetterIsNoTradeNote() => Clocked(() => + { + var rig = World(withNotes: false); + AddStack(Letter, "Scarlet Red Letter", TypeWritable, 99001, 1, 5, 1); + Open(rig); + Run(rig, 10); + Check.False(FakeHost.Logs.Any(l => l.Contains("Scarlet Red Letter") && l.Contains("needs Object Class data")), + "a writable is never a TradeNote: the Sell rule simply doesn't match it"); + Check.Eq(Sells.Count, 0, "and it isn't sold"); + }); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorZeroRateTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorZeroRateTests.cs new file mode 100644 index 0000000..002c3ea --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorZeroRateTests.cs @@ -0,0 +1,33 @@ +using RynthCore.Plugin.RynthAi.Vendor; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +/// +/// AutoVendor's prices for a free vendor (buy=0 sell=0, a storage vault): 0 both ways, as the engine +/// prices it since AwfulWaffle's RynthCore PR #10, so the planner never thinks a free trade costs money. +/// +internal static class AutoVendorZeroRateTests +{ + public static void Register(Runner r) + { + r.Add("autovendor prices: a zero-rate (free) vendor costs and pays 0; any rate above 0 keeps ACE's 1 floor", ZeroRatePrices); + } + + private static void ZeroRatePrices() + { + var free = new VendorView { BuyRate = 0f, SellRate = 0f }; + Check.Eq(AutoVendorPlanner.PlayerPays(free, isNote: false, 1), 0L, "free vendor: a 1-value stack costs 0"); + Check.Eq(AutoVendorPlanner.PlayerPays(free, isNote: false, 250_000), 0L, "free vendor: a big stack costs 0"); + Check.Eq(AutoVendorPlanner.PlayerPays(free, isNote: true, 250_000), 0L, "free vendor: a note costs 0"); + Check.Eq(AutoVendorPlanner.VendorPays(free, isNote: false, 250_000), 0L, "free vendor: pays 0"); + Check.Eq(AutoVendorPlanner.VendorPays(free, isNote: true, 250_000), 0L, "free vendor: pays 0 for a note"); + + var shop = new VendorView { BuyRate = 0.75f, SellRate = 1.15f }; + Check.Eq(AutoVendorPlanner.PlayerPays(shop, isNote: false, 100), 115L, "rate 1.15, value 100: 115"); + Check.Eq(AutoVendorPlanner.VendorPays(shop, isNote: false, 100), 75L, "rate 0.75, value 100: 75"); + Check.Eq(AutoVendorPlanner.PlayerPays(shop, isNote: false, 0), 1L, "a rate above 0 keeps the 1-per-stack floor"); + var tiny = new VendorView { BuyRate = 0.001f, SellRate = 0.001f }; + Check.Eq(AutoVendorPlanner.VendorPays(tiny, isNote: false, 1), 1L, "rate 0.001 still floors at 1"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CommandReplyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CommandReplyTests.cs index 5227c4b..70f99fb 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CommandReplyTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CommandReplyTests.cs @@ -95,6 +95,7 @@ internal static class CommandReplyTests new(null, "/ra igp NoSuchProfileHere", K.Act), new("/ra cast 1234", "/ra cast banana", K.Act), new("/ra targetlock off", null, K.Act), + new("/ra fightselected off", "/ra fightselected banana", K.Act), new("/ra meleelow", null, K.Act), new("/ra meleemid", null, K.Act), new("/ra meleehigh", null, K.Act), @@ -125,6 +126,9 @@ internal static class CommandReplyTests new(null, "/ra settings loadchar", K.Act), new(null, "/ra loot add banana", K.Act), new(null, "/ra loot why", K.Act), // nothing selected: says so + new("/ra loot mode rares", "/ra loot mode banana", K.Act), + new("/ra loot mode profile", null, K.Act), + new("/ra loot mode", null, K.Query), new(null, "/ra lootparse", K.Act), new(null, "/ra lootcheckinv", K.Act), new(null, "/ra autotrade", K.Act), diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/FightSelectedTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/FightSelectedTests.cs new file mode 100644 index 0000000..58a0737 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/FightSelectedTests.cs @@ -0,0 +1,424 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// "Fight the monster I select" (2026-11-01, CombatManager.SelectedTarget.cs): a monster the +// player selects in a fight is fought first, until it dies, can't be reached, or the player +// selects another monster / deselects. The bot's own selections (ItemInfo.SelfSelect) never count. +internal static class FightSelectedTests +{ + private const uint Player = 0x50000F21; + private const uint Lb = 0xA9B40000; + private const uint A = 0x80000A01, B = 0x80000A02, Boss = 0x80000A03, Far = 0x80000A04, + Npc = 0x80000A05, Corpse = 0x80000A06, Skip = 0x80000A07, Never = 0x80000A08, Pk = 0x80000A09; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("fight selected: off (the default) changes nothing", OffNoChange); + r.Add("fight selected: the player's selection of a lower-priority monster wins; another selection moves it, a deselect ends it", PlayerSelectionWins); + r.Add("fight selected: the bot's own selections never count (native attack, looter, meta)", BotSelectionNeverCounts); + r.Add("fight selected: an NPC, a corpse, a player, yourself, an ignored or never-attack monster change nothing", NonMonstersNothing); + r.Add("fight selected: the chosen monster dying returns to normal priority, quietly", DeathReturnsToNormal); + r.Add("fight selected: past Disengage Range it's said once, fought if it comes close, dropped after 30 s", OutOfRange); + r.Add("fight selected: a /ra targetlock lock is never moved; /ra targetlock on the selected one makes it explicit", TargetLockInteraction); + r.Add("fight selected: the setting off releases it; /ra fightselected, the settings face, profiles, metas", SettingPlumbing); + r.Add("fight selected: /ra why says it is fighting the monster you selected", WhySaysSo); + } + + // ── Rig ─────────────────────────────────────────────────────────────────── + + private sealed class Rig + { + public readonly CombatManager Combat; + public readonly LegacyUiSettings S; + public readonly WorldObjectCache Cache; + public readonly RynthCoreHost Host; + private DateTime _now = DateTime.Now; + + public Rig(bool on = true) + { + FakeHost.Reset(); + SelfSelect.Reset(); + Place(Player, "Me", 96, 96, creature: false); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + Place(A, "Mob A", 96, 98); + Place(B, "Mob B", 96, 102); + Place(Boss, "Boss", 96, 100); + Place(Far, "Far Mob", 96, 136); // 40 m: past Disengage Range (20 + 3) + Place(Skip, "Harmless Bug", 96, 99); + Place(Never, "Never Mob", 96, 99); + Place(Pk, "Someone", 96, 99); + FakeHost.Wcids[Pk] = 1; // a player's weenie, classed as a monster by the cache + Place(Npc, "Town Crier", 96, 97); + FakeHost.NotAttackable.Add(Npc); + Place(Corpse, "Corpse of Mob A", 96, 97, creature: false); + FakeHost.ItemTypes[Corpse] = 0x200; + FakeHost.Bitfields[Corpse] = 0x00002000; + FakeHost.NotAttackable.Add(Corpse); + S = new LegacyUiSettings + { + MonsterRange = 20, TargetSelection = 1 /* closest */, TargetLock = true, + IsMacroRunning = true, EnableCombat = true, FightSelectedTarget = on, + }; + S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 }); + S.MonsterRules.Add(new MonsterRule { Name = "Harmless Bug", Priority = 0 }); + var host = FakeHost.Create(); + Host = host; + Cache = FakeHost.MakeCache(host, Player, new[] { A, B, Boss, Far, Skip, Never, Pk, Npc, Corpse }); + Combat = new CombatManager(host, S, Cache); + Combat.SetPlayerId(Player); + Combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore()); + Combat.TargetClock = () => _now; + } + + public void Advance(double ms) => _now = _now.AddMilliseconds(ms); + + public uint Pick(params (uint Id, double Dist)[] scan) + { + Combat.SetScannedTargetsForTests(scan.Select(t => new CombatManager.ScannedTarget + { + Id = unchecked((int)t.Id), Distance = t.Dist, Angle = 0, Bearing = double.NaN, Name = FakeHost.Names[t.Id], + })); + Combat.HandleCombatTrigger(); + return unchecked((uint)Combat.activeTargetId); + } + + /// The player selects (0 = deselect). + public string? Select(uint id) => Combat.OnSelectionChanged(id, SelfSelect.IsOurs(id)); + public int Forced => Combat.ForcedTargetId; + } + + private static void Place(uint id, string name, float x, float y, bool creature = true) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f); + if (creature) FakeHost.ItemTypes[id] = 0x10; + } + + private static int I(uint id) => unchecked((int)id); + + // ── Tests ───────────────────────────────────────────────────────────────── + + private static void OffNoChange() + { + Check.False(new LegacyUiSettings().FightSelectedTarget, "off by default"); + var t = new Rig(on: false); + Check.Eq(t.Pick((A, 2), (B, 6)), A, "closest: A"); + Check.Eq(t.Select(B), null, "selecting B: nothing"); + Check.Eq(t.Forced, 0, "no lock"); + Check.Eq(t.Pick((A, 2), (B, 6)), A, "still A"); + t.Select(0); + Check.Eq(t.Pick((A, 2), (B, 6)), A, "a deselect: still A"); + } + + private static void PlayerSelectionWins() + { + var t = new Rig(); + Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), Boss, "normal: the Boss's priority wins"); + Check.Eq(t.Select(B), "locked", "the player selects B"); + Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), B, "B (priority 1, farther) over the Boss and the closer A"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch") && l.Contains("fight the monster I select: selected by the player")), + "the switch line says why"); + Check.Eq(t.Pick((A, 1), (B, 6), (Boss, 3)), B, "kept while the others come closer"); + + Check.Eq(t.Select(A), "locked", "the player selects A"); + Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), A, "the lock moves to A"); + Check.True(FakeHost.Logs.Any(l => l.Contains("(the player selected another monster,")), "the switch says so"); + + Check.Eq(t.Select(0), "deselected", "the player deselects"); + Check.Eq(t.Forced, 0, "the lock is gone"); + Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), Boss, "normal priority again: the Boss"); + Check.True(t.Combat.ForcedBySelection == false, "and nothing forced"); + Check.False(FakeHost.Chat.Any(c => c.Contains("Stopped fighting")), "no chat for a selection or a deselect"); + + // Only while the macro runs with Combat on. + t = new Rig(); + t.S.IsMacroRunning = false; + Check.Eq(t.Select(B), null, "macro off: a selection isn't followed"); + t.S.IsMacroRunning = true; + t.S.EnableCombat = false; + Check.Eq(t.Select(B), null, "Combat off: not followed either"); + } + + private static void BotSelectionNeverCounts() + { + var t = new Rig(); + var bot = new Bot(t); + long clock = 1_000_000; + SelfSelect.Clock = () => clock; + try + { + Check.Eq(t.Pick((A, 2), (B, 6)), A, "fighting A"); + + // Combat's native attack (SelectAsBot), the looter, a meta: all marked before the select. + SelfSelect.SelectAsBot(t.Host, A); + bot.P.OnSelectedTargetChange(A, 0); + Check.Eq(t.Forced, 0, "the bot selecting its own target: not the player's"); + SelfSelect.Mark(B); // e.g. a meta's selectitem + bot.P.OnSelectedTargetChange(B, A); + Check.Eq(t.Forced, 0, "the bot selecting another monster: not the player's"); + Check.Eq(t.Pick((A, 2), (B, 6)), A, "still A"); + + // Several marks in a row: the earlier ones are still the bot's (not just the last). + SelfSelect.Mark(Boss); + bot.P.OnSelectedTargetChange(A, Boss); + Check.Eq(t.Forced, 0, "an earlier mark (A) is still ours after a later one (Boss)"); + + // The same monster selected by the player once the mark has expired. + clock += SelfSelect.WindowMs + 1; + bot.P.OnSelectedTargetChange(B, A); + Check.Eq(t.Forced, I(B), "the player's click on B (no fresh mark): followed"); + Check.True(t.Combat.ForcedBySelection, "as a selection lock"); + + // The bot re-selecting its old target while the player's pick is pending changes nothing. + SelfSelect.SelectAsBot(t.Host, A); + bot.P.OnSelectedTargetChange(A, B); + Check.Eq(t.Forced, I(B), "the bot's native-attack re-select of A doesn't undo the player's B"); + Check.Eq(t.Pick((A, 2), (B, 6)), B, "B is fought"); + } + finally + { + SelfSelect.Clock = () => Environment.TickCount64; + SelfSelect.Reset(); + } + } + + private static void NonMonstersNothing() + { + var t = new Rig(); + t.S.MonsterNameBlacklist.Add("Never Mob"); + Check.True(t.Select(Npc)?.Contains("can't be attacked") == true, "an NPC: not followed"); + Check.True(t.Select(Corpse)?.Contains("isn't a monster") == true, "a corpse: not followed"); + Check.Eq(t.Select(Player), "that's you", "yourself: not followed"); + Check.True(t.Select(Pk)?.Contains("is a player") == true, "a player (by weenie): not followed"); + Check.True(t.Select(Skip)?.Contains("Priority 0") == true, "an ignored (Priority 0) monster: not followed"); + Check.True(t.Select(Never)?.Contains("never-attack") == true, "a never-attack monster: not followed"); + Check.Eq(t.Forced, 0, "no lock from any of them"); + + // With a selected monster being fought, those selections leave it alone. + t.Select(B); + Check.Eq(t.Pick((A, 2), (B, 6)), B, "fighting the selected B"); + foreach (uint id in new[] { Npc, Corpse, Player, Pk, Skip, Never }) + t.Select(id); + Check.Eq(t.Forced, I(B), "B is still the selected target"); + Check.Eq(t.Pick((A, 2), (B, 6)), B, "and still fought"); + Check.False(FakeHost.Logs.Any(l => l.Contains("fight-selected") && l.Contains("Corpse of")), "a corpse click isn't even logged"); + } + + private static void DeathReturnsToNormal() + { + var t = new Rig(); + t.Select(B); + Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), B, "fighting the selected B"); + t.Cache.OnUpdateHealth(B, 0f); + Check.Eq(t.Pick((A, 2), (Boss, 4)), Boss, "B died: normal priority, the Boss"); + Check.Eq(t.Forced, 0, "the lock is over"); + Check.True(FakeHost.Logs.Any(l => l.Contains("fight-selected") && l.Contains("ended: it died")), "logged"); + Check.False(FakeHost.Chat.Any(c => c.Contains("Stopped fighting")), "no chat for the normal end"); + + // Its kill notice ends it too. + t = new Rig(); + t.Select(Boss); + t.Pick((A, 2), (Boss, 4)); + t.Combat.OnKillNotification("You killed Boss!"); + Check.Eq(t.Pick((A, 2), (B, 6)), A, "killed: the closest again"); + Check.Eq(t.Forced, 0, "and the lock is over"); + } + + private static void OutOfRange() + { + var t = new Rig(); + Check.Eq(t.Select(Far), "far", "40 m away: past the 23 m reach"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Far Mob is 40 yd away, past Disengage Range (23 yd)") && c.Contains("not chasing")), + "said in chat: " + string.Join(" | ", FakeHost.Chat)); + int lines = FakeHost.Chat.Count; + t.Select(0); + Check.Eq(t.Select(Far), "far", "selected again"); + Check.Eq(FakeHost.Chat.Count, lines, "said once per monster"); + + Check.Eq(t.Pick((A, 2)), A, "not in the scan (it is never chased): A meanwhile"); + t.Advance(10_000); + Check.Eq(t.Pick((A, 2), (Far, 15)), Far, "it comes within range: fought"); + + // Never comes close: dropped 30 s after the click, with one line. + t = new Rig(); + t.Select(Far); + t.Advance(CombatManager.ForcedTargetLostMs - 1000); + Check.Eq(t.Pick((A, 2)), A, "29 s: A, the lock waits"); + Check.Eq(t.Forced, I(Far), "still waiting"); + t.Advance(2000); + Check.Eq(t.Pick((A, 2)), A, "31 s"); + Check.Eq(t.Forced, 0, "dropped"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Stopped fighting the monster you selected (Far Mob): never in reach")), + "and says why: " + string.Join(" | ", FakeHost.Chat)); + + // Selected, deselected and selected again: the 30 s restart from the new click. + t = new Rig(); + t.Select(Far); + t.Pick((A, 2)); + t.Advance(25_000); + t.Select(0); + t.Pick((A, 2)); + t.Select(Far); + t.Advance(10_000); + t.Pick((A, 2)); + Check.Eq(t.Forced, I(Far), "35 s after the first click, 10 s after the second: still waiting"); + } + + private static void TargetLockInteraction() + { + // A /ra targetlock lock is never moved by a selection. + var t = new Rig(); + t.Combat.SetForcedTarget(I(B)); + Check.Eq(t.Select(A), null, "selecting A under a /ra targetlock lock: nothing"); + Check.Eq(t.Select(0), null, "nor a deselect"); + Check.Eq(t.Forced, I(B), "the lock stays on B"); + Check.False(t.Combat.ForcedBySelection, "as the explicit lock"); + Check.True(FakeHost.Logs.All(l => !l.Contains("fight-selected")), "and nothing logged for it"); + + // The commands. + t = new Rig(); + var bot = new Bot(t); + FakeHost.SelectedItem = A; + bot.P.OnSelectedTargetChange(A, 0); + Check.True(t.Combat.ForcedBySelection && t.Forced == I(A), "the player selects A: fought by the setting"); + bot.Ra("/ra targetlock"); + Check.Eq(t.Forced, I(A), "/ra targetlock on it: still A (not released)"); + Check.False(t.Combat.ForcedBySelection, "now the explicit lock"); + Check.True(bot.LastChat.Contains("no longer moves it"), "chat: " + bot.LastChat); + FakeHost.SelectedItem = B; + bot.P.OnSelectedTargetChange(B, A); + Check.Eq(t.Forced, I(A), "selecting B doesn't move the explicit lock"); + bot.Ra("/ra targetlock off"); + Check.Eq(t.Forced, 0, "/ra targetlock off releases it"); + + // /ra targetlock off also ends a selection lock. + bot.P.OnSelectedTargetChange(A, B); + bot.P.OnSelectedTargetChange(B, A); + Check.True(t.Combat.ForcedBySelection && t.Forced == I(B), "selection lock on B"); + bot.Ra("/ra targetlock off"); + Check.Eq(t.Forced, 0, "/ra targetlock off ends the selection lock too"); + + // The Target Lock setting (keep the incumbent) is a different thing: it doesn't stop the switch. + t = new Rig(); + t.S.TargetLock = true; + Check.Eq(t.Pick((A, 2), (B, 6)), A, "Target Lock (setting) holds A"); + t.Select(B); + Check.Eq(t.Pick((A, 2), (B, 6)), B, "the player's selection still switches to B"); + t.S.TargetLock = false; + t.Select(A); + Check.Eq(t.Pick((A, 2), (B, 6)), A, "Target Lock off: the same"); + } + + private static void SettingPlumbing() + { + // Turned off mid-fight: released on the next tick, quietly. + var t = new Rig(); + t.Select(B); + Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), B, "fighting the selected B"); + t.S.FightSelectedTarget = false; + Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), Boss, "the setting off: normal priority"); + Check.Eq(t.Forced, 0, "released"); + Check.False(FakeHost.Chat.Any(c => c.Contains("Stopped fighting")), "no chat line"); + + // /ra fightselected [on|off] (toggle without an argument); every reply says the state. + t = new Rig(on: false); + var bot = new Bot(t); + bot.Ra("/ra fightselected"); + Check.True(bot.S.FightSelectedTarget, "toggle: on"); + Check.True(bot.LastChat.Contains("Fight the monster I select: on"), bot.LastChat); + bot.Ra("/ra fightselected on"); + Check.True(bot.S.FightSelectedTarget, "on: on"); + bot.P.OnSelectedTargetChange(B, 0); + Check.True(t.Combat.ForcedBySelection, "selection followed"); + bot.Ra("/ra fightselected off"); + Check.False(bot.S.FightSelectedTarget, "off"); + Check.Eq(t.Forced, 0, "off releases the selection lock at once"); + Check.True(bot.LastChat.Contains("Fight the monster I select: off"), bot.LastChat); + bot.Ra("/ra fightselected banana"); + Check.True(bot.LastChat.Contains("Usage: /ra fightselected [on|off]"), bot.LastChat); + Check.False(bot.S.FightSelectedTarget, "an unknown argument changes nothing"); + + // Profiles: an old profile loads it off; a profile's value is copied. + var loaded = System.Text.Json.JsonSerializer.Deserialize("{\"MonsterRange\":7}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(loaded != null && !loaded.FightSelectedTarget, "a profile saved before the setting loads it off"); + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { FightSelectedTarget = true }, dst }); + Check.True(dst.FightSelectedTarget, "a profile's value is copied"); + string json = System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { FightSelectedTarget = true }, RynthAiJsonContext.Default.LegacyUiSettings); + var back = System.Text.Json.JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(json.Contains("FightSelectedTarget") && back != null && back.FightSelectedTarget, "saved with the profile"); + + // The engine Settings face: sent; a save without the field leaves it alone. + var s = new LegacyUiSettings { FightSelectedTarget = true }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); + var sent = System.Text.Json.JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.FightSelectedTarget == true, "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.True(s.FightSelectedTarget, "an engine without the field leaves it alone"); + dash.ApplySettingsJson("{\"FightSelectedTarget\":false}"); + Check.False(s.FightSelectedTarget, "a save with it sets it"); + + // Metas: rasetsetting / ragetsetting. + var e = ExpressionTests.Engine(settings: s); + Check.Eq(e.Evaluate("rasetsetting[FightSelectedTarget, 1]"), "1", "meta sets it"); + Check.True(s.FightSelectedTarget, "on"); + Check.Eq(e.Evaluate("ragetsetting[FightSelectedTarget]"), "1", "meta reads it"); + } + + private static void WhySaysSo() + { + var t = new Rig(); + var bot = new Bot(t); + bot.P.OnSelectedTargetChange(B, 0); + t.Pick((A, 2), (B, 6)); + FakeHost.Chat.Clear(); + bot.Ra("/ra why"); + Check.True(bot.AllChat.Contains("fighting the monster you selected: Mob B"), "the target line: " + bot.AllChat); + Check.True(bot.AllChat.Contains("likely: fighting the monster you selected"), "the interpretation: " + bot.AllChat); + } + + // ── Plugin harness ─────────────────────────────────────────────────────── + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S; + + public Bot(Rig t) + { + S = t.S; + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Set("_objectCache", t.Cache); + Set("_playerId", Player); + Set("_combatManager", t.Combat); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public void Ra(string line) + { + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + object[] args = { parts[1].ToLowerInvariant(), parts, 0 }; + typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, args); + } + public string LastChat => FakeHost.Chat.Count > 0 ? FakeHost.Chat[^1] : ""; + public string AllChat => string.Join(" | ", FakeHost.Chat); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/KillNoticeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/KillNoticeTests.cs new file mode 100644 index 0000000..fa91cd0 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/KillNoticeTests.cs @@ -0,0 +1,309 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.CreatureData; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-11-01: looting mid-fight, and lesser monsters fought while a top-priority one stood by. +// A kill notice carries only the dead monster's name. In a pack of same-named monsters two things +// matched it to the wrong one: +// - in Melee mode a dual-wield or multi-strike weapon's second hit (about 0.3 s after the first) +// was handed to the nearest other monster of that name by the spell "volley" rule, so a +// neighbour we never touched counted as hit by us; +// - some kills brought two notices 1-2 ms apart (one corpse); the second was matched to that +// neighbour. +// The neighbour was kept out of the scan for 4 s while alive: with no other monster scanned the +// arbiter gave Looting the tick (a corpse opened with the monster 3 m away), and in a mixed pack +// the top tier was empty, so a lower-priority monster was locked. +internal static class KillNoticeTests +{ + private const uint Player = 0x50000F01; + private const uint Lb = 0xA9B40000; + private const uint SentryWcid = 2001, LesserWcid = 2002; + private const string Sentry = "Drumtaken Sentry"; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("kill notice (melee): a dual-wield second hit stays on the fight target, not a same-named neighbour", MeleeSecondHitStaysOnTarget); + r.Add("kill notice (melee): the fight target's notice drops it even with stale server health", MeleeKillDropsTargetNotNeighbour); + r.Add("kill notice: a second notice for the same death is an echo - no one hidden, one kill", EchoHidesNoOne); + r.Add("kill notice: a death matched by name holds combat (no looting) until confirmed or 2 s", GuessedDeathHoldsCombat); + r.Add("kill notice: the fight is over when the last monster dies - looting gets the tick", FightOverLoots); + r.Add("targeting: a top-priority monster's tier holds while its death is only a guess", GuessedDeathHoldsTier); + r.Add("targeting (melee): after a kill and its echo the same-named top priority is next, not a lesser one", EchoKeepsTopPriorityNext); + } + + // ── The rig ────────────────────────────────────────────────────────────── + + private sealed class Rig + { + public readonly LegacyUiSettings S = new() { MonsterRange = 10, TargetSelection = 1, TargetLock = true, EnableCombat = true }; + public readonly MonsterDamageStore Store = new(); + public CombatManager C = null!; + public WorldObjectCache Cache = null!; + public DateTime Now = RynthClock.Now; + private readonly List _ids = new(); + private uint _next = 0x80000501; + + public Rig(int mode) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // installs GetCurrentCombatMode + FakeHost.CombatModeValue = mode; + FakeHost.Names[Player] = "Me"; + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + } + + public uint Mob(string name, uint wcid, float north, float east = 0) + { + uint id = _next++; + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1C, 96f + east, 96f + north, 0f); + FakeHost.ItemTypes[id] = 0x10; + FakeHost.Wcids[id] = wcid; + _ids.Add(id); + return id; + } + + public void Build(uint fightTarget = 0) + { + var host = FakeHost.Create(); + Cache = FakeHost.MakeCache(host, Player, _ids); + C = new CombatManager(host, S, Cache); + C.SetPlayerId(Player); + C.SetDamageStores(null, Store); + C.TargetClock = () => Now; + if (fightTarget != 0) C.EngageForTest(unchecked((int)fightTarget)); + } + + public void Rescan() + { + typeof(CombatManager).GetField("_lastScanTime", Any)!.SetValue(C, DateTime.MinValue); + C.ScanNearbyTargets(); + } + + public bool Scanned(uint id) => C.ScannedTargets.Any(t => t.Id == unchecked((int)id)); + public bool Suppressed(uint id) => C.IsKillSuppressed(unchecked((int)id)); + public int Kills(uint wcid) => Store.Snapshot().Where(r => r.Wcid == wcid).Sum(r => r.KillSamples); + + /// The arbiter's pick with this combat state, a lootable corpse and a route. + public BotActivity Decide() + { + var inputs = new ArbiterInputs(true, false, S.EnableCombat && C.HasEngageableTarget, true, false, true, + combatEngaged: C.IsUnderCloseAttack); + return ActivityArbiter.Decide(in inputs); + } + } + + private static int Id(uint id) => unchecked((int)id); + + // ── Melee: one swing, one monster ──────────────────────────────────────── + + private static void MeleeSecondHitStaysOnTarget() + { + var rig = new Rig(CombatMode.Melee); + uint target = rig.Mob(Sentry, SentryWcid, 2); + uint twin = rig.Mob(Sentry, SentryWcid, 3); + rig.Build(target); + rig.Store.SetManualHp(SentryWcid, 200); + + // Main hand, then off hand 0.3 s later (inside the 0.8 s volley window). + rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 10 points of acid damage!"); + rig.C.HandleChatForDamage("You numb Drumtaken Sentry for 12 points of cold damage!"); + + Check.False(rig.Cache.IsHealthEstimated(Id(twin)), "the neighbour gets no damage estimate (it was never hit)"); + Check.Near(rig.Cache.GetHealthRatio(Id(twin)), -1, 1e-6, "its health stays unknown"); + + // The same two lines in Magic mode still go to two monsters (a ring or chain: one line each). + var magic = new Rig(CombatMode.Magic); + uint mt = magic.Mob(Sentry, SentryWcid, 2); + uint mtwin = magic.Mob(Sentry, SentryWcid, 3); + magic.Build(mt); + magic.Store.SetManualHp(SentryWcid, 200); + magic.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI."); + magic.C.HandleChatForDamage("You blast Drumtaken Sentry for 50 points with Flame Ring VI."); + Check.True(magic.Cache.IsHealthEstimated(Id(mtwin)), "magic: the second line of a volley is the neighbour's"); + } + + private static void MeleeKillDropsTargetNotNeighbour() + { + var rig = new Rig(CombatMode.Melee); + uint target = rig.Mob(Sentry, SentryWcid, 2); + uint twin = rig.Mob(Sentry, SentryWcid, 3); + rig.Build(target); + rig.Cache.OnUpdateHealth(target, 0.38f); // the last health the server sent; no 0 came with the killing blow + rig.C.OnCombatDamage(40, 1, false, true); + rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 40 points of acid damage!"); + rig.C.HandleChatForDamage("You numb Drumtaken Sentry for 30 points of cold damage!"); + + rig.C.OnKillNotification("You knock Drumtaken Sentry into next Morningthaw!"); + + Check.Eq(rig.C.activeTargetId, 0, "the fight target is the one that died: dropped"); + Check.True(rig.Suppressed(target), "and kept off the scan while its corpse forms"); + Check.False(rig.Suppressed(twin), "the neighbour (never hit) is not taken for it"); + Check.False(FakeHost.Logs.Any(l => l.Contains("keeping the target")), "no 'a neighbour we hit died' guess"); + rig.Rescan(); + Check.True(rig.Scanned(twin), "the neighbour is still a candidate"); + } + + // ── Two notices, one death ─────────────────────────────────────────────── + + private static void EchoHidesNoOne() + { + var rig = new Rig(CombatMode.Melee); + uint target = rig.Mob(Sentry, SentryWcid, 2); + uint twin = rig.Mob(Sentry, SentryWcid, 3); + rig.Build(target); + rig.C.OnCombatDamage(40, 1, false, true); // one landed hit: the kill is credited to this fight + rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 40 points of acid damage!"); + + rig.C.OnKillNotification("You killed Drumtaken Sentry!"); + rig.C.OnKillNotification("Drumtaken Sentry suffers a frozen fate!"); // the same death, 1-2 ms later + + Check.False(rig.Suppressed(twin), "the echo hides no one"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[KillDbg] how=echo")), "it is logged as an echo"); + Check.Eq(rig.Kills(SentryWcid), 1, "one death, one kill counted"); + + rig.Rescan(); + Check.True(rig.Scanned(twin), "the live neighbour is scanned"); + Check.True(rig.C.HasEngageableTarget, "combat wants the tick"); + Check.Eq(rig.Decide(), BotActivity.Combat, "the arbiter keeps Combat: no looting with the neighbour 3 m away"); + + // Later than the echo window, a notice is a death of its own. + rig.Now = rig.Now.AddMilliseconds(KillNoticeWindow + 50); + rig.C.EngageForTest(Id(twin)); + rig.C.OnCombatDamage(40, 1, false, true); + rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 40 points of acid damage!"); + System.Threading.Thread.Sleep((int)KillNoticeWindow + 50); // the echo window runs on RynthClock + rig.C.OnKillNotification("Drumtaken Sentry died!"); + Check.Eq(rig.C.activeTargetId, 0, "the neighbour's own death later drops it"); + Check.Eq(rig.Kills(SentryWcid), 2, "and counts"); + } + + private static double KillNoticeWindow => CombatManager.KillEchoMs; + + // ── A death matched by name only ───────────────────────────────────────── + + /// Magic: a ring hits the target and its twin; the target dies (health 0), then a + /// notice of that name comes that may be the twin's. + private static Rig RingKillThenGuess(out uint target, out uint twin) + { + var rig = new Rig(CombatMode.Magic); + target = rig.Mob(Sentry, SentryWcid, 2); + twin = rig.Mob(Sentry, SentryWcid, 3); + rig.Build(target); + rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI."); + rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI."); + rig.Cache.OnUpdateHealth(target, 0f); + rig.C.OnKillNotification("Drumtaken Sentry died!"); + rig.C.OnKillNotification("Drumtaken Sentry's death is preceded by a sharp, stabbing pain!"); + return rig; + } + + private static void GuessedDeathHoldsCombat() + { + var rig = RingKillThenGuess(out _, out uint twin); + Check.True(rig.Suppressed(twin), "the twin was hit by the ring: the notice is taken for it"); + rig.Rescan(); + Check.False(rig.Scanned(twin), "it is kept off the scan for now"); + Check.True(rig.C.HasTargets, "but still counts as a monster in range"); + Check.True(rig.C.HasCloseThreat(RynthAiPlugin.LootStarveCloseYards), "and as a close threat (no starved loot turn)"); + Check.Eq(rig.Decide(), BotActivity.Combat, "so the arbiter keeps Combat, not Looting"); + + // No word of its death in 2 s: it is alive, a target again. + rig.Now = rig.Now.AddMilliseconds(2100); + rig.Rescan(); + Check.True(rig.Scanned(twin), "after 2 s it is scanned again"); + Check.True(FakeHost.Logs.Any(l => l.Contains("matched by name") && l.Contains("still alive: it is a target again")), + "and the log says the guess was wrong"); + + // A hit on it ends the hold at once. + rig = RingKillThenGuess(out _, out twin); + rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 80 points with Flame Ring VI."); + Check.False(rig.Suppressed(twin), "a damage line on it says it is alive"); + } + + private static void FightOverLoots() + { + // The guessed twin really died: its corpse (health 0) ends the hold, and the fight is over. + var rig = RingKillThenGuess(out _, out uint twin); + rig.Cache.OnUpdateHealth(twin, 0f); + rig.Rescan(); + Check.False(rig.C.HasTargets, "both dead: nothing in range"); + Check.False(rig.C.HasEngageableTarget, "combat lets the tick go"); + Check.Eq(rig.Decide(), BotActivity.Looting, "looting gets the tick"); + + // A lone kill: looting right after it. + var lone = new Rig(CombatMode.Melee); + uint mob = lone.Mob(Sentry, SentryWcid, 2); + lone.Build(mob); + lone.C.OnCombatDamage(40, 1, false, true); + lone.C.OnKillNotification("You killed Drumtaken Sentry!"); + lone.C.OnKillNotification("Drumtaken Sentry suffers a frozen fate!"); + lone.Rescan(); + Check.False(lone.C.HasEngageableTarget, "the last monster died: no combat"); + Check.Eq(lone.Decide(), BotActivity.Looting, "the arbiter loots"); + } + + // ── Priority ───────────────────────────────────────────────────────────── + + private static void UseRules(Rig rig) + => rig.S.MonsterRules = new List + { + new MonsterRule { Name = "Default", Priority = 1 }, + new MonsterRule { Name = Sentry, Priority = 5 }, + }; + + private static void GuessedDeathHoldsTier() + { + var rig = new Rig(CombatMode.Magic); + UseRules(rig); + uint target = rig.Mob(Sentry, SentryWcid, 2); + uint twin = rig.Mob(Sentry, SentryWcid, 4); + uint lesser = rig.Mob("Drumtaken Lesser Siraluun", LesserWcid, 3); + rig.Build(target); + rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI."); + rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI."); + rig.Cache.OnUpdateHealth(target, 0f); + rig.C.OnKillNotification("Drumtaken Sentry died!"); + rig.C.OnKillNotification("Drumtaken Sentry's death is preceded by a sharp, stabbing pain!"); + + rig.Rescan(); + Check.True(rig.Scanned(lesser) && !rig.Scanned(twin), "the scan has only the Priority 1 monster"); + rig.C.HandleCombatTrigger(); + Check.Eq(rig.C.activeTargetId, 0, "the Priority 1 monster isn't locked while the Priority 5 twin may be alive"); + + rig.Now = rig.Now.AddMilliseconds(2100); + rig.Rescan(); + rig.C.HandleCombatTrigger(); + Check.Eq(rig.C.activeTargetId, Id(twin), "the twin was alive: it is the target, not the lesser one"); + } + + private static void EchoKeepsTopPriorityNext() + { + var rig = new Rig(CombatMode.Melee); + UseRules(rig); + uint target = rig.Mob(Sentry, SentryWcid, 2); + uint twin = rig.Mob(Sentry, SentryWcid, 4); + uint lesser = rig.Mob("Drumtaken Lesser Siraluun", LesserWcid, 3); + rig.Build(target); + rig.C.OnCombatDamage(40, 1, false, true); + rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 40 points of acid damage!"); + rig.C.HandleChatForDamage("You numb Drumtaken Sentry for 30 points of cold damage!"); + rig.C.OnKillNotification("You killed Drumtaken Sentry!"); + rig.C.OnKillNotification("Drumtaken Sentry suffers a frozen fate!"); + + rig.Rescan(); + rig.C.HandleCombatTrigger(); + Check.Eq(rig.C.activeTargetId, Id(twin), "the Priority 5 twin is next (it was 4 s out of the scan before)"); + Check.True(rig.Scanned(lesser), "the lesser one was a candidate too"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs index a574943..5fe06bd 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs @@ -43,6 +43,33 @@ internal static class LootAddItemTests r.Add("loot add: unsaved edits in the Loot Editor block the add (nothing saved behind them)", BridgeRefusesUnderEdits); r.Add("loot add: the popup says when RynthAi's built-in looting takes the item (Mana Tap, mana stones)", BuiltInReasons); r.Add("loot: Mana Tap takes a high-mana wand like any other item (they drain)", ManaTapTakesWands); + r.Add("loot profile load (R-20261101-133624-7eeb): a rule with no conditions is named in chat; a normal profile says nothing", UnconditionalRuleWarned); + } + + // A 'Trade Note' that lost its Name condition keeps every item silently; loading says so. + private static void UnconditionalRuleWarned() + { + var bot = new Bot(); + string broken = Temp("broken-trade-note.utl", Utl( + "UTL", "1", "2", + "Trade Note", "", "0;1", + "Keep pyreals", "", "0;1;1", "0", "^Pyreal$", "1")); + bot.S.CurrentLootPath = broken; + FakeHost.Chat.Clear(); + object?[] load = { string.Empty, null, null }; + Check.True((bool)typeof(RynthAiPlugin).GetMethod("TryLoadLootProfile", Any)!.Invoke(bot.P, load)!, "it loads"); + string chat = bot.ChatText; + Check.True(chat.Contains("1 rule(s) have no conditions") && chat.Contains("'Trade Note' (rule 1, Keep)") && chat.Contains("will be Keep"), + "the unconditional rule is named: " + chat); + Check.Eq(VTankLootEvaluator.FirstMatch(bot.Get("_loadedLootProfile")!, bot.Item(Opal), null, out _)?.Name, "Trade Note", + "and it does keep a gem (what the report showed)"); + + var ok = new Bot(); + ok.S.CurrentLootPath = Temp("sell-gems.utl", SellGems); + FakeHost.Chat.Clear(); + object?[] load2 = { string.Empty, null, null }; + Check.True((bool)typeof(RynthAiPlugin).GetMethod("TryLoadLootProfile", Any)!.Invoke(ok.P, load2)!, "a normal profile loads"); + Check.False(ok.ChatText.Contains("no conditions"), "and says nothing about it"); } // ── World and plugin ────────────────────────────────────────────────────── diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs index e9b92c0..07d0db8 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs @@ -579,6 +579,13 @@ internal static class LootCorpseTests rare.Call("NoteBoostLootKill"); combat4.HandleCombatTrigger(); Check.Eq(combat4.activeTargetId, unchecked((int)Monster), "Loot Only Rare Corpses: no wait"); + + // Loot Mode rares (rares and needed mana stones only): the same. + var raresMode = BoostWorld(15f, withCorpse: false, out var combat5); + raresMode.S.LootMode = RynthCore.Plugin.RynthAi.Loot.LootModes.Rares; + raresMode.Call("NoteBoostLootKill"); + combat5.HandleCombatTrigger(); + Check.Eq(combat5.activeTargetId, unchecked((int)Monster), "Loot Mode rares: no wait"); } private static void BoostLootWaitEndsOnKillCorpse() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootJumpTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootJumpTests.cs new file mode 100644 index 0000000..e8e5f42 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootJumpTests.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Jump-loot: the jump is the keyboard one (TapJump, 0xF61B Jump, which ACE handles), never +// JumpNonAutonomous (0xF7C9, no handler on ACE). It goes BEFORE the move, on every pickup (a +// corpse's only match included), only with the setting on and stamina above 5. +// The loot clock (RynthAiPlugin.CorpseClock) is moved by hand here. +internal static class LootJumpTests +{ + private const uint Player = 0x50000F31; + private const uint CorpseA = 0x80263100; + private const uint GemA = 0x80263101; + private const uint GemA2 = 0x80263102; + private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800; + private const uint LongDescKey = 16; + private const string Me = "Test Looter"; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f); + + public static void Register(Runner r) + { + r.Add("jump loot: two-item corpse - the keyboard jump (0xF61B) goes out before the move; never the unhandled 0xF7C9", TwoItemJumpsBeforeMove); + r.Add("jump loot: a corpse's only match jumps too (one tap jump)", SingleItemJumps); + r.Add("jump loot: the setting off sends no jump", SettingOffNoJump); + r.Add("jump loot: stamina of 5 or less sends no jump", LowStaminaNoJump); + } + + private static long _now; + + private static void Clocked(Action body) + { + var old = RynthAiPlugin.CorpseClock; + _now = 50_000_000; + RynthAiPlugin.CorpseClock = () => _now; + try { body(); } + finally { RynthAiPlugin.CorpseClock = old; } + } + + private static void Gem(uint id) + { + FakeHost.Names[id] = "Black Opal"; + FakeHost.ItemTypes[id] = ItemTypeGem; + FakeHost.Containers[id] = CorpseA; + FakeHost.Appraised.Add(id); + } + + private static void World(bool secondGem) + { + FakeHost.Reset(); + FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal + FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData + FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId + FakeHost.TapJumpCalls = true; + FakeHost.Names[Player] = Me; + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + FakeHost.Names[CorpseA] = "Corpse of Olthoi Swarm Drone"; + FakeHost.ItemTypes[CorpseA] = ItemTypeContainer; + FakeHost.Strings[(CorpseA, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(CorpseA); + FakeHost.Positions[CorpseA] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); + Gem(GemA); + if (secondGem) Gem(GemA2); + } + + /// Opens the corpse and ticks until the first pickup's move has gone out. + private static void LootUntilFirstMove(bool jumpEnabled, bool secondGem, uint stamina) + { + World(secondGem); + var host = FakeHost.Create(Player); + var bot = new RynthAiPlugin(); + var s = new LegacyUiSettings + { + IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0, + LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false, + LootJumpEnabled = jumpEnabled, + }; + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(bot, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s); + void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(bot, v); + Set("_dashboard", dash); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + Set("_objectCache", cache); + Set("_playerId", Player); + Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = stamina, MaxMana = 100, CurrentMana = 100 }); + + string profile = Path.Combine(Program.TempRoot, "loot-jump-test.json"); + var p = new LootProfile { Name = "gems" }; + var rule = new LootRule { Name = "Gems", Action = LootAction.Keep }; + rule.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem }); + p.Rules.Add(rule); + p.Save(profile); + s.CurrentLootPath = profile; + + void Tick() + { + Set("_activity", BotActivity.Looting); + typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(bot, null); + } + foreach (uint id in secondGem ? new[] { CorpseA, GemA, GemA2 } : new[] { CorpseA, GemA }) cache.OnCreateObject(id); + cache.Tick(); + Tick(); + Check.True(FakeHost.Uses.Contains(CorpseA), "the corpse is opened"); + FakeHost.UseDone(0); + FakeHost.GroundContainer = CorpseA; + bot.OnViewObjectContents(CorpseA); + for (int i = 0; i < 200 && FakeHost.ExternalMoves.Count == 0; i++) { _now += 20; Tick(); } + Check.True(FakeHost.ExternalMoves.Count > 0, "a gem's move is sent"); + } + + private static string Order() => string.Join(",", FakeHost.Order); + + private static void TwoItemJumpsBeforeMove() => Clocked(() => + { + LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u); + Check.Eq(FakeHost.Order.FirstOrDefault() ?? "", "tapjump", "the keyboard jump goes first: " + Order()); + Check.True(FakeHost.Order.Count >= 2 && FakeHost.Order[1].StartsWith("move:", StringComparison.Ordinal), "then the move: " + Order()); + Check.Eq(FakeHost.Jumps, 0, "never JumpNonAutonomous (0xF7C9, no handler on ACE)"); + }); + + private static void SingleItemJumps() => Clocked(() => + { + LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u); + Check.Eq(FakeHost.Order.FirstOrDefault() ?? "", "tapjump", "single item: the jump goes first: " + Order()); + Check.True(FakeHost.Order.Count >= 2 && FakeHost.Order[1].StartsWith("move:", StringComparison.Ordinal), "single item: then the move: " + Order()); + Check.Eq(FakeHost.TapJumps, 1, "single item: exactly one tap jump"); + Check.Eq(FakeHost.Jumps, 0, "single item: never JumpNonAutonomous"); + }); + + private static void SettingOffNoJump() => Clocked(() => + { + LootUntilFirstMove(jumpEnabled: false, secondGem: true, stamina: 100u); + Check.Eq(FakeHost.TapJumps + FakeHost.Jumps, 0, "jump-loot off: no jump: " + Order()); + }); + + private static void LowStaminaNoJump() => Clocked(() => + { + LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 5u); + Check.Eq(FakeHost.TapJumps + FakeHost.Jumps, 0, "stamina 5: no jump: " + Order()); + }); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootRaresModeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootRaresModeTests.cs new file mode 100644 index 0000000..b9e3c75 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootRaresModeTests.cs @@ -0,0 +1,442 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json; +using RynthCore.Loot.VTank; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-31, owner: "We need a loot mode that only loots mana stones when it needs them and rares." +// Loot Mode "Rares and needed mana stones only" (LootModes.Rares): the loot profile is not used. One +// corpse, looted with LootSnob (Fixtures\lootsnob-excerpt.utl), in each mode: +// * a rare gem (its rare icon, IconUnderlay 0x06005B0C, from the create message; never identified), +// * a rare ring known by its RareId (identified), +// * a Blunt Crossbow (identified) that LootSnob's "(M) Xbow (OD +9)" keeps, +// * a gold Helm (identified) that LootSnob's "(Salv) Gold" salvages, +// * a Mana Stone, with tapping on and the keep count 5 (none in the pack: needed). +// The loot clock (CorpseClock) is moved by hand; the server lands each move in the pack at once. +internal static class LootRaresModeTests +{ + private const uint Player = 0x50000D51; + private const uint Corpse = 0x80267100; + private const uint Xbow = 0x80267101, RareGem = 0x80267102, RareRing = 0x80267103, Stone = 0x80267104, Helm = 0x80267105; + private const uint PackStone = 0x80267106; + private const uint ItemTypeContainer = 0x200, ItemTypeMissile = 0x100, ItemTypeGem = 0x800, ItemTypeJewelry = 0x8, + ItemTypeArmor = 0x2, ItemTypeManaStone = 0x80000; + private const uint LongDescKey = 16; + private const string Me = "Test Hunter"; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + private const long TickMs = 25; + private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f); + + public static void Register(Runner r) + { + r.Add("loot rares mode: the rares and a needed mana stone are looted; the OD crossbow LootSnob keeps and the gold salvage are not", RaresModeCorpse); + r.Add("loot rares mode: a mana stone at the keep count is left (not needed), and the corpse's end line says the mode", StoneNotNeeded); + r.Add("loot rares mode: profile mode is unchanged (crossbow kept, helm salvaged, stone kept, the rares left)", ProfileModeUnchanged); + r.Add("loot rares mode: a rare needs no ID (rare icon) or is known by its RareId; Mana Tap takes nothing", NoIdNoTap); + r.Add("loot rares mode: the loot details line names the reason (rare, mana stone (needed))", DetailsLineNamesReason); + r.Add("loot rares mode: the setting round trip (profile file, profile switch, engine face, meta LootMode)", SettingRoundTrip); + r.Add("loot rares mode: /ra loot mode replies with the mode, or why not and the usage; /ra loot why gives the mode's verdict", Commands); + r.Add("loot rares mode: the dashboard's LOOT line and the status say the mode", ShowsTheMode); + } + + // ── Clock and world ─────────────────────────────────────────────────────── + + private static long _now; + + private static void Clocked(Action body) + { + var old = RynthAiPlugin.CorpseClock; + _now = 70_000_000; + RynthAiPlugin.CorpseClock = () => _now; + try { body(); } + finally { RynthAiPlugin.CorpseClock = old; } + } + + private static void World(bool stoneInPack) + { + FakeHost.Reset(); + FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal + FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData + FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId + FakeHost.ContentsCalls = true; // GetContainerContents: the stone count walks the pack + FakeHost.Names[Player] = Me; + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Drone"; + FakeHost.ItemTypes[Corpse] = ItemTypeContainer; + FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(Corpse); + FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); + + // The crossbow, identified: LootSnob's (M) Xbow (OD +9) keeps it (as in LootLateIdTests). + Item(Xbow, "Blunt Crossbow", ItemTypeMissile, Corpse, appraised: true); + foreach (var (k, v) in new (uint, int)[] { (1, 0x100), (9, 0x00400000), (19, 12000), (5, 600), (131, 60), + (105, 6), (353, 9), (158, 2), (159, 47), (160, 385), (204, 22), (45, 4), (48, 47) }) + FakeHost.Ints[(Xbow, k)] = v; + FakeHost.Doubles[(Xbow, 63)] = 2.62; + FakeHost.Doubles[(Xbow, 29)] = 1.15; + FakeHost.SpellIds[Xbow] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") }; + // Mana on it (an ID shows it): Mana Tap would take it in rares mode if Mana Tap were on there. + FakeHost.Ints[(Xbow, 107)] = 4000; + + // A rare gem as the create message shows it: its rare icon plate, no ID. + Item(RareGem, "Pearl of Spirit Drinking", ItemTypeGem, Corpse, appraised: false); + FakeHost.DataIds[(RareGem, RareItems.IconUnderlayKey)] = 0x06005B0C; + // A rare known by its RareId (identified), without the icon plate. + Item(RareRing, "Ring of Fortitude", ItemTypeJewelry, Corpse, appraised: true); + FakeHost.Ints[(RareRing, RareItems.RareIdKey)] = 30183; + + // A gold helm, identified: LootSnob's (Salv) Gold salvages it. + Item(Helm, "Helm", ItemTypeArmor, Corpse, appraised: true); + foreach (var (k, v) in new (uint, int)[] { (131, 60), (105, 6), (19, 900), (5, 300) }) + FakeHost.Ints[(Helm, k)] = v; + + Item(Stone, "Mana Stone", ItemTypeManaStone, Corpse, appraised: true); + FakeHost.Ints[(Stone, 107)] = 0; + if (stoneInPack) + { + Item(PackStone, "Mana Stone", ItemTypeManaStone, Player, appraised: true); + FakeHost.Ints[(PackStone, 107)] = 0; + } + } + + private static void Item(uint id, string name, uint type, uint container, bool appraised) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = type; + FakeHost.Containers[id] = container; + if (appraised) FakeHost.Appraised.Add(id); + } + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() + { + IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0, + LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false, + LootAssessWindowMs = 200, LootCorpseTimeoutMs = 12_000, + EnableManaTapping = true, ManaTapMinMana = 2500, ManaStoneKeepCount = 5, + }; + public readonly WorldObjectCache Cache; + public readonly RynthCoreHost Host; + public readonly LegacyDashboardRenderer Dash; + private int _seenMoves; + + public Bot(RynthCoreHost host, int mode) + { + Host = host; + S.LootMode = mode; + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + Dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(Dash, S); + Set("_dashboard", Dash); + Cache = new WorldObjectCache(host); + Cache.SetPlayerId(Player); + Set("_objectCache", Cache); + Set("_playerId", Player); + Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }); + Set("_manaStoneManager", new ManaStoneManager(host, S, Cache)); + + VTankLootProfile p = VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl")); + string path = Path.Combine(Program.TempRoot, "loot-rares-mode.utl"); + File.WriteAllText(path, VTankLootWriter.Serialize(p)); + S.CurrentLootPath = path; + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!; + public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + + public void Tick() + { + _now += TickMs; + Set("_activity", BotActivity.Looting); + Call("TickCorpseOpening"); + while (_seenMoves < FakeHost.ExternalMoves.Count) + { + var m = FakeHost.ExternalMoves[_seenMoves++]; + FakeHost.Containers[m.Id] = m.Target; + } + } + + public void Create(params uint[] ids) + { + foreach (uint id in ids) Cache.OnCreateObject(id); + for (int i = 0; i < 5; i++) Cache.Tick(); + } + + public void Ra(string line) + { + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + int eat = 0; + object[] args = { parts[1].ToLowerInvariant(), parts, eat }; + typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, args); + } + + public (bool Taken, string Action, string Rule, string BuiltIn) Classify(uint id) + { + MethodInfo m = typeof(RynthAiPlugin).GetMethod("ClassifyLootItem", Any)!; + object?[] args = { Cache[unchecked((int)id)]!, S, true, null, null, null, null }; + bool taken = (bool)m.Invoke(P, args)!; + return (taken, (string)args[3]!, (string)args[5]!, (string)args[6]!); + } + + public bool CorpseDone => Get>("_completedCorpses").ContainsKey(unchecked((int)Corpse)); + } + + private static bool Said(string part) => FakeHost.Chat.Any(l => l.Contains(part, StringComparison.Ordinal)); + private static string ChatDump() => string.Join(" | ", FakeHost.Chat); + private static bool Moved(uint id) => FakeHost.ExternalMoves.Any(m => m.Id == id && m.Target == Player); + private static readonly uint[] OnCorpse = { Xbow, RareGem, RareRing, Helm, Stone }; + + /// Opens the corpse (the server's ViewContents) and loots it to its end. + private static Bot LootCorpse(int mode, bool stoneInPack = false, Action? setUp = null) + { + World(stoneInPack); + var host = FakeHost.Create(Player); + var bot = new Bot(host, mode); + setUp?.Invoke(bot); + var ids = new List { Corpse }; + ids.AddRange(OnCorpse); + if (stoneInPack) ids.Add(PackStone); + bot.Create(ids.ToArray()); + long end = _now + 30_000; + bool opened = false; + while (_now < end && !bot.CorpseDone) + { + bot.Tick(); + if (!opened && FakeHost.Uses.Contains(Corpse)) + { + opened = true; + FakeHost.UseDone(0); + FakeHost.GroundContainer = Corpse; + bot.P.OnViewObjectContents(Corpse); + bot.P.OnUpdateObjectInventory(Corpse); + } + } + Check.True(opened, "the corpse is opened (rares mode still opens corpses)"); + Check.True(bot.CorpseDone, "the corpse is finished"); + return bot; + } + + // ── Tests ───────────────────────────────────────────────────────────────── + + private static void RaresModeCorpse() => Clocked(() => + { + LootCorpse(LootModes.Rares); + Check.True(Moved(RareGem), $"the rare gem is looted ({ChatDump()})"); + Check.True(Moved(RareRing), "the rare ring (RareId) is looted"); + Check.True(Moved(Stone), "the mana stone is looted: none in the pack, keep count 5"); + Check.False(Moved(Xbow), "the OD crossbow LootSnob keeps is NOT looted (the profile isn't used)"); + Check.False(Moved(Helm), "the gold helm LootSnob salvages is NOT looted"); + Check.True(Said("Loot rule: Pearl of Spirit Drinking -> [Keep] Rares mode: rare"), "the pickup says why: a rare"); + Check.True(Said("Loot rule: Mana Stone -> [Keep] Rares mode: mana stone (needed)"), "and: a needed mana stone"); + Check.False(Said("(M) Xbow"), "no LootSnob rule is named"); + Check.False(Said("(Salv) Gold"), "nor its salvage rule"); + }); + + private static void StoneNotNeeded() => Clocked(() => + { + LootCorpse(LootModes.Rares, stoneInPack: true, bot => + { + bot.S.ManaStoneKeepCount = 1; + FakeHost.DataIds.Remove((RareGem, RareItems.IconUnderlayKey)); // no rares this time + FakeHost.Ints.Remove((RareRing, RareItems.RareIdKey)); + }); + Check.False(Moved(Stone), $"the stone is left: one in the pack, keep count 1 ({ChatDump()})"); + Check.True(Said("Mana stone match: 'Mana Stone' (have 1/1) — at cap, leaving."), "and said, as in profile mode"); + Check.False(OnCorpse.Any(Moved), "nothing else is looted"); + Check.True(Said("[RynthAi] Nothing to loot on Corpse of Olthoi Swarm Drone: 1 item(s) match, but you already have enough."), + "the end line: the stone matched, you have enough"); + + // With no stone either, the end line names the mode. + LootCorpse(LootModes.Rares, stoneInPack: true, bot => + { + bot.S.ManaStoneKeepCount = 1; + bot.S.EnableManaTapping = false; // no ManaStone rules, tapping off: no stone is a mana stone to keep + FakeHost.DataIds.Remove((RareGem, RareItems.IconUnderlayKey)); + FakeHost.Ints.Remove((RareRing, RareItems.RareIdKey)); + }); + Check.False(OnCorpse.Any(Moved), "nothing looted"); + Check.True(Said("[RynthAi] Nothing on Corpse of Olthoi Swarm Drone is a rare or a needed mana stone (Loot Mode: rares)."), + $"the end line says the mode ({ChatDump()})"); + }); + + private static void ProfileModeUnchanged() => Clocked(() => + { + LootCorpse(LootModes.Profile); + Check.True(Moved(Xbow), $"the crossbow is kept by LootSnob ({ChatDump()})"); + Check.True(Said("Loot rule: Blunt Crossbow -> [Keep] (M) Xbow (OD +9)"), "by its (M) Xbow (OD +9) rule"); + Check.True(Moved(Helm), "the gold helm is taken"); + Check.True(Said("Loot rule: Helm -> [Salvage] (Salv) Gold"), "for LootSnob's (Salv) Gold"); + Check.True(Moved(Stone), "the mana stone is kept by the built-in stone rule"); + Check.True(Said("Loot rule: Mana Stone -> [Keep] ManaStone (Consumable, 1/5)"), "under its old label"); + Check.False(Moved(RareGem), "the rare gem: no LootSnob rule takes it, so profile mode leaves it, as before"); + Check.False(Said("Rares mode"), "nothing says rares mode"); + }); + + private static void NoIdNoTap() => Clocked(() => + { + World(stoneInPack: false); + // An empty stone in the pack: Mana Tap (profile mode) would loot a 4,000-mana item to drain. + Item(PackStone, "Mana Stone", ItemTypeManaStone, Player, appraised: true); + FakeHost.Ints[(PackStone, 107)] = 0; + var host = FakeHost.Create(Player); + var bot = new Bot(host, LootModes.Rares); + bot.Create(Corpse, Xbow, RareGem, RareRing, Helm, Stone, PackStone); + + var gem = bot.Classify(RareGem); + Check.True(gem.Taken && gem.Action == "Keep" && gem.Rule == LootModes.RareRule, $"the rare gem, never identified: [{gem.Action}] {gem.Rule}"); + Check.True(gem.BuiltIn.StartsWith("a rare (rare icon)", StringComparison.Ordinal), "known by its rare icon: " + gem.BuiltIn); + var ring = bot.Classify(RareRing); + Check.True(ring.Taken && ring.BuiltIn.StartsWith("a rare (RareId 30183)", StringComparison.Ordinal), "the ring by its RareId: " + ring.BuiltIn); + Check.False((bool)bot.Call("ItemNeedsAppraisalForLoot", bot.Cache[unchecked((int)RareGem)]!)!, "rares mode asks for no ID"); + Check.False((bool)bot.Call("ItemNeedsAppraisalForLoot", bot.Cache[unchecked((int)Helm)]!)!, "for any item"); + + var xbow = bot.Classify(Xbow); + Check.False(xbow.Taken, $"the 4,000-mana crossbow is not a Mana Tap pickup in rares mode: [{xbow.Action}] {xbow.Rule}"); + Check.True(xbow.BuiltIn.StartsWith("not a rare or a mana stone", StringComparison.Ordinal), "and says why: " + xbow.BuiltIn); + var stone = bot.Classify(Stone); + Check.True(stone.Taken && stone.Rule == LootModes.StoneRule, $"the stone: 1 in the pack, keep count 5: [{stone.Action}] {stone.Rule}"); + Check.True(stone.BuiltIn.StartsWith("a needed mana stone, 1 of 5 kept", StringComparison.Ordinal), stone.BuiltIn); + + // Profile mode, same world: no LootSnob rule takes the 4,000-mana ring, so Mana Tap does. + FakeHost.Ints[(RareRing, 107)] = 4000; + bot.S.LootMode = LootModes.Profile; + var tap = bot.Classify(RareRing); + Check.True(tap.Taken && tap.Action == "ManaTap", $"profile mode: Mana Tap as before: [{tap.Action}] {tap.Rule}"); + bot.S.LootMode = LootModes.Rares; + Check.Eq(bot.Classify(RareRing).Action, "Keep", "rares mode: the same ring is kept as a rare, not drained"); + }); + + private static void DetailsLineNamesReason() => Clocked(() => + { + LootCorpse(LootModes.Rares, setUp: bot => bot.S.ItemInfoSettings.LootChat = true); + Check.True(Said("[RynthAi] Looted [Keep] Pearl of Spirit Drinking (Rares mode: rare)"), $"the rare's line ({ChatDump()})"); + Check.True(Said("[RynthAi] Looted [Keep] Mana Stone (Rares mode: mana stone (needed))"), "the stone's line"); + Check.False(Said("rule \"Rares mode"), "shown as the reason, not as a rule name"); + }); + + private static void SettingRoundTrip() + { + // The settings profile file. + var ctx = RynthAiJsonContext.Default.LegacyUiSettings; + var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(new LegacyUiSettings { LootMode = LootModes.Rares }, ctx), ctx); + Check.Eq(back?.LootMode, LootModes.Rares, "saved and loaded with the settings profile"); + var old = JsonSerializer.Deserialize("{\"EnableLooting\":true}", ctx); + Check.Eq(old?.LootMode, LootModes.Profile, "a profile saved before it loads as Profile"); + + // A profile switch copies it. + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { LootMode = LootModes.Rares }, dst }); + Check.Eq(dst.LootMode, LootModes.Rares, "a profile switch copies it"); + Check.True(!LootModes.IsRares(7) && LootModes.Clamp(7) == LootModes.Profile, "an unknown value reads as Profile"); + + // The engine's Settings face: sent; a save without it leaves it alone. + var s = new LegacyUiSettings { LootMode = LootModes.Rares }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent?.LootMode == LootModes.Rares, "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.Eq(s.LootMode, LootModes.Rares, "a save without it leaves it alone"); + dash.ApplySettingsJson("{\"LootMode\":0}"); + Check.Eq(s.LootMode, LootModes.Profile, "a save with 0 sets Profile"); + + // The meta settings map (setsetting / getsetting LootMode). + var live = new LegacyUiSettings(); + var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic(); + Check.True(map.TryGetValue("LootMode", out var entry), "LootMode is in the meta settings map"); + Check.Eq(entry.Get(), "0", "reads 0 (Profile)"); + entry.Set("1"); + Check.Eq(live.LootMode, LootModes.Rares, "1 sets rares"); + Check.Eq(entry.Get(), "1", "and reads 1"); + entry.Set("profile"); + Check.Eq(live.LootMode, LootModes.Profile, "the word 'profile' works too"); + entry.Set("rares"); + Check.Eq(live.LootMode, LootModes.Rares, "and 'rares'"); + entry.Set("banana"); + Check.Eq(live.LootMode, LootModes.Rares, "anything else changes nothing"); + } + + private static void Commands() => Clocked(() => + { + World(stoneInPack: false); + var host = FakeHost.Create(Player); + var bot = new Bot(host, LootModes.Profile); + bot.Create(Corpse, Xbow, RareGem, RareRing, Helm, Stone); + + FakeHost.Chat.Clear(); + bot.Ra("/ra loot mode rares"); + Check.Eq(bot.S.LootMode, LootModes.Rares, "/ra loot mode rares sets it"); + Check.True(Said("[RynthAi] Loot Mode: Rares and needed mana stones only (mana stones up to the keep count, 5; the loot profile loot-rares-mode.utl is not used)."), + "and replies with the mode now: " + ChatDump()); + + FakeHost.Chat.Clear(); + bot.Ra("/ra loot mode"); + Check.True(Said("[RynthAi] Loot Mode: Rares and needed mana stones only") && Said("Usage: /ra loot mode profile|rares"), + "no word: says the mode now, and the usage: " + ChatDump()); + + FakeHost.Chat.Clear(); + bot.Ra("/ra loot mode banana"); + Check.Eq(bot.S.LootMode, LootModes.Rares, "a wrong word changes nothing"); + Check.True(Said("[RynthAi] loot mode: 'banana'? Loot Mode is still Rares and needed mana stones only") && Said("Usage: /ra loot mode profile|rares"), + "it says why, the mode now and the usage: " + ChatDump()); + + // /ra loot why: the mode's verdict. + FakeHost.SelectedItem = Xbow; + FakeHost.Chat.Clear(); + bot.Ra("/ra loot why"); + Check.True(Said("[RynthAi] Loot why: 'Blunt Crossbow' (identified) -> left (not a rare or a mana stone (Loot Mode: rares and needed mana stones only)") + && Said("Loot Mode: Rares and needed mana stones only"), "the crossbow: left, by the mode: " + ChatDump()); + FakeHost.SelectedItem = RareGem; + FakeHost.Chat.Clear(); + bot.Ra("/ra loot why"); + Check.True(Said("[RynthAi] Loot why: 'Pearl of Spirit Drinking' (not identified yet) -> [Keep] Rares mode: rare (a rare (rare icon)"), + "the rare gem: kept as a rare: " + ChatDump()); + + FakeHost.Chat.Clear(); + bot.Ra("/ra loot mode profile"); + Check.Eq(bot.S.LootMode, LootModes.Profile, "/ra loot mode profile sets it back"); + Check.True(Said("[RynthAi] Loot Mode: Profile (the loot profile)."), "and replies: " + ChatDump()); + FakeHost.SelectedItem = Xbow; + FakeHost.Chat.Clear(); + bot.Ra("/ra loot why"); + Check.True(Said("-> [Keep] (M) Xbow (OD +9)"), "profile mode's loot why, as before: " + ChatDump()); + }); + + private static void ShowsTheMode() + { + FakeHost.Reset(); + var host = FakeHost.Create(Player); + var bot = new Bot(host, LootModes.Profile); + Check.Eq(bot.Dash.LootLineName(), "loot-rares-mode", "profile mode: the LOOT line is the profile's name"); + bot.S.LootMode = LootModes.Rares; + Check.Eq(bot.Dash.LootLineName(), "Rares + needed mana stones (loot-rares-mode not used)", "rares mode: the LOOT line says so"); + bot.S.CurrentLootPath = string.Empty; + Check.Eq(bot.Dash.LootLineName(), "Rares + needed mana stones", "with no profile picked"); + + bot.Set("_loginComplete", true); + string? json = (string?)bot.Call("BuildBotStatusJson"); + Check.True(json != null && json.Contains("\"lootMode\":\"rares\""), "the status says lootMode rares: " + json); + bot.S.LootMode = LootModes.Profile; + json = (string?)bot.Call("BuildBotStatusJson"); + Check.True(json != null && json.Contains("\"lootMode\":\"profile\""), "and profile: " + json); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs index c41ec19..a7f890f 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs @@ -47,6 +47,13 @@ internal static class LootRetryTimingTests r.Add("loot retry (R-20261029-122319-321f): a refusal on arrival is 'too busy' (free resend), one after the pickup is the pack's answer", RefusalTiming); r.Add("loot retry (R-20261029-122319-321f): the answer wait grows with the server's measured answers, within 4-8 s", AnswerWaitAdapts); r.Add("loot retry (R-20261029-122319-321f): PackRefusals keeps confirmed marks and drops the unconfirmed ones with the item", PackRefusalMarks); + r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): a treasure map the server refuses (quest timer, no object named) is left after one try; the next item is picked up and the corpse completes", QuestTimerMapFirst); + r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): with the map last, the items before it land, the map is left, the corpse completes", QuestTimerMapLast); + r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): maps on corpse after corpse, no side pack: each map one try, every other item lands, no pack marked", QuestTimerMapsCorpseAfterCorpse); + r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): a quest refusal naming the item is left at once too, no pack blamed", NeedsQuestNamedItem); + r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): an item refused 'for room' in every pack it tries takes its pack marks with it; the next item lands", RefusedInEveryPackWithdrawn); + r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): a refusal with an error code counts as a try but not against the pack", CodedRefusalNotThePack); + r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): PackRefusals withdraws an item's own marks, keeps the ones another item backs", PackRefusalWithdraw); } // ── Clock and world ─────────────────────────────────────────────────────── @@ -160,7 +167,16 @@ internal static class LootRetryTimingTests /// one pending inventory request: a move sent while one is unanswered never leaves the client. /// : extra delay before the server takes up an item's first move (a lag spike); /// : items whose moves the server never answers. The engine empties a - /// pending request that has had no answer for 10 s (ClientActionGates.PendingTimeoutMs). + /// pending request that has had no answer for 10 s (ClientActionGates.PendingTimeoutMs), and + /// /rc unlockactions empties it at once. + /// : items with a pickup timer (2026-11-01, #rynth-issues "Stopped looting": + /// Conquest treasure maps). After the pickup motion ACE's VerifyQuest refuses them with + /// "You have solved this quest too recently!" + InventoryServerSaveFailed(object 0, + /// YouHaveSolvedThisQuestTooRecently) (QuestManager.HandleSolveError): naming no object, the + /// answer leaves the client's pending request in place. : the same + /// refusal naming the item (ItemRequiresQuestToBePickedUp, HandleNoQuestError). + /// : refused after the motion like a full pack (no error code), + /// whatever pack the move names: a pickup timer that says no more than a full pack does. /// private sealed class SlowAce { @@ -168,6 +184,8 @@ internal static class LootRetryTimingTests public readonly Dictionary Room = new(); // the server's free slots per pack (absent: plenty) public readonly Dictionary Lag = new(); public readonly HashSet NeverAnswer = new(); + public readonly HashSet QuestTimer = new(), NeedsQuest = new(), RefusedForItem = new(); + public int QuestRefusals, Unlocks; public long ClientPendingTimeoutMs = 10_000; public int TooBusy, LocalRefused, Queued, RoomRefusals; public readonly List<(uint Id, uint Pack, long At)> Landed = new(); @@ -178,6 +196,7 @@ internal static class LootRetryTimingTests private int _seenMoves; private uint _clientPending; private long _clientPendingAt; + private int _seenCommands; private readonly List<(long At, int Seq, Action Act)> _events = new(); private int _seq; @@ -185,6 +204,8 @@ internal static class LootRetryTimingTests public void Step(long now) { + while (_seenCommands < FakeHost.ChatCommands.Count) + if (FakeHost.ChatCommands[_seenCommands++] == "/rc unlockactions") { _clientPending = 0; Unlocks++; } while (_seenMoves < FakeHost.ExternalMoves.Count) { var m = FakeHost.ExternalMoves[_seenMoves++]; @@ -232,7 +253,22 @@ internal static class LootRetryTimingTests private void Finish(uint id, uint pack, long ts) { _st = St.Return; - if (Room.TryGetValue(pack, out int free) && free <= 0) + if (QuestTimer.Contains(id) || NeedsQuest.Contains(id)) + { + QuestRefusals++; + bool named = NeedsQuest.Contains(id); + At(ts + Rtt / 2, () => + { + if (named) + { + FakeHost.WeenieError(0x0445, 0x00A0, id); // ItemRequiresQuestToBePickedUp + Answered(id); + } + else + FakeHost.WeenieError(0x043E, 0x00A0, 0); // YouHaveSolvedThisQuestTooRecently, no object: the slot stays + }); + } + else if (RefusedForItem.Contains(id) || (Room.TryGetValue(pack, out int free) && free <= 0)) { RoomRefusals++; At(ts + Rtt / 2, () => @@ -243,7 +279,7 @@ internal static class LootRetryTimingTests } else { - if (Room.ContainsKey(pack)) Room[pack] = free - 1; + if (Room.TryGetValue(pack, out int left)) Room[pack] = left - 1; At(ts + Rtt / 2, () => { FakeHost.Containers[id] = pack; @@ -470,4 +506,196 @@ internal static class LootRetryTimingTests r.Accepted(1); Check.False(r.IsRefused(1, 10), "an item landing there ends a confirmed mark"); } + + // ── 7. Items the server won't hand over yet (#rynth-issues "Stopped looting") ──────────── + // "I've experienced this when it's reached its loot attempt limit on some obscure item with + // pickup timers. It looks like from then on out it just selects another item in the + // container, but doesn't pick it up. Example: CQ Treasure Maps." ACE (Player.VerifyQuest, + // QuestManager.HandleSolveError) refuses such an item after the pickup motion with + // InventoryServerSaveFailed naming object 0: RynthAi saw no answer, and the client's one + // pending request stayed full, so the retries and the next item's move never left the client. + // An answer naming the item was taken for a full pack, and a pack after another was left out. + + private const uint QuestMap = 0x80263151; // the lowest id on its corpse: tried first + + /// The map among normal gems (the profile keeps every gem; a treasure map is one). + private static void NameMap(uint map) => FakeHost.Names[map] = "Treasure Map"; + + private static void QuestTimerMapFirst() => Clocked(() => + { + const uint G2 = 0x80263152; + World(sidePack: true, QuestMap, G2); + NameMap(QuestMap); + var sim = new SlowAce(); + sim.QuestTimer.Add(QuestMap); + var bot = Open(sim, sidePack: true, QuestMap, G2); + + Run(bot, () => bot.Completed, 60_000); + + Check.True(FakeHost.ExternalMoves.Count > 0 && FakeHost.ExternalMoves[0].Id == QuestMap, "the map is tried first"); + Check.Eq(bot.MovesOf(QuestMap), 1, "the map is sent once: a retry would be refused the same way for its timer"); + Check.Eq(sim.QuestRefusals, 1, "the server refused it once"); + Check.True(Logged("the server won't hand over 0x80263151") && Logged("pickup timer"), "logged as refused for the item (its pickup timer)"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Can't loot Treasure Map")), "the player is told"); + Check.True(FakeHost.ChatCommands.Contains("/rc unlockactions"), "the client's pending request (the answer named no object) is emptied"); + Check.Eq(bot.MovesOf(G2), 1, "the next item is sent once"); + Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == Player), "and lands in the main pack"); + Check.Eq(sim.LocalRefused, 0, "no move dropped by the client's one-request slot"); + Check.False(Logged("took none of"), "no pack judged full"); + Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now) || bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "no pack marked"); + Check.False(Logged("no pack has a free slot"), "looting does not stop for want of a pack"); + Check.True(bot.Completed, "the corpse completes"); + }); + + private static void QuestTimerMapLast() => Clocked(() => + { + const uint G1 = 0x80263141, G2 = 0x80263142, Map = 0x80263159; + World(sidePack: true, G1, G2, Map); + NameMap(Map); + var sim = new SlowAce(); + sim.QuestTimer.Add(Map); + var bot = Open(sim, sidePack: true, G1, G2, Map); + + Run(bot, () => bot.Completed, 60_000); + + Check.True(FakeHost.ExternalMoves.Count > 0 && FakeHost.ExternalMoves[^1].Id == Map, "the map is tried last"); + Check.True(sim.Landed.Any(l => l.Id == G1) && sim.Landed.Any(l => l.Id == G2), "the items before it land"); + Check.Eq(bot.MovesOf(Map), 1, "the map is sent once"); + Check.True(Logged("the server won't hand over 0x80263159"), "and left for its pickup timer"); + Check.False(Logged("pickup failed"), "no item runs out of tries"); + Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack is not marked"); + Check.True(bot.Completed, "the corpse completes"); + }); + + private static void QuestTimerMapsCorpseAfterCorpse() => Clocked(() => + { + // One corpse after another, each with a map (first) and a gem; no side pack, so a wrong + // mark on the main pack would stop all looting. + World(sidePack: false); + var sim = new SlowAce(); + static (uint Corpse, uint Map, uint Gem) Ids(int n) { uint c = 0x80263200u + (uint)n * 0x10; return (c, c + 1, c + 2); } + for (int n = 0; n < 3; n++) + { + var (corpse, map, gem) = Ids(n); + FakeHost.Names[corpse] = "Corpse of Brier Wasp"; + FakeHost.ItemTypes[corpse] = ItemTypeContainer; + FakeHost.Strings[(corpse, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(corpse); + FakeHost.Positions[corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); + foreach (uint item in new[] { map, gem }) + { + FakeHost.Names[item] = item == map ? "Treasure Map" : $"Gem {item & 0xFF}"; + FakeHost.ItemTypes[item] = ItemTypeGem; + FakeHost.Containers[item] = corpse; + FakeHost.Appraised.Add(item); + } + sim.QuestTimer.Add(map); + } + var bot = new Bot(FakeHost.Create(Player)) { Sim = sim }; + for (int n = 0; n < 3; n++) + { + var (corpse, map, gem) = Ids(n); + foreach (uint id in new[] { corpse, map, gem }) bot.Cache.OnCreateObject(id); + for (int i = 0; i < 50; i++) bot.Cache.Tick(); + bot.TickUntil(() => FakeHost.Uses.Contains(corpse), 10_000); + Check.True(FakeHost.Uses.Contains(corpse), $"corpse {n + 1} is opened"); + FakeHost.UseDone(0); + FakeHost.GroundContainer = corpse; + bot.P.OnViewObjectContents(corpse); + bool Done() => bot.Get>("_completedCorpses").ContainsKey(unchecked((int)corpse)); + bot.TickUntil(Done, 60_000); + + Check.True(Done(), $"corpse {n + 1} completes"); + Check.Eq(bot.MovesOf(map), 1, $"corpse {n + 1}: the map is sent once"); + Check.True(sim.Landed.Any(l => l.Id == gem && l.Pack == Player), $"corpse {n + 1}: the gem lands in the main pack"); + Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), $"corpse {n + 1}: the main pack is not marked"); + FakeHost.GroundContainer = 0; + bot.P.OnStopViewingObjectContents(corpse); // the server closes it + } + Check.Eq(sim.LocalRefused, 0, "no move dropped by the client's one-request slot"); + Check.False(Logged("no pack has a free slot"), "looting never stops for want of a pack"); + Check.False(Logged("took none of"), "no pack judged full"); + }); + + private static void NeedsQuestNamedItem() => Clocked(() => + { + const uint G2 = 0x80263152; + World(sidePack: true, QuestMap, G2); + NameMap(QuestMap); + var sim = new SlowAce(); + sim.NeedsQuest.Add(QuestMap); + var bot = Open(sim, sidePack: true, QuestMap, G2); + + Run(bot, () => bot.Completed, 60_000); + + Check.Eq(bot.MovesOf(QuestMap), 1, "sent once"); + Check.True(Logged("needs a quest flag"), "left: it needs a quest flag"); + Check.False(FakeHost.ChatCommands.Contains("/rc unlockactions"), "the answer named the item: the client empties its own request"); + Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack is not marked (it was taken for the pack's answer before)"); + Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == Player), "the next item lands in the main pack"); + Check.True(bot.Completed, "the corpse completes"); + }); + + private static void RefusedInEveryPackWithdrawn() => Clocked(() => + { + const uint G2 = 0x80263152; + World(sidePack: true, QuestMap, G2); + NameMap(QuestMap); + var sim = new SlowAce(); + sim.RefusedForItem.Add(QuestMap); // refused like a full pack, whichever pack + var bot = Open(sim, sidePack: true, QuestMap, G2); + + Run(bot, () => bot.Completed, 90_000); + + var mapMoves = FakeHost.ExternalMoves.Where(m => m.Id == QuestMap).ToList(); + Check.Eq(mapMoves.Count(m => m.Target == Player), 3, "three tries into the main pack"); + Check.Eq(mapMoves.Count(m => m.Target == SidePack), 3, "three into the side pack"); + Check.True(Logged("pickup failed for 0x80263151"), "then the map is given up"); + Check.True(Logged("it is refusing the item, not the packs") && Logged("the main pack and pack 0x80263001 are no longer treated as full"), + "both marks go with the map"); + Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now) || bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "no pack marked"); + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == G2) && FakeHost.ExternalMoves.Where(m => m.Id == G2).All(m => m.Target == Player), "the next item goes into the main pack"); + Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == Player), "and lands"); + Check.False(Logged("no pack has a free slot"), "looting does not stop for want of a pack"); + Check.True(bot.Completed, "the corpse completes"); + }); + + private static void CodedRefusalNotThePack() => Clocked(() => + { + const uint G1 = 0x80263161; + World(sidePack: false, G1); + var bot = Open(new SlowAce(), sidePack: false, G1); + bot.Sim = null; // the answers are given by hand here + bot.TickUntil(() => bot.MovesOf(G1) > 0, 2000); + Check.Eq(bot.MovesOf(G1), 1, "the move is sent"); + FakeHost.CastBusy = 1; + bot.TickUntil(() => false, 1800); + FakeHost.WeenieError(0x0036, 0x00A0, G1); // refused after the pickup ran, with a code (ActionCancelled) + bot.Tick(); + FakeHost.CastBusy = 0; + bot.TickUntil(() => bot.MovesOf(G1) > 1, 3000); + Check.Eq(bot.MovesOf(G1), 2, "sent again"); + Check.Eq(bot.Get("_currentLootItemMoveAttempts"), 2, "counted as a try"); + Check.Eq(bot.Get("_currentLootItemDestRefusals"), 0, "but not against the main pack"); + Check.True(Logged("for the item (error 0x36), not the pack"), "logged as the item's refusal"); + }); + + private static void PackRefusalWithdraw() + { + var r = new RynthCore.Plugin.RynthAi.Loot.PackRefusals(); + r.Refuse(1, 0, confirmed: true, itemId: 100); + r.Refuse(2, 0, confirmed: true, itemId: 100); + r.Refuse(3, 0, confirmed: true, itemId: 200); + r.Refuse(3, 0, confirmed: true, itemId: 100); // pack 3: refused for two items + var back = r.Withdraw(100, 10); + Check.True(back.Contains(1) && back.Contains(2) && !back.Contains(3), $"item 100's own marks are withdrawn ({string.Join(",", back)})"); + Check.False(r.IsRefused(1, 10) || r.IsRefused(2, 10), "packs 1 and 2 are tried again"); + Check.True(r.IsConfirmed(3, 10), "pack 3, refused for another item as well, stays marked"); + r.Refuse(1, 20, confirmed: true, itemId: 300); // another item refused in pack 1 after all: it is the pack + Check.Eq(r.Withdraw(300, 30).Count, 0, "a pack two items were refused in is not withdrawn"); + Check.True(r.IsConfirmed(1, 30), "pack 1 stays marked"); + r.Refuse(4, 0); // no item said: never withdrawn + Check.Eq(r.Withdraw(0, 10).Count, 0, "nothing for item 0"); + Check.True(r.IsConfirmed(4, 10), "a mark with no item stays"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs index 24c03cd..59d4768 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs @@ -12,8 +12,8 @@ using N = RynthCore.Loot.VTank.VTankNodeTypes; namespace RynthCore.RynthAiHostTests.Tests; // 2026-10-31: "a +9 bludg xbow that rynth sees as gold salvage", with LootSnob, which VTank keeps. -// Fixtures\lootsnob-excerpt.utl is LootSnobV4's melee head, missile and void wand sections and six -// of its Salvage rules (switched on, as players have them), in the file's own order. +// Fixtures\lootsnob-excerpt.utl is LootSnobV4's melee head, missile and wand (No Wield, Void, War) +// sections and six of its Salvage rules (switched on, as players have them), in the file's own order. // Two causes: // 1. "Calc'd Buffed Missile Damage" read max damage x the wand elemental modifier (152). A launcher // has no max damage, so it was 0 and every one of LootSnob's 33 missile damage keeps failed; the @@ -35,7 +35,9 @@ internal static class LootRuleMatchTests r.Add("loot rule match: tinked damage and tinked target melee (VTank's worked examples)", TinkedNodes); r.Add("loot rule match: which conditions need the ID", ConditionsNeedingId); r.Add("loot rule match: Decide passes over a rule a known condition fails, in any order", DecideOrder); + r.Add("loot rule match (R-20261101-133624-7eeb): a name rule 'Trade Note' first keeps none of a corpse's plain items, ID or not", TradeNoteRuleFirst); r.Add("loot rule match: /ra loot why lists the rules above that came close, with the value read", LootWhyExplains); + r.Add("loot rule match: /ra loot why's words, in chat and in the 'Why this loot rule?' window", LootWhyReportWords); } private static VTankLootProfile Excerpt() @@ -246,6 +248,47 @@ internal static class LootRuleMatchTests Check.Eq(i3, -1, "index -1"); } + // R-20261101-133624-7eeb (Conquest, 2026.10.31.3): every item on a corpse was kept by a rule named + // 'Trade Note' (Imperial Topaz, Frost Child Essence and Pyreal with no ID; Gloves and Flagon with + // it). LootSnob's 'Trade Note' is one StringValueMatch on the Name ("Trade Note", key 1): it keeps + // none of them, with or without the ID, here and through the whole fixture. A rule with no + // conditions keeps everything (VTank's unconditional rule), so a 'Trade Note' that lost its + // condition in the player's own profile would do exactly what the report shows. + private static void TradeNoteRuleFirst() + { + FakeHost.Reset(); + static VTankLootCondition C(int node, params string[] data) => new(node, "0", data); + var tradeNote = new VTankLootRule { Name = "Trade Note", Action = VTankLootAction.Keep }; + tradeNote.Conditions.Add(C(N.StringValueMatch, "Trade Note", "1")); + var p = new VTankLootProfile(); + p.Rules.Add(tradeNote); + p.Rules.AddRange(Excerpt().Rules); + + var items = new (Item Item, bool Id)[] + { + (new Item("Imperial Topaz", AcObjectClass.Gem).Int(1, 0x800).Int(19, 6094), false), + (new Item("Frost Child Essence (180)", AcObjectClass.Misc).Int(1, 0x80).Int(19, 9000), false), + (new Item("Pyreal", AcObjectClass.Money).Int(1, 0x40).Int(19, 693).Int(12, 693), false), + (new Item("Gloves", AcObjectClass.Clothing).Int(1, 0x4).Int(19, 24429).Int(105, 5), true), + (new Item("Flagon", AcObjectClass.MissileWeapon).Int(1, 0x100).Int(19, 12741).Int(105, 4), true), + }; + foreach (var (item, id) in items) + { + VTankLootVerdict v = VTankLootEvaluator.Decide(p, item, Ctx(), hasIdData: id, out int idx); + Check.True(!(v == VTankLootVerdict.Match && idx == 0), $"{item.Wo.Name}: not kept by 'Trade Note' ({v}{(idx >= 0 ? " at " + p.Rules[idx].Name.Trim() : "")})"); + Check.True(VTankLootEvaluator.FirstMatch(p, item, Ctx(), out int fi)?.Name != "Trade Note", $"{item.Wo.Name}: FirstMatch not 'Trade Note' ({fi})"); + } + var note = new Item("Trade Note (250,000)", AcObjectClass.TradeNote).Int(1, 0x80); + Check.Eq(VTankLootEvaluator.Decide(p, note, Ctx(), hasIdData: false, out int ni), VTankLootVerdict.Match, "a trade note is kept with no ID"); + Check.Eq(ni, 0, "by 'Trade Note'"); + + // The same rule with its condition gone keeps everything: what the report looks like. + var empty = new VTankLootRule { Name = "Trade Note", Action = VTankLootAction.Keep }; + var broken = new VTankLootProfile(); + broken.Rules.Add(empty); + Check.Eq(VTankLootEvaluator.FirstMatch(broken, items[0].Item, Ctx(), out _)?.Name, "Trade Note", "a 'Trade Note' with no condition keeps a topaz (unconditional rule)"); + } + private static void LootWhyExplains() { FakeHost.Reset(); @@ -268,4 +311,50 @@ internal static class LootRuleMatchTests Check.Eq(wait.Verdict, VTankLootVerdict.NeedsId, "no ID: waits"); Check.Eq(wait.RuleName, "(M) Bow (OD +10)", "names the rule that needs it"); } + + // 2026-10-31: the same answer as a report the chat lines and the window are both made from. + private static void LootWhyReportWords() + { + FakeHost.Reset(); + VTankLootProfile p = Excerpt(); + var plain = PlusNineXbow(); + FakeHost.SpellIds.Remove(unchecked((uint)plain.Wo.Id)); + LootWhy.Result why = LootWhy.Explain(p, plain, Ctx(), hasIdData: true); + LootWhy.Report r = LootWhy.Describe("Blunt Crossbow", true, "[Salvage] (Salv) Gold", "lootsnob.utl", p.Rules.Count, why, askedForId: false); + Check.True(r.Ok && r.RuleDetail, "a VTank profile: rule-by-rule"); + Check.Eq(r.Headline, "'Blunt Crossbow' (identified) -> [Salvage] (Salv) Gold", "the headline: the item, its ID, the looter"); + Check.True(r.Decision.StartsWith($"lootsnob.utl: rule {why.Index + 1} of {p.Rules.Count} '(Salv) Gold' [", StringComparison.Ordinal), $"the decision names the rule ({r.Decision})"); + Check.Eq(r.NearMisses.Count, why.NearMisses.Count, "every near miss is in the report (the window lists them all)"); + + var lines = LootWhy.ChatLines(r, 2); + Check.Eq(lines[0], "[RynthAi] Loot why: " + r.Headline, "chat line 1: the headline"); + Check.Eq(lines[1], "[RynthAi] " + r.Decision, "chat line 2: the decision"); + Check.True(lines[2].Contains($"{r.NearMisses.Count} rule(s) above it came close"), "then how many came close"); + Check.Eq(lines[3], "[RynthAi] " + LootWhy.NearMissLine(r.NearMisses[0]), "then each, as #N 'name': failed"); + Check.True(r.NearMisses.Count <= 2 || lines[^1].Contains($"{r.NearMisses.Count - 2} more in the log"), "past the chat's limit: the rest are counted (the log has them)"); + Check.Eq(lines.Count, 3 + Math.Min(2, r.NearMisses.Count) + (r.NearMisses.Count > 2 ? 1 : 0), "no other lines"); + Check.True(LootWhy.NearMissLine(new LootWhy.NearMiss(4, "Rule", "x: read 1")) == "#5 'Rule': x: read 1", "a near miss counts from 1"); + + LootWhy.Result wait = LootWhy.Explain(p, PlusNineXbow(withId: false), Ctx(), hasIdData: false); + LootWhy.Report w = LootWhy.Describe("Blunt Crossbow", false, "left", "lootsnob.utl", p.Rules.Count, wait, askedForId: true); + Check.True(w.Decision.EndsWith("needs the item's ID to decide", StringComparison.Ordinal) && w.Headline.Contains("(not identified yet)"), "no ID: which rule waits for it"); + Check.True(LootWhy.ChatLines(w, 10).Contains("[RynthAi] Asked for its ID; /ra loot why again once it's in."), "and that it asked for it"); + + LootWhy.Report native = LootWhy.Describe("Blunt Crossbow", true, "[Keep] Xbows", "", 0, null, false); + Check.False(native.RuleDetail, "RynthAi's own (.json) profile: no rule-by-rule detail"); + var one = LootWhy.ChatLines(native, 10); + Check.Eq(one.Count, 1, "one chat line"); + Check.True(one[0].EndsWith("(Rule-by-rule detail is for VTank .utl profiles.)", StringComparison.Ordinal), "that says so"); + + LootWhy.Report rares = LootWhy.ModeOnly("Blunt Crossbow", true, "left", "Loot Mode: Rares and needed mana stones only (the loot profile isn't used)"); + Check.True(rares.Ok && !rares.RuleDetail, "rares mode: the mode decides, no rule detail"); + Check.Eq(LootWhy.ChatLines(rares, 10).Single(), + "[RynthAi] Loot why: 'Blunt Crossbow' (identified) -> left. Loot Mode: Rares and needed mana stones only (the loot profile isn't used).", + "chat: one line naming the Loot Mode, not the .utl note"); + + LootWhy.Report fail = LootWhy.Report.Fail("select an item first"); + Check.False(fail.Ok, "a failed report"); + Check.Eq(fail.Headline, "select an item first", "its headline is the reason"); + Check.Eq(LootWhy.ChatLines(fail, 10).Single(), "[RynthAi] loot why: select an item first", "chat: one line, the reason"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootWandTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootWandTests.cs new file mode 100644 index 0000000..e99ba3d --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootWandTests.cs @@ -0,0 +1,347 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Loot; +using RynthCore.Loot.VTank; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-11-01: "damage on wands isn't being read by the loot properly; someone thinks it's missing +// them". Casters through LootSnobV4's own wand rules (Fixtures\lootsnob-excerpt.utl: its No Wield, +// Void and War sections, as LootSnob ships them), with tier 8 values as ACE's caster mutations make +// them: elemental damage vs monsters (152) 1.10-1.18 at wield 355/375/385, melee defense (29) 1.0x, +// mana conversion (144), magic defense (150), and the cantrips that add to them (Spirit Thirst, +// Defender, Hermetic Link). The values are read after the ID, through the host, on a corpse too. +// +// What was wrong: +// - Until 2026.10.31.2 a "Buffed Double Key" read the plain value without the item's cantrips. A +// loot caster tops out at 1.18, so every "(W) War/Void (OD +1..+7)" rule (1.19-1.25) failed; on +// Conquest's CQ_Lootsnob_lite, whose War and Void rules are nearly all OD rules, no war or void +// wand was kept (the 10-19 report, on 2026.10.17.1). Fixed there; checked here. +// - The installed LootSnobV4 on the PC has the War "Max 385/375/355", "18pvm + NNmd", "amazing 355", +// "25MD"-"21MD" and Void "Max" rules switched off in the Loot Editor (the stock file has them on), +// so typical tier 8 war wands were left. A profile matter, but nothing said so: /ra loot why +// skipped switched-off rules and the log said "leave". Both now name the switched-off rule that +// would take the item. +internal static class LootWandTests +{ + private const uint Player = 0x50000E41; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + // Property ids (ACE PropertyInt / PropertyFloat). + private const int ItemType = 1, Burden = 5, ValidLoc = 9, Value = 19, DamageType = 45, Workmanship = 105, Material = 131, + WieldReq = 158, WieldSkill = 159, WieldDiff = 160; + private const int MeleeDef = 29, ManaConv = 144, MissileDef = 149, MagicDef = 150, VsMonsters = 152; + private const int WarMagic = 34, VoidMagic = 43, Ebony = 73; // Ebony: no Salvage rule in the excerpt + + public static void Register(Runner r) + { + r.Add("loot wands: tier 8 war and void casters get LootSnob's own wand rules (Max 385/375/355, OD, MD, MC)", WandsGetTheirRules); + r.Add("loot wands: the cantrips count (Spirit Thirst OD +2/+5, Defender, Hermetic Link), as floats", WandCantrips); + r.Add("loot wands: without its ID a caster waits for it; elemental damage is ID data", WandWithoutId); + r.Add("loot wands: a switched-off rule that would take the wand is named (/ra loot why, chat, window)", SwitchedOffRuleNamed); + r.Add("loot wands: on a corpse the wand's damage is read from the host after its ID and it is kept", CorpseWandKept); + r.Add("loot wands: on a corpse, a wand left because its rule is switched off says so in the log", CorpseWandSwitchedOff); + } + + private static VTankLootProfile Excerpt() + => VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl")); + + private static VTankLootContext Ctx() => new(FakeHost.Create(), Player); + + private static uint Spell(string name) + { + int id = SpellDatabase.GetIdByName(name); + if (id == 0) throw new InvalidOperationException($"spell '{name}' is not in SpellData.txt"); + return (uint)id; + } + + /// A caster as ACE's tier 8 caster mutations make it, identified. + private static Item Caster(string name, int skill, int wield, double vsMonsters, double def, double manaConv = 0.06, + double magicDef = 1.02, params string[] spells) + { + var c = new Item(name, AcObjectClass.WandStaffOrb) + .Int(ItemType, 0x8000).Int(ValidLoc, 0x01000000).Int(Value, 25000).Int(Burden, 50).Int(Material, Ebony) + .Int(Workmanship, 6).Dbl(MeleeDef, def).Dbl(ManaConv, manaConv).Dbl(MissileDef, 1.03).Dbl(MagicDef, magicDef); + if (wield > 0) c.Int(WieldReq, 2).Int(WieldSkill, skill).Int(WieldDiff, wield); + if (vsMonsters > 0) c.Dbl(VsMonsters, vsMonsters).Int(DamageType, skill == VoidMagic ? 0x400 : 0x10); + if (spells.Length > 0) FakeHost.SpellIds[unchecked((uint)c.Wo.Id)] = spells.Select(Spell).ToArray(); + return c; + } + + private static string? First(VTankLootProfile p, Item item) => VTankLootEvaluator.FirstMatch(p, item, Ctx(), out _)?.Name.Trim(); + + private static void WandsGetTheirRules() + { + FakeHost.Reset(); + VTankLootProfile p = Excerpt(); + Check.Eq(First(p, Caster("Fire Sceptre", WarMagic, 385, 1.18, 1.12)), "(W) War (Max 385)", "1.18 at 385: War (Max 385)"); + Check.Eq(First(p, Caster("Frost Baton", WarMagic, 375, 1.15, 1.10)), "(W) War (Max 375)", "1.15 at 375: War (Max 375)"); + Check.Eq(First(p, Caster("Acid Staff", WarMagic, 355, 1.13, 1.08)), "(W) War (Max 355)", "1.13 at 355: War (Max 355)"); + Check.Null(First(p, Caster("Fire Baton", WarMagic, 375, 1.14, 1.08)), "1.14 at 375, 1.08 defense: no rule (LootSnob leaves it)"); + Check.Eq(First(p, Caster("Blunt Sceptre", WarMagic, 385, 1.18, 1.20)), "(W) War (18pvm + 20md)", "1.18 and 1.20 defense"); + Check.Eq(First(p, Caster("Piercing Sceptre", WarMagic, 355, 1.17, 1.25)), "(W) War (amazing 355)", "1.17 at 355 with 1.25 defense"); + Check.Eq(First(p, Caster("Slashing Sceptre", WarMagic, 385, 1.10, 1.26)), "(W) War (26MD)", "a war caster on defense alone"); + Check.Eq(First(p, Caster("Nether Sceptre", VoidMagic, 385, 1.18, 1.12)), "(W) Void (Max 385)", "void 1.18 at 385"); + Check.Eq(First(p, Caster("Nether Baton", VoidMagic, 375, 1.18, 1.17)), "(W) Void (18pvm + 17md)", "void 1.18 and 1.17 defense"); + Check.Null(First(p, Caster("Nether Staff", VoidMagic, 355, 1.12, 1.05)), "void 1.12 at 355: under Void (Max 355)'s 1.13"); + // The name filters are LootSnob's: War wants Baton|Sceptre|Staff, Void wants Nether. + Check.Null(First(p, Caster("Fire Wand", WarMagic, 385, 1.18, 1.12)), "a war caster named 'Wand' is outside LootSnob's War names"); + Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.24)), "(W) No Wield (24MD)", "an orb with no wield requirement on defense"); + Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.10, magicDef: 1.0)), "(W) No Wield (20MD + 10MC)", "20 defense and 10% mana conversion"); + Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.05, magicDef: 1.04)), "(W) No Wield (20MD + 4MgcD)", "20 defense and 4% magic defense"); + Check.Null(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.05, magicDef: 1.0)), "20 defense alone"); + Check.Null(First(p, Caster("Orb", WarMagic, 330, 0, 1.24)), "an orb with a wield requirement (330) is not 'No Wield', and War wants Baton|Sceptre|Staff"); + } + + private static void WandCantrips() + { + FakeHost.Reset(); + VTankLootProfile p = Excerpt(); + Check.Eq(First(p, Caster("Electric Baton", WarMagic, 385, 1.17, 1.10, spells: "Major Spirit Thirst")), "(W) War (OD +2)", + "1.17 + Major Spirit Thirst 0.03 = 1.20 (as floats)"); + Check.Eq(First(p, Caster("Nether Sceptre", VoidMagic, 385, 1.16, 1.10, spells: "Legendary Spirit Thirst")), "(W) Void (OD +5)", + "1.16 + Legendary Spirit Thirst 0.07 = 1.23"); + Check.Eq(First(p, Caster("Fire Baton", WarMagic, 375, 1.14, 1.10, spells: "Epic Spirit Thirst")), "(W) War (OD +1)", + "1.14 + Epic Spirit Thirst 0.05 = 1.19"); + Check.Eq(First(p, Caster("Frost Baton", WarMagic, 375, 1.14, 1.10, spells: "Minor Spirit Thirst")), "(W) War (Max 375)", + "Max 375 reads the buffed value too: 1.14 + 0.01"); + Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.17, spells: "Epic Defender")), "(W) No Wield (24MD)", "1.17 + Epic Defender 0.07"); + Check.Null(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.08, magicDef: 1.0, spells: "Minor Hermetic Link")), + "0.08 x Minor Hermetic Link 1.10 = 0.088: under 10% mana conversion"); + Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.08, magicDef: 1.0, spells: "Legendary Hermetic Link")), "(W) No Wield (20MD + 10MC)", + "0.08 x Legendary Hermetic Link 1.30 = 0.104"); + // A castable item spell is not a cantrip: it adds nothing. + Check.Eq(First(p, Caster("Fire Sceptre", WarMagic, 385, 1.18, 1.12, spells: "Flame Bolt VI")), "(W) War (Max 385)", "its own war spell adds nothing"); + } + + private static void WandWithoutId() + { + FakeHost.Reset(); + VTankLootProfile p = Excerpt(); + // What the CreateObject shows: name, class, value, burden, material. No 152, wield or defense. + var bare = new Item("Fire Sceptre", AcObjectClass.WandStaffOrb).Int(ItemType, 0x8000).Int(ValidLoc, 0x01000000) + .Int(Value, 25000).Int(Burden, 50).Int(Material, Ebony); + Check.Eq(VTankLootEvaluator.Decide(p, bare, Ctx(), hasIdData: false, out int idx), VTankLootVerdict.NeedsId, "a caster waits for its ID"); + Check.Eq(p.Rules[idx].Name.Trim(), "(W) No Wield (29MD)", "at LootSnob's first wand rule"); + static VTankLootCondition C(int node, params string[] data) => new(node, "0", data); + Check.True(VTankLootEvaluator.ConditionNeedsId(C(VTankNodeTypes.BuffedDoubleValKeyGE, "1.18", "152")), "buffed elemental damage needs the ID"); + Check.True(VTankLootEvaluator.ConditionNeedsId(C(VTankNodeTypes.DoubleValKeyGE, "1.18", "152")), "plain elemental damage too"); + Check.True(VTankLootEvaluator.ConditionNeedsId(C(VTankNodeTypes.LongValKeyE, "385", "160")), "and the wield difficulty"); + Check.Null(VTankLootEvaluator.FirstMatch(p, bare, Ctx(), out _), "judged with 0s nothing takes it (why it must wait)"); + } + + private static VTankLootProfile WithOff(params string[] names) + { + VTankLootProfile p = Excerpt(); + foreach (VTankLootRule r in p.Rules) + if (names.Contains(r.Name.Trim())) LootEditSessionOff(r); + return p; + } + + // As the Loot Editor switches a rule off (LootEditSession.SetEnabled: a DisabledRule node "true" at the end). + private static void LootEditSessionOff(VTankLootRule r) + => r.Conditions.Add(new VTankLootCondition(VTankNodeTypes.DisabledRule, "0", new[] { "true" })); + + private static void SwitchedOffRuleNamed() + { + FakeHost.Reset(); + VTankLootProfile p = WithOff("(W) War (Max 385)", "(W) War (18pvm + 20md)"); + var wand = Caster("Fire Sceptre", WarMagic, 385, 1.18, 1.12); + Check.Null(First(p, wand), "with War (Max 385) off, nothing takes the 1.18 / 385 sceptre"); + int off = VTankLootEvaluator.FirstSwitchedOffMatch(p, wand, Ctx()); + Check.True(off >= 0 && p.Rules[off].Name.Trim() == "(W) War (Max 385)", $"the switched-off rule that would take it ({(off >= 0 ? p.Rules[off].Name : "none")})"); + Check.Eq(VTankLootEvaluator.FirstSwitchedOffMatch(p, Caster("Fire Baton", WarMagic, 375, 1.14, 1.08), Ctx()), -1, "none for a wand no rule wants"); + Check.Eq(VTankLootEvaluator.FirstSwitchedOffMatch(Excerpt(), wand, Ctx()), -1, + "LootSnob's own switched-off rules (the 'leave this disabled' separators, Creature Cantrip ...) don't take it"); + Check.True(VTankLootEvaluator.FirstSwitchedOffMatch(p, wand, Ctx(), end: off) == -1, "only rules above the end count"); + + LootWhy.Result why = LootWhy.Explain(p, wand, Ctx(), hasIdData: true); + Check.Eq(why.Verdict, VTankLootVerdict.NoMatch, "no rule matches"); + Check.Eq(why.SwitchedOffName, "(W) War (Max 385)", "why names the switched-off rule"); + Check.Eq(why.SwitchedOffAction, VTankLootAction.Keep, "and what it does"); + Check.True(why.NearMisses.Any(m => m.RuleName == "(W) War (OD +7)" && m.Failed.Contains("read 1.18")), + "the OD rules came close, reading its 1.18 (" + string.Join(" | ", why.NearMisses.Take(3).Select(LootWhy.NearMissLine)) + ")"); + + LootWhy.Report r = LootWhy.Describe("Fire Sceptre", true, "left", "LootSnobV4.utl", p.Rules.Count, why, askedForId: false); + string expect = $"#{off + 1} '(W) War (Max 385)' [Keep]"; + Check.Eq(r.SwitchedOff, expect, "the report carries it"); + var lines = LootWhy.ChatLines(r, 3); + Check.Eq(lines[2], "[RynthAi] Switched off in the profile: " + expect + + " would take it. Switch that rule on in the Loot Editor to loot items like this.", "chat says so, after the decision"); + Check.True(lines.Count > 3 && lines[3].Contains("came close"), "then the near misses as before"); + + // A rule that takes the item comes first: a switched-off rule below the winner isn't named. + VTankLootProfile q = WithOff("(W) War (Max 375)"); + LootWhy.Result kept = LootWhy.Explain(q, wand, Ctx(), hasIdData: true); + Check.Eq(kept.RuleName, "(W) War (Max 385)", "kept by Max 385"); + Check.Eq(kept.SwitchedOffIndex, -1, "Max 375 (off, below it) isn't named"); + Check.Eq(LootWhy.Describe("Fire Sceptre", true, "[Keep] (W) War (Max 385)", "x.utl", q.Rules.Count, kept, false).SwitchedOff, "", + "nothing switched off in its report"); + + // LootSnob ships its Salvage rules off: /ra loot why names one (the player may want it), the + // looter's log line (keeps only) doesn't, or nearly every left item would carry one. + VTankLootProfile s = Excerpt(); + var ebony = new VTankLootRule { Name = "(Salv) Ebony", Action = VTankLootAction.Salvage }; + ebony.Conditions.Add(new VTankLootCondition(VTankNodeTypes.LongValKeyE, "0", new[] { Ebony.ToString(), Material.ToString() })); + LootEditSessionOff(ebony); + s.Rules.Add(ebony); + var plainBaton = Caster("Fire Baton", WarMagic, 375, 1.14, 1.08); + Check.Eq(VTankLootEvaluator.FirstSwitchedOffMatch(s, plainBaton, Ctx()), s.Rules.Count - 1, "any action: the switched-off Ebony salvage"); + Check.Eq(VTankLootEvaluator.FirstSwitchedOffMatch(s, plainBaton, Ctx(), keepsOnly: true), -1, "keeps only: none"); + Check.Eq(LootWhy.Explain(s, plainBaton, Ctx(), hasIdData: true).SwitchedOffAction, VTankLootAction.Salvage, "/ra loot why names the salvage rule"); + + // Without the ID its stats read 0: no switched-off rule is judged. + var bare = new Item("Fire Sceptre", AcObjectClass.WandStaffOrb).Int(ItemType, 0x8000).Int(Value, 25000); + Check.Eq(LootWhy.Explain(p, bare, Ctx(), hasIdData: false).SwitchedOffIndex, -1, "no ID: none named"); + } + + // ── On a corpse: the looter, the host's reads, the log ─────────────────── + + private const uint Corpse = 0x80265100; + private const uint Wand = 0x80265101; + private const uint LongDescKey = 16; + private const string Me = "Test Looter"; + private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f); + private static long _now; + + private static void Clocked(Action body) + { + var old = RynthAiPlugin.CorpseClock; + _now = 70_000_000; + RynthAiPlugin.CorpseClock = () => _now; + try { body(); } + finally { RynthAiPlugin.CorpseClock = old; } + } + + private static void World() + { + FakeHost.Reset(); + FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal + FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData + FakeHost.Names[Player] = Me; + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + FakeHost.Names[Corpse] = "Corpse of Tusker Guard"; + FakeHost.ItemTypes[Corpse] = 0x200; + FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(Corpse); + FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); + // The CreateObject: name, type, slot, value, burden, material. + FakeHost.Names[Wand] = "Fire Sceptre"; + FakeHost.ItemTypes[Wand] = 0x8000; + FakeHost.Containers[Wand] = Corpse; + foreach (var (k, v) in new (uint, int)[] { (1, 0x8000), (9, 0x01000000), (19, 28640), (5, 50), (131, Ebony) }) + FakeHost.Ints[(Wand, k)] = v; + } + + /// The ID lands: wield 385 War Magic, fire, workmanship 6; 1.18 vs monsters, 1.12 defense. + private static void Identify() + { + foreach (var (k, v) in new (uint, int)[] { (105, 6), (158, 2), (159, WarMagic), (160, 385), (45, 0x10) }) + FakeHost.Ints[(Wand, k)] = v; + FakeHost.Doubles[(Wand, VsMonsters)] = 1.18; + FakeHost.Doubles[(Wand, MeleeDef)] = 1.12; + FakeHost.Doubles[(Wand, ManaConv)] = 0.06; + FakeHost.Doubles[(Wand, MissileDef)] = 1.03; + FakeHost.Doubles[(Wand, MagicDef)] = 1.02; + FakeHost.SpellIds[Wand] = new[] { Spell("Flame Bolt VI") }; + FakeHost.Appraised.Add(Wand); + } + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() + { + IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0, + LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false, + LootAssessWindowMs = 200, LootCorpseTimeoutMs = 12_000, + }; + public readonly WorldObjectCache Cache; + + public Bot(RynthCoreHost host, VTankLootProfile profile, string file) + { + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Cache = new WorldObjectCache(host); + Cache.SetPlayerId(Player); + Set("_objectCache", Cache); + Set("_playerId", Player); + Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }); + string path = Path.Combine(Program.TempRoot, file); + File.WriteAllText(path, VTankLootWriter.Serialize(profile)); + S.CurrentLootPath = path; + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!; + public void Tick() + { + Set("_activity", BotActivity.Looting); + typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(P, null); + } + public bool Completed(uint corpse) => + Get>("_completedCorpses").ContainsKey(unchecked((int)corpse)); + } + + private static bool Moved() => FakeHost.ExternalMoves.Any(m => m.Id == Wand); + + private static Bot OpenCorpse(VTankLootProfile profile, string file) + { + World(); + var host = FakeHost.Create(Player); + var bot = new Bot(host, profile, file); + bot.Cache.OnCreateObject(Corpse); + bot.Cache.OnCreateObject(Wand); + bot.Cache.Tick(); + bot.Tick(); + Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened"); + FakeHost.UseDone(0); + bot.P.OnViewObjectContents(Corpse); + for (int i = 0; i < 5; i++) { _now += 20; bot.Tick(); } + Check.True(FakeHost.IdRequests.Contains(Wand), "the wand's ID is asked for (LootSnob's wand rules need it)"); + Check.False(Moved(), "not taken before its ID"); + return bot; + } + + private static void CorpseWandKept() => Clocked(() => + { + var bot = OpenCorpse(Excerpt(), "loot-wand-stock.utl"); + Identify(); + // Read through the host as the looter reads it: the WorldObject in the cache, no overlay. + WorldObject? wo = bot.Cache[unchecked((int)Wand)]; + Check.NotNull(wo, "the wand is in the cache"); + Check.Near(wo?.Values((DoubleValueKey)VsMonsters, 0.0) ?? 0, 1.18, 1e-9, "elemental damage vs monsters read from the host after the ID"); + for (int i = 0; i < 200 && !Moved(); i++) { _now += 20; bot.Tick(); } + Check.True(Moved(), "taken once the ID is in"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Loot rule: Fire Sceptre -> [Keep] (W) War (Max 385)")), + "by LootSnob's War (Max 385) (chat: " + string.Join(" | ", FakeHost.Chat.Where(c => c.Contains("Loot rule"))) + ")"); + }); + + private static void CorpseWandSwitchedOff() => Clocked(() => + { + VTankLootProfile p = WithOff("(W) War (Max 385)"); + var bot = OpenCorpse(p, "loot-wand-off.utl"); + Identify(); + for (int i = 0; i < 1000 && !bot.Completed(Corpse); i++) { _now += 20; bot.Tick(); } + Check.False(Moved(), "left: the rule that wants it is off"); + int off = p.Rules.FindIndex(r => r.Name.Trim() == "(W) War (Max 385)"); + string note = $"-> leave (switched-off rule #{off + 1} '(W) War (Max 385)' [Keep] would take it)"; + Check.True(FakeHost.Logs.Any(l => l.Contains("[LootEval] 'Fire Sceptre'") && l.Contains(note)), + "the log's leave line names the switched-off rule (" + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("[LootEval] 'Fire Sceptre'"))) + ")"); + }); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaSaveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaSaveTests.cs new file mode 100644 index 0000000..5163026 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaSaveTests.cs @@ -0,0 +1,309 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-11-01, "still having trouble editing metas and the changes not saving". Meta edits go: +// the engine's Meta panel -> RynthPluginSendMetaCommand -> HandleMetaCommand -> DrainMetaCommands -> +// ApplyMetaCommand -> MetaSaver (or RynthAi's own Macro Rules window -> TryAutoSaveMeta -> MetaSaver). +// Before: no save logged anything, a save that didn't happen (no file, a stale rule index, a command +// that threw) returned silently, and at login a meta ran the copy of its rules kept in the settings +// profile, not its file. These tests drive the commands in the engine's wire format (MetaData.cs +// MetaCmd and MetaRuleDto.cs: PascalCase, LastFiredMs included) on scratch files only. +internal static class MetaSaveTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + private const string TwoRules = + "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n\tIF:\tNever\n\t\tDO:\tChat {/say two}\n~~ }\n"; + + public static void Register(Runner r) + { + r.Add("meta save: an engine update_rule rewrites the .af and logs it once (path, rule count)", EngineUpdateSaves); + r.Add("meta save: a write that fails says why (status, log, snapshot) and the next edit saves", FailedWriteSays); + r.Add("meta save: an edit to a meta with no file is refused with the reason, not silently", NoFileRefused); + r.Add("meta save: an update for a rule index the meta doesn't have is refused and logged", StaleIndexRefused); + r.Add("meta save: a command that doesn't read is logged, not swallowed", GarbageCommandLogged); + r.Add("meta save: Save As (save_file) writes, logs and switches to the new file", SaveAsSwitches); + r.Add("meta save: the Macro Rules window's autosave shows Saved / NOT saved in its status line", LegacyStatusLine); + r.Add("meta save: at login the meta runs its file's rules, not the profile's old copy", LoginUsesFile); + r.Add("meta save: an edit after login is written on top of the newer file, not over it", EditAfterLoginKeepsFile); + r.Add("meta save: a profile whose last meta save failed keeps its copy at login and says so", UnsavedProfileCopyKept); + r.Add("meta save: a missing meta file at login keeps the profile's copy (logged)", MissingFileKeepsCopy); + } + + // ── helpers ────────────────────────────────────────────────────────────── + + private static string Dir(string name) + { + string dir = Path.Combine(Program.TempRoot, "meta-save", name); + if (Directory.Exists(dir)) + { + foreach (string f in Directory.GetFiles(dir, "*", SearchOption.AllDirectories)) File.SetAttributes(f, FileAttributes.Normal); + Directory.Delete(dir, recursive: true); + } + Directory.CreateDirectory(dir); + return dir; + } + + private static LegacyMetaUi MetaUi(LegacyDashboardRenderer dash) => + (LegacyMetaUi)typeof(LegacyDashboardRenderer).GetField("_metaUi", Any)!.GetValue(dash)!; + + private static MetaSaver Saver(LegacyDashboardRenderer dash) => + (MetaSaver)typeof(LegacyDashboardRenderer).GetField("_metaSaver", Any)!.GetValue(dash)!; + + /// A dashboard with farm.af (two rules) loaded from a scratch folder. + private static string NewMeta(string name, out LegacyDashboardRenderer dash) + { + string path = Path.Combine(Dir(name), "farm.af"); + File.WriteAllText(path, TwoRules); + FakeHost.Reset(); + DataWriteGuard.Reset(); + dash = new LegacyDashboardRenderer(FakeHost.Create()); + var ui = MetaUi(dash); + Check.True(ui.LoadMacroFile(path), "loads: " + ui.LastLoadStatus); + return path; + } + + private static string RuleJson(string say, string state = "Default") => + "{\"State\":\"" + state + "\",\"Condition\":1,\"ConditionData\":\"\",\"Action\":1,\"ActionData\":\"" + say + "\"," + + "\"Children\":[],\"ActionChildren\":[],\"Enabled\":true,\"Name\":\"\",\"LastFiredMs\":99999}"; + + private static string Cmd(string op, int index = -1, string? rule = null, string path = "") => + "{\"Op\":\"" + op + "\",\"Index\":" + index + ",\"Value\":\"\",\"Path\":\"" + path.Replace("\\", "\\\\") + "\",\"Text\":\"\"" + + (rule != null ? ",\"Rule\":" + rule : "") + "}"; + + private static void Send(LegacyDashboardRenderer dash, string json) + { + dash.HandleMetaCommand(json); + dash.DrainMetaCommands(); + } + + private static int LogCount(string part) + { + int n = 0; + foreach (string l in FakeHost.Logs) + if (l.Contains(part, StringComparison.OrdinalIgnoreCase)) n++; + return n; + } + + private static string LogWith(string part) + { + foreach (string l in FakeHost.Logs) + if (l.Contains(part, StringComparison.OrdinalIgnoreCase)) return l; + return "(no log line with '" + part + "'; log: " + string.Join(" | ", FakeHost.Logs) + ")"; + } + + /// The snapshot's saveResult, as the engine panel reads it. + private static (long Seq, bool Ok, string Text, string Path) SaveResult(LegacyDashboardRenderer dash) + { + using var doc = JsonDocument.Parse(dash.BuildMetaJson()); + JsonElement r = doc.RootElement.GetProperty("saveResult"); + return (r.GetProperty("seq").GetInt64(), r.GetProperty("ok").GetBoolean(), + r.GetProperty("text").GetString() ?? "", r.GetProperty("path").GetString() ?? ""); + } + + // ── engine panel commands ──────────────────────────────────────────────── + + private static void EngineUpdateSaves() + { + string path = NewMeta("update", out var dash); + var loadedResult = SaveResult(dash); + Check.True(loadedResult.Ok && loadedResult.Text.Contains("Loaded farm.af"), "the load is the last result: " + loadedResult.Text); + long s0 = loadedResult.Seq; + Send(dash, Cmd("update_rule", 0, RuleJson("/say edited"))); + Check.Eq(dash.Settings.MetaRules[0].ActionData, "/say edited", "applied in memory"); + Check.True(File.ReadAllText(path).Contains("/say edited"), "written to the file"); + Check.Eq(LogCount("Meta saved"), 1, "one log line for the save"); + string line = LogWith("Meta saved"); + Check.True(line.Contains(path) && line.Contains("2 rules"), "names the path and the rule count: " + line); + var r = SaveResult(dash); + Check.True(r.Seq == s0 + 1 && r.Ok && r.Text.Contains("Saved farm.af") && r.Path == path, $"snapshot says saved: {r}"); + + Send(dash, Cmd("add_rule", -1, RuleJson("/say three"))); + Check.True(File.ReadAllText(path).Contains("/say three"), "add_rule written"); + Check.True(SaveResult(dash).Seq == s0 + 2 && LogWith("Meta saved: " + path + " (3 rules").Contains("3 rules"), "add_rule logged with the new count"); + + // A move with nothing to swap still answers (the panel isn't left waiting), and writes nothing. + int saves = LogCount("Meta saved"); + Send(dash, Cmd("move_up", 0)); + var moved = SaveResult(dash); + Check.True(moved.Seq == s0 + 3 && moved.Ok && moved.Text.Contains("Nothing to move"), "no-op move answered: " + moved.Text); + Check.Eq(LogCount("Meta saved"), saves, "and wrote nothing"); + } + + private static void FailedWriteSays() + { + string path = NewMeta("fail", out var dash); + using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + { + Send(dash, Cmd("update_rule", 1, RuleJson("/say held"))); + var r = SaveResult(dash); + Check.False(r.Ok, "snapshot says not saved"); + Check.True(r.Text.Contains("NOT saved") && r.Text.Contains("open in another program"), "says why: " + r.Text); + Check.True(LogWith("Meta NOT saved").Contains(path), "logged with the path"); + Check.True(dash.Settings.MetaUnsaved, "the profile's copy is marked as the newer one"); + } + Check.True(DataWriteGuard.PendingCount == 1, "and the once-per-folder chat line is queued"); + Check.False(File.ReadAllText(path).Contains("/say held"), "file untouched while held"); + Send(dash, Cmd("set_rule_enabled", 0) .Replace("\"Value\":\"\"", "\"Value\":\"true\"")); + Check.True(SaveResult(dash).Ok && File.ReadAllText(path).Contains("/say held"), "the next edit saves everything"); + Check.False(dash.Settings.MetaUnsaved, "and clears the mark"); + } + + private static void NoFileRefused() + { + FakeHost.Reset(); + var dash = new LegacyDashboardRenderer(FakeHost.Create()); + Check.True(MetaUi(dash).LoadMacroFile(""), "a new, empty meta"); + Send(dash, Cmd("add_rule", -1, RuleJson("/say lonely"))); + Check.Eq(dash.Settings.MetaRules.Count, 1, "the rule is added"); + var r = SaveResult(dash); + Check.True(!r.Ok && r.Text.Contains("no file") && r.Text.Contains("Save As"), "says it has no file and what to do: " + r.Text); + Check.True(LogCount("no file") == 1, "logged: " + LogWith("no file")); + } + + private static void StaleIndexRefused() + { + string path = NewMeta("stale", out var dash); + string before = File.ReadAllText(path); + long s0 = SaveResult(dash).Seq; + Send(dash, Cmd("update_rule", 5, RuleJson("/say ghost"))); + var r = SaveResult(dash); + Check.True(!r.Ok && r.Text.Contains("rule 6 isn't in the meta"), "says which rule and why: " + r.Text); + Check.True(LogWith("update_rule").Contains("isn't in the meta"), "logged"); + Check.Eq(File.ReadAllText(path), before, "file untouched"); + Send(dash, Cmd("delete_rule", 9)); + Check.True(SaveResult(dash).Seq == s0 + 2 && !SaveResult(dash).Ok, "delete of a missing rule is refused too"); + Check.Eq(dash.Settings.MetaRules.Count, 2, "nothing deleted"); + } + + private static void GarbageCommandLogged() + { + NewMeta("garbage", out var dash); + Send(dash, "{\"Op\":\"update_rule\",\"Index\":\"zero\"}"); + var r = SaveResult(dash); + Check.True(!r.Ok && r.Text.Contains("Edit not applied"), "said: " + r.Text); + Check.True(LogWith("Edit not applied").Contains("Exception"), "the exception is logged: " + LogWith("Edit not applied")); + } + + private static void SaveAsSwitches() + { + string path = NewMeta("saveas", out var dash); + string copy = Path.Combine(Path.GetDirectoryName(path)!, "farm2.af"); + Send(dash, Cmd("save_file", path: copy)); + Check.True(File.Exists(copy) && File.ReadAllText(copy).Contains("/say two"), "the copy is written"); + Check.Eq(dash.Settings.CurrentMetaPath, copy, "editing continues in the copy"); + Check.True(LogWith("Meta saved: " + copy).Contains("Save As"), "logged"); + Send(dash, Cmd("update_rule", 0, RuleJson("/say in copy"))); + Check.True(File.ReadAllText(copy).Contains("/say in copy") && !File.ReadAllText(path).Contains("/say in copy"), "later edits go to the copy"); + } + + // ── RynthAi's own Macro Rules window ───────────────────────────────────── + + private static void LegacyStatusLine() + { + string path = NewMeta("legacy", out var dash); + var ui = MetaUi(dash); + MethodInfo autosave = typeof(LegacyMetaUi).GetMethod("TryAutoSaveMeta", Any)!; + dash.Settings.MetaRules[0].ActionData = "/say window"; + autosave.Invoke(ui, null); + Check.True(ui.StatusLine.StartsWith("Saved farm.af"), "status line: " + ui.StatusLine); + Check.True(File.ReadAllText(path).Contains("/say window"), "written"); + Check.True(LogWith("Meta saved").Contains("Macro Rules"), "logged through the dashboard's saver"); + using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + autosave.Invoke(ui, null); + Check.True(ui.StatusLine.Contains("NOT saved"), "a failure shows: " + ui.StatusLine); + Check.True(ReferenceEquals(ui.Saver, Saver(dash)), "one saver for both editors"); + } + + // ── login: the file is the meta ────────────────────────────────────────── + + /// A character whose profile names farm.af and holds a copy of its two rules. + private static string ProfileWithMeta(string name, out string metaPath, Action? tweak = null) + { + string root = Dir(name); + LegacyDashboardRenderer.ProfilesBase = Path.Combine(root, "SettingsProfiles"); + LegacyDashboardRenderer.MonstersBase = Path.Combine(root, "MonsterProfiles"); + metaPath = Path.Combine(root, "farm.af"); + File.WriteAllText(metaPath, TwoRules); + FakeHost.Reset(); + FakeHost.WorldName = "TestWorld"; + var dash = new LegacyDashboardRenderer(FakeHost.Create()); + dash.LoadSettings("Tester"); + Check.True(MetaUi(dash).LoadMacroFile(metaPath), "loads"); + tweak?.Invoke(dash.Settings); + dash.SaveSettings(); + return root; + } + + private static LegacyDashboardRenderer Relog() + { + FakeHost.Reset(); + FakeHost.WorldName = "TestWorld"; + var dash = new LegacyDashboardRenderer(FakeHost.Create()); + dash.LoadSettings("Tester"); + return dash; + } + + private static void LoginUsesFile() + { + ProfileWithMeta("login-file", out string meta); + // Changed elsewhere: another client, the rmeta tool, a text editor. + File.WriteAllText(meta, TwoRules.Replace("/say two", "/say changed elsewhere")); + var dash = Relog(); + Check.Eq(dash.Settings.CurrentMetaPath, meta, "same meta"); + Check.Eq(dash.Settings.MetaRules.Count, 2, "two rules"); + Check.Eq(dash.Settings.MetaRules[1].ActionData, "/say changed elsewhere", "the file's rules run, not the profile's old copy"); + Check.True(LogWith("differs from the copy").Contains(meta), "logged"); + dash.SaveSettings(); // what the autosave does next: the profile's copy is the file's now + + var again = Relog(); + Check.Eq(LogCount("differs from the copy"), 0, "an unchanged file loads quietly"); + Check.Eq(again.Settings.MetaRules[1].ActionData, "/say changed elsewhere", "still the file's"); + } + + private static void EditAfterLoginKeepsFile() + { + ProfileWithMeta("login-edit", out string meta); + File.WriteAllText(meta, TwoRules.Replace("/say two", "/say newer file")); + var dash = Relog(); + Send(dash, Cmd("update_rule", 0, RuleJson("/say my edit"))); + string text = File.ReadAllText(meta); + Check.True(text.Contains("/say my edit") && text.Contains("/say newer file"), "the edit lands on the newer file: " + text); + } + + private static void UnsavedProfileCopyKept() + { + ProfileWithMeta("login-unsaved", out string meta, s => + { + s.MetaRules[1].ActionData = "/say edit that never reached the file"; + s.MetaUnsaved = true; + }); + var dash = Relog(); + Check.Eq(dash.Settings.MetaRules[1].ActionData, "/say edit that never reached the file", "the profile's copy is kept"); + Check.True(LogWith("wasn't saved to the file").Contains(meta), "logged"); + Check.True(FakeHost.Chat.Exists(c => c.Contains("wasn't saved to its file")), "and said in chat"); + Send(dash, Cmd("set_rule_enabled", 0).Replace("\"Value\":\"\"", "\"Value\":\"true\"")); + Check.True(File.ReadAllText(meta).Contains("/say edit that never reached the file"), "the next save writes it"); + Check.False(dash.Settings.MetaUnsaved, "mark cleared"); + } + + private static void MissingFileKeepsCopy() + { + ProfileWithMeta("login-missing", out string meta); + File.Delete(meta); + var dash = Relog(); + Check.Eq(dash.Settings.MetaRules.Count, 2, "the profile's copy runs"); + Check.True(LogWith("isn't there").Contains(meta), "logged"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs index 3a7a208..f6715da 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs @@ -36,6 +36,9 @@ internal static class TargetingTests r.Add("targeting: a higher priority out of sight is named as passed over, once per reason", PassedOverOutOfSight); r.Add("targeting: a higher priority just past Monster Range is named on the lock line", PassedOverBeyondRange); r.Add("targeting: nothing is named when no higher priority was left out", PassedOverNothingHigher); + r.Add("targeting: lock off keeps a target that blinks out of the scan (no switch on stale values)", LockOffNoSwitchOnStale); + r.Add("targeting: lock off holds right after a cast goes out, before it is judged", LockOffHoldsJustSentCast); + r.Add("targeting: a higher priority just past Monster Range is logged once while fighting, and /ra why names it", BeyondRangeWhileEngaged); } // ── Schemes ─────────────────────────────────────────────────────────────── @@ -317,6 +320,59 @@ internal static class TargetingTests Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")), "the target itself out of sight isn't 'passed over'"); } + // ── R-20261031-201214-8be7: a switch on stale values, 124 ms after a bolt went out ───── + + private static void LockOffNoSwitchOnStale() + { + var t = new Rig(Closest, false); + Check.Eq(t.Pick((A, 4.3, 0)), A, "A, a swarm closing in, is locked at 4.3 m"); + Check.Eq(t.Pick((B, 2.4, 0)), A, "A blinks out of the scan (its last value 4.3 m): kept, not judged on it"); + Check.False(FakeHost.Logs.Any(l => l.Contains("another is clearly better")), "no 'clearly better' switch"); + Check.Eq(t.Pick((A, 1.9, 0), (B, 2.4, 0)), A, "back in the scan at 1.9 m: still A"); + t.Advance(2000); + Check.Eq(t.Pick((B, 2.4, 0)), B, "gone past the scan grace: B"); + } + + private static void LockOffHoldsJustSentCast() + { + var t = new Rig(Closest, false); + Check.Eq(t.Pick((A, 3, 0)), A, "A is locked"); + t.Combat.NoteCastSent(unchecked((int)A)); // the bolt went out; no judgement yet + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), A, "a cast just sent at A: B (2.5 m closer) waits"); + t.Combat.ReportDamageOnTarget(unchecked((int)A)); + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "the cast landed: the switch goes ahead"); + + t = new Rig(Closest, false); + t.Pick((A, 3, 0)); + t.Combat.NoteCastSent(unchecked((int)A)); + t.Advance(4100); + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "past the 4 s flight window with nothing landed: switch"); + } + + private static void BeyondRangeWhileEngaged() + { + var t = new ScanPick(monsterRange: 10); + t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 }); + t.Place(A, "Mob A", north: 2); + t.Place(Boss, "Boss", north: -40); + Check.Eq(t.Tick(), A, "Mob A is locked; the Boss is far off"); + Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")), "nothing named yet"); + + t.Place(Boss, "Boss", north: -12); // the Boss walks up, still past Monster Range 10 + Check.Eq(t.Tick(), A, "the Boss at 12 m is not a candidate: the target stays (intended)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] passed over 0x80000404 'Boss' priority 5, 12.0 m: beyond Monster Range (10 m), the Monster Range setting") + && l.Contains("the target stays 0x80000401 'Mob A' priority 1")), + "logged: the setting is why"); + int lines = PassedLines(); + t.Tick(); + Check.Eq(PassedLines(), lines, "once"); + string? why = t.C.DescribeHigherPriorityPassedOver(); + Check.True(why != null && why.Contains("'Boss' priority 5") && why.Contains("beyond Monster Range (10 m)"), $"/ra why names it ({why})"); + + t.Place(Boss, "Boss", north: -9); + Check.Eq(t.Tick(), Boss, "inside Monster Range: the Boss takes over at once"); + } + private static int PassedLines() => FakeHost.Logs.Count(l => l.Contains("[CombatTarget] passed over")); /// The real scan (ScanNearbyTargets) over placed monsters, then the pick. @@ -326,6 +382,7 @@ internal static class TargetingTests public readonly HashSet Blocked = new(); private readonly List _ids = new(); private CombatManager? _c; + public CombatManager C => _c!; private static readonly FieldInfo LastScan = typeof(CombatManager).GetField("_lastScanTime", BindingFlags.NonPublic | BindingFlags.Instance)!; diff --git a/Tools/RynthNav.RouteTests/Program.cs b/Tools/RynthNav.RouteTests/Program.cs index 6ba6345..daf0a44 100644 --- a/Tools/RynthNav.RouteTests/Program.cs +++ b/Tools/RynthNav.RouteTests/Program.cs @@ -511,6 +511,38 @@ internal static partial class Program Check(back.Recent.Count == AtlasStore.MaxRecent && back.Recent[0].Name == "P5", "recent survives in order"); Near(back.Favorites[0].Ns, 42.08, 1e-9, "coordinates survive"); Check(back.RemoveFavorite("HOLTBURG") && back.Favorites.Count == 0, "remove by name"); + + // Every client saves atlas.txt: a save applies this client's changes to the file on disk + // (MergeInto), so another client's favorite survives (2026-11-01). + var exp = new SavedPlace { Name = "Abandoned Experiment (Conquest)", Type = "Dungeon", Ns = 42.45, Ew = 56.05 }; + var yaraq = new SavedPlace { Name = "Yaraq", Type = "Town", Ns = -21.5, Ew = -1.8 }; + var a = new AtlasStore(); // the client that adds the dungeon + a.ToggleFavorite(exp); + var disk = AtlasStore.Parse(a.Serialize()); + a.MergeInto(disk); + var b = AtlasStore.Parse(new AtlasStore().Serialize()); // another client, loaded before that save + b.Touch(yaraq); + b.MergeInto(AtlasStore.Parse(a.Serialize())); + Check(b.IsFavorite(exp), "another client's save keeps the favorite it never had"); + Check(b.Recent.Count == 1 && b.Recent[0].Name == "Yaraq", "and puts its own trip in Recent"); + var c = AtlasStore.Parse(b.Serialize()); + c.RemoveFavorite("Abandoned Experiment (Conquest)"); + c.MergeInto(AtlasStore.Parse(b.Serialize())); + Check(!c.IsFavorite(exp), "a removal on one client sticks (the disk copy still had it)"); + var d = AtlasStore.Parse(b.Serialize()); + d.ClearRecent(); + d.MergeInto(AtlasStore.Parse(b.Serialize())); + Check(d.Recent.Count == 0 && d.IsFavorite(exp), "Clear recent sticks; favorites stay"); + var e = new AtlasStore(); + e.MergeInto(AtlasStore.Parse(b.Serialize())); + e.MergeInto(AtlasStore.Parse(e.Serialize())); + Check(e.Favorites.Count == 1 && e.Recent.Count == 1, "merging the same file twice adds nothing"); + + // Names find favorites, with or without a bracketed tag. + Check(b.FindFavorite("abandoned experiment")?.SameAs(exp) == true, "a favorite by its name without the tag"); + Check(b.FindFavorite("Abandoned Experiment (Conquest)")?.SameAs(exp) == true, "and with it"); + Check(b.FindFavorite("Abandoned") == null, "not by part of a word"); + Check(b.FindFavorite("") == null, "nothing for nothing"); } ///