using System; using System.Collections.Generic; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthAi.Loot; /// /// Drives the salvage state machine for loot-rule items marked Salvage. /// Items are enqueued by CorpseOpenController after pickup confirmation. /// /// Flow per item: /// Idle → call OpenSalvagePanel(ustId), wait OpenDelay /// → call AddNewItem(itemId), wait AddDelay /// → call Salvage(), wait SalvageDelay /// → wait ResultDelay → Idle (next item or CombineSalvage) /// /// First-open delays (400ms/600ms) let the panel animate open and the /// gmSalvageUI singleton hook fire before we make thiscall instance calls. /// Fast delays (50ms) apply once the panel has been opened at least once. /// public sealed class SalvageManager { private enum Phase { Idle, OpeningPanel, AddingItem, Salvaging, WaitingForResult, CombiningSalvage } private readonly RynthCoreHost _host; private readonly LegacyUiSettings _settings; private readonly WorldObjectCache? _cache; private readonly Queue _queue = new(); private Phase _phase = Phase.Idle; private long _phaseReadyAt; private uint _currentItemId; private uint _currentUstId; private bool _panelEverOpened; private bool _firstResultCycle = true; private bool _pendingCombineScan; // Combine-salvage state — process one material group per cycle by opening // the salvage panel, adding all under-full bags of that material, and hitting // Salvage so the server merges them server-side. Far more reliable than the // old MoveItemExternal-into-bag approach which AC silently rejects when the // bags have different workmanship. private enum CombinePhase { None, OpeningPanel, AddingBags, Salvaging, WaitingForResult } private List>? _combineGroups; private int _combineGroupIdx; private int _combineAddIdx; private CombinePhase _combinePhase = CombinePhase.None; private long _combinePhaseReadyAt; // Verification — snapshot of the bag ids submitted for the current group's // Execute. After the result delay, we count how many of these are still in // the cache to decide whether the server actually merged them. private List? _combineGroupSnapshot; // Polling deadline for verification. The salvage delete event from the // server can arrive 500ms-1s after Execute on busy servers; we keep // checking inventory until either the items are gone OR this deadline // passes. Without this, fast result delays (~300ms) produce false-negative // re-queues and prevent _pendingCombineScan from ever firing. private long _waitingResultDeadline; private const long ResultMaxWaitMs = 2000; // Session-level combine metrics. Logged per-group so the user can see // running totals without needing a separate diagnostic surface. private int _combineGroupsSucceeded; private int _combineGroupsFailed; private int _bagsMergedThisSession; // Per-item retry counter so a failed salvage gets re-queued a few times // before we give up. AC sometimes drops a Salvage execute when the bot is // busy with other actions; the item stays in the pack and we want to try // again when the queue gets back to idle. private readonly Dictionary _itemRetryCount = new(); private const int MaxItemRetries = 3; // Backoff after a refused panel step. Without it a failed UseObject/AddItem // re-queues the item and TickIdle dequeues it again on the very next tick, // so one busy hiccup burns all three attempts inside ~50ms and the item is // dropped. A second is long enough for the action queue to clear. private long _idleRetryReadyAt; private const long RetryBackoffMs = 1000; // Same for the combine sweep: a refused UseObject used to skip the whole // material group immediately, and with no timer set the next tick tried the // next group — so one hiccup could tear through every group in the sweep. // Retry the group a few times on the same backoff before giving up on it. private int _combineOpenAttempts; private const int MaxCombineOpenAttempts = 3; // Last thing that went wrong, for GetStateSnapshot. The Log() trail has this // but the log is where you look *after* you know salvage is the problem; // this is so a state dump says so on its own. private string _lastError = string.Empty; private long _lastErrorAt; // Periodic combine sweep — even when no items have been salvaged this // session (or every salvage gave up after retries), we still want to // periodically merge any under-full bags sitting in inventory. private long _lastCombineSweepAt; private const long CombineSweepIntervalMs = 30_000; private static long NowMs => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); /// /// Set by the plugin to point at the currently-loaded loot profile's /// SalvageCombine block (if any). When non-null and Enabled, bags are /// grouped by (MaterialType, WorkmanshipBand) per the profile's rules /// instead of just (MaterialType). /// public Func? CombineConfigProvider { get; set; } public SalvageManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache? cache) { _host = host; _settings = settings; _cache = cache; } /// Returns true while a salvage operation is in flight. public bool IsBusy => _phase != Phase.Idle || _queue.Count > 0; /// Enqueue an item to be salvaged. Called by CorpseOpenController after pickup. public void EnqueueItem(uint itemId) { if (itemId == 0) return; // A salvage bag is ALREADY salvage. Feeding one into the single-item // flow opens the panel on a lone bag, Executes a no-op, fails the // "still present" check, and retry-storms — this is the user-reported // "keeps salvaging bags by themselves" behaviour. Bags are consolidated // by the combine sweep (grouped, never solo); they must never enter the // single-item queue. string? name = _cache?[unchecked((int)itemId)]?.Name; if (IsSalvageBag(name)) { Log($"[Salvage] Ignoring enqueue of salvage bag 0x{itemId:X8} ({name}) — bags are combined by the sweep, not salvaged solo."); if (_settings.EnableCombineSalvage) _pendingCombineScan = true; return; } _queue.Enqueue(itemId); _pendingCombineScan = false; // reset; will be set again when queue drains } /// Called every game tick from RynthAiPlugin.OnTick. public void OnTick(int busyCount) { if (!_host.HasSalvagePanel || !_host.HasUseObject) return; long now = NowMs; switch (_phase) { case Phase.Idle: TickIdle(now, busyCount); break; case Phase.OpeningPanel: if (now >= _phaseReadyAt) BeginAddingItem(now); break; case Phase.AddingItem: if (now >= _phaseReadyAt) BeginSalvaging(now); break; case Phase.Salvaging: if (now >= _phaseReadyAt) BeginWaitingForResult(now); break; case Phase.WaitingForResult: if (now < _phaseReadyAt) break; // Poll: if the item is still in inventory and we're under the // deadline, wait for the next tick. Server delete events for // salvage-consumed items can lag the result delay by 500ms+. if (_currentItemId != 0 && now < _waitingResultDeadline && IsItemInDirectInventory(_currentItemId)) { break; } OnResultReady(now); break; case Phase.CombiningSalvage: TickCombiningSalvage(now); break; } } // ── Phase handlers ──────────────────────────────────────────────────────── private void TickIdle(long now, int busyCount) { if (_queue.Count == 0) { if (_pendingCombineScan && _settings.EnableCombineSalvage) { _pendingCombineScan = false; _lastCombineSweepAt = now; BeginCombineSalvage(now); return; } // Periodic standalone sweep: if 30s have passed since the last // combine attempt and there are still under-full bag groups in the // pack, run another pass. Catches bags accumulated from sources // outside the salvage queue (or sessions where every salvage gave // up after retries). if (_settings.EnableCombineSalvage && busyCount == 0 && now - _lastCombineSweepAt >= CombineSweepIntervalMs) { _lastCombineSweepAt = now; BeginCombineSalvage(now); } return; } // Don't start while the game is busy processing a prior action. if (busyCount > 0) return; // Serving out the backoff from a refused panel step. if (now < _idleRetryReadyAt) return; uint itemId = _queue.Dequeue(); if (itemId == 0) return; // Backstop for the EnqueueItem guard: the item's name may not have been // cached at enqueue time. Never run the single-item salvage flow on a // bag — it's already salvage; the combine sweep consolidates it. string? dqName = _cache?[unchecked((int)itemId)]?.Name; if (IsSalvageBag(dqName)) { Log($"[Salvage] Dequeued a salvage bag 0x{itemId:X8} ({dqName}) — skipping solo salvage; combine sweep will consolidate it."); if (_settings.EnableCombineSalvage) _pendingCombineScan = true; return; } uint ustId = FindUst(); if (ustId == 0) { _host.WriteToChat("[RynthAi] Salvage: No UST found in inventory — item skipped. Add a Ust to your pack.", 2); NoteError("no UST in inventory — item skipped"); Log($"[Salvage] No UST found in inventory — skipping 0x{itemId:X8}."); return; } _currentItemId = itemId; _currentUstId = ustId; // UseObject on the UST mimics a double-click — this is the reliable path to // trigger gmSalvageUI::OpenSalvagePanel (our hook captures the instance there). // SendNotice_OpenSalvagePanel does not reliably call the hooked function. if (!_host.UseObject(_currentUstId)) { Log($"[Salvage] UseObject(UST) failed for 0x{_currentUstId:X8} — re-queuing item."); NoteError($"UseObject(UST) failed for 0x{_currentUstId:X8}"); _currentItemId = 0; _currentUstId = 0; RequeueOrDrop(itemId, "UseObject(UST) failed"); _idleRetryReadyAt = now + RetryBackoffMs; return; } int openDelay = _panelEverOpened ? _settings.SalvageOpenDelayFastMs : _settings.SalvageOpenDelayFirstMs; _phaseReadyAt = now + openDelay; _phase = Phase.OpeningPanel; } private void BeginAddingItem(long now) { if (!_host.SalvagePanelAddItem(_currentItemId)) { Log($"[Salvage] SalvagePanelAddItem failed for 0x{_currentItemId:X8} (panel instance not ready — re-queuing)."); NoteError($"SalvagePanelAddItem failed for 0x{_currentItemId:X8} (panel not ready)"); // Re-queue the item so we retry on the next idle cycle. Reset panel-ever-opened // so the longer first-open delays are applied on retry. uint failedItemId = _currentItemId; _currentItemId = 0; _currentUstId = 0; _panelEverOpened = false; _phase = Phase.Idle; RequeueOrDrop(failedItemId, "SalvagePanelAddItem failed"); _idleRetryReadyAt = now + RetryBackoffMs; return; } // Combine-during-salvage: add ALL under-full bags of the same material // (and workmanship band, if configured) alongside the new item so the // server merges everything in one operation. int extraBags = 0; if (_settings.CombineBagsDuringSalvage) extraBags = AddAllMatchingUnderFullBags(_currentItemId); bool wasFirstOpen = !_panelEverOpened; _panelEverOpened = true; // Allow 50 ms per extra bag so AC can register each add before Execute fires. int addDelay = (wasFirstOpen ? _settings.SalvageAddDelayFirstMs : _settings.SalvageAddDelayFastMs) + extraBags * _settings.SalvageAddDelayFastMs; _phaseReadyAt = now + addDelay; _phase = Phase.AddingItem; } // STypes (canonical values from Chorizite STypes.cs — verified against // the live binary; the PropertyNames.IntNames index in this codebase is // off-by-some-rows so do NOT use it as the source of truth). private const uint StypeMaxStructure = 91; private const uint StypeStructure = 92; private const uint StypeItemWorkmanship = 105; private const uint StypeMaterialType = 131; // On a salvage BAG, ItemWorkmanship(#105) is a cumulative SUM, not a 1-10 // value (ACE Player_Crafting.TryAddSalvage). The per-bag average workmanship // used for band grouping is #105 / NumItemsInMaterial(#170). private const uint StypeNumItemsInMaterial = 170; /// /// Scans inventory for every under-full salvage bag whose material (and /// workmanship band, if configured) matches , adds /// each one to the open salvage panel, and returns how many were added. /// Adding them all at once lets the server merge everything in one Salvage /// operation instead of leaving partial bags for the periodic sweep. /// private int AddAllMatchingUnderFullBags(uint itemId) { if (_cache == null) return 0; if (!_host.TryGetObjectIntProperty(itemId, StypeMaterialType, out int itemMat) || itemMat == 0) return 0; RynthCore.Loot.SalvageCombineSettings? cfg = CombineConfigProvider?.Invoke(); bool useBands = cfg != null && cfg.Enabled; // The freshly-looted ITEM carries a true 1-10 ItemWorkmanship(#105) — // unlike a bag, whose #105 is a cumulative sum. So the item's band is // read directly here; bag keys come from TryGetBagCombineKey (average). string itemKey; if (useBands) { if (!_host.TryGetObjectIntProperty(itemId, StypeItemWorkmanship, out int itemWm) || itemWm <= 0) return 0; string? itemBand = cfg!.GetBandKey(itemMat, itemWm); if (itemBand == null) return 0; itemKey = $"{itemMat}|{itemBand}"; } else { itemKey = itemMat.ToString(); } int added = 0; foreach (WorldObject bag in _cache.GetDirectInventory(forceRefresh: true)) { uint bagId = unchecked((uint)bag.Id); if (bagId == itemId) continue; if (!IsSalvageBag(bag.Name)) continue; if (!IsBagUnderFull(bagId, bag.Name)) continue; if (!TryGetBagCombineKey(bagId, bag.Name, cfg, useBands, out string bagKey, out _)) continue; if (bagKey != itemKey) continue; if (_host.SalvagePanelAddItem(bagId)) { Log($"[Salvage] Combine-during-salvage: added bag {bag.Name} 0x{bagId:X8} ({added + 1})."); added++; } } return added; } private void BeginSalvaging(long now) { if (!_host.SalvagePanelExecute()) { Log($"[Salvage] SalvagePanelExecute failed for 0x{_currentItemId:X8} — re-queuing."); RequeueOrDrop(_currentItemId, "execute failed"); _currentItemId = 0; _phase = Phase.Idle; return; } _phaseReadyAt = now + _settings.SalvageSalvageDelayMs; _phase = Phase.Salvaging; } private void BeginWaitingForResult(long now) { int resultDelay = _firstResultCycle ? _settings.SalvageResultDelayFirstMs : _settings.SalvageResultDelayFastMs; _firstResultCycle = false; _phaseReadyAt = now + resultDelay; _waitingResultDeadline = now + resultDelay + ResultMaxWaitMs; _phase = Phase.WaitingForResult; } private void OnResultReady(long now) { // If the item we tried to salvage is STILL in the player's actual // inventory after the result delay, the salvage didn't consume it // (panel closed mid-execute, bot got busy, AC dropped the request, // etc.). Re-queue so we try again. // // We use GetDirectInventory(forceRefresh: true) — a live walk of the // player's containers — instead of _cache[id] because salvage-consumed // items don't reliably trigger OnDeleteObject in the cache, leading to // false positives where successfully-salvaged items get re-queued. uint itemId = _currentItemId; bool itemStillPresent = itemId != 0 && IsItemInDirectInventory(itemId); _currentItemId = 0; _phase = Phase.Idle; if (itemStillPresent) { Log($"[Salvage] Item 0x{itemId:X8} still in inventory after salvage cycle — re-queuing."); RequeueOrDrop(itemId, "item still present after result"); } else { // Successful salvage — clear retry counter for this id. _itemRetryCount.Remove(itemId); } // Always trigger a combine scan on the next idle tick when the queue // drains — both to consolidate any newly-merged bags and so combine // doesn't depend on the busyCount==0 gate of the periodic timer (which // an active combat macro rarely satisfies). if (_queue.Count == 0) _pendingCombineScan = true; } /// /// Re-queue an item that failed a salvage step. Counts retries per id and /// drops the item once it's failed MaxItemRetries times in a row, so a /// truly un-salvageable item doesn't trap the queue forever. /// private void RequeueOrDrop(uint itemId, string reason) { if (itemId == 0) return; int prior = _itemRetryCount.TryGetValue(itemId, out int n) ? n : 0; int next = prior + 1; if (next > MaxItemRetries) { _itemRetryCount.Remove(itemId); Log($"[Salvage] Giving up on 0x{itemId:X8} after {MaxItemRetries} attempts ({reason})."); NoteError($"gave up on 0x{itemId:X8} after {MaxItemRetries} attempts ({reason})"); // Trigger a combine scan if dropping this item left the queue empty. if (_queue.Count == 0) _pendingCombineScan = true; return; } _itemRetryCount[itemId] = next; _queue.Enqueue(itemId); Log($"[Salvage] Re-queued 0x{itemId:X8} ({reason}) — attempt {next}/{MaxItemRetries}."); } // ── Combine salvage bags ────────────────────────────────────────────────── private void BeginCombineSalvage(long now) { if (_cache == null) return; RynthCore.Loot.SalvageCombineSettings? cfg = CombineConfigProvider?.Invoke(); bool useBands = cfg != null && cfg.Enabled; // Group under-full bags by MaterialType (and Workmanship band, if a // SalvageCombine config is loaded and enabled). Bags at 100/100 are // skipped (already full); singleton groups are skipped (nothing to merge). // forceRefresh: true — startup combines work because the engine's replay // freshly populates the cache, but during a session the snapshot drifts // and forceRefresh:false returns yesterday's inventory. Always walk live. var byKey = new Dictionary>(StringComparer.Ordinal); var inv = _cache.GetDirectInventory(forceRefresh: true); int scannedItems = inv.Count; int salvageBagCount = 0; int underFullCount = 0; int rejMaterialUnknown = 0; int rejWmUnread = 0; foreach (WorldObject item in inv) { if (!IsSalvageBag(item.Name)) continue; salvageBagCount++; uint id = unchecked((uint)item.Id); if (!IsBagUnderFull(id, item.Name)) continue; underFullCount++; if (!TryGetBagCombineKey(id, item.Name, cfg, useBands, out string key, out string diag)) { rejMaterialUnknown++; continue; } if (diag == "workmanship-unread") rejWmUnread++; if (!byKey.TryGetValue(key, out var list)) { list = new List(); byKey[key] = list; } list.Add(id); } _combineGroups = new List>(); int eligibleBags = 0; foreach (var kv in byKey) { eligibleBags += kv.Value.Count; if (kv.Value.Count >= 2) _combineGroups.Add(kv.Value); } if (_combineGroups.Count == 0) { _combineGroups = null; Log($"[Salvage] Combine sweep: scanned {scannedItems} inv items, {salvageBagCount} salvage bag(s), {underFullCount} under-full, {eligibleBags} mat-eligible, rej(mat?={rejMaterialUnknown},wm?={rejWmUnread}), 0 mergeable groups."); return; } Log($"[Salvage] Combine sweep: scanned {scannedItems} inv items, {salvageBagCount} salvage bag(s), {underFullCount} under-full, rej(mat?={rejMaterialUnknown},wm?={rejWmUnread}) → {_combineGroups.Count} mergeable group(s)."); _combineGroupIdx = 0; _combineAddIdx = 0; _combinePhase = CombinePhase.None; _combinePhaseReadyAt = now; _phase = Phase.CombiningSalvage; } private void TickCombiningSalvage(long now) { if (_combineGroups == null) { _phase = Phase.Idle; return; } if (_combineGroupIdx >= _combineGroups.Count) { _combineGroups = null; _combinePhase = CombinePhase.None; _phase = Phase.Idle; return; } if (now < _combinePhaseReadyAt) return; var group = _combineGroups[_combineGroupIdx]; switch (_combinePhase) { case CombinePhase.None: { uint ust = FindUst(); if (ust == 0) { Log("[Salvage] Combine: no UST available — aborting combine cycle."); NoteError("combine: no UST in inventory"); _combineGroups = null; _phase = Phase.Idle; return; } if (!_host.UseObject(ust)) { _combineOpenAttempts++; if (_combineOpenAttempts < MaxCombineOpenAttempts) { Log($"[Salvage] Combine: UseObject(UST) failed — retrying this group in {RetryBackoffMs}ms (attempt {_combineOpenAttempts}/{MaxCombineOpenAttempts})."); _combinePhaseReadyAt = now + RetryBackoffMs; return; } Log($"[Salvage] Combine: UseObject(UST) failed {_combineOpenAttempts}x — skipping this group."); NoteError($"combine: UseObject(UST) failed {_combineOpenAttempts}x — group skipped"); _combineOpenAttempts = 0; _combineGroupIdx++; _combineAddIdx = 0; _combinePhaseReadyAt = now + RetryBackoffMs; return; } _combineOpenAttempts = 0; int openDelay = _panelEverOpened ? _settings.SalvageOpenDelayFastMs : _settings.SalvageOpenDelayFirstMs; _combinePhaseReadyAt = now + openDelay; _combinePhase = CombinePhase.OpeningPanel; break; } case CombinePhase.OpeningPanel: { _panelEverOpened = true; _combineAddIdx = 0; _combinePhase = CombinePhase.AddingBags; _combinePhaseReadyAt = now; break; } case CombinePhase.AddingBags: { if (_combineAddIdx < group.Count) { uint bagId = group[_combineAddIdx]; if (_host.SalvagePanelAddItem(bagId)) Log($"[Salvage] Combine: added bag 0x{bagId:X8} to panel ({_combineAddIdx + 1}/{group.Count})."); else Log($"[Salvage] Combine: SalvagePanelAddItem failed for 0x{bagId:X8}."); _combineAddIdx++; _combinePhaseReadyAt = now + _settings.SalvageAddDelayFastMs; } else { _combinePhase = CombinePhase.Salvaging; _combinePhaseReadyAt = now; } break; } case CombinePhase.Salvaging: { // Snapshot the bag IDs we expect the server to merge so the // verification pass in WaitingForResult can count survivors. _combineGroupSnapshot = new List(group); if (!_host.SalvagePanelExecute()) Log($"[Salvage] Combine group {_combineGroupIdx + 1}/{_combineGroups!.Count}: SalvagePanelExecute returned false (group of {group.Count} bag(s)) — verifying server-side outcome anyway."); _combinePhase = CombinePhase.WaitingForResult; _combinePhaseReadyAt = now + _settings.SalvageSalvageDelayMs + _settings.SalvageResultDelayFastMs; _waitingResultDeadline = _combinePhaseReadyAt + ResultMaxWaitMs; break; } case CombinePhase.WaitingForResult: { // Poll: if any snapshot bag is still in inventory and we're // under the deadline, wait. Server delete events for merged // bags arrive after the result delay on busy servers. if (now < _waitingResultDeadline && _combineGroupSnapshot != null && AnySnapshotBagStillInInventory(_combineGroupSnapshot)) { break; } VerifyCombineGroupResult(); _combineGroupIdx++; _combineAddIdx = 0; _combinePhase = CombinePhase.None; _combinePhaseReadyAt = now; break; } } } /// /// Compares the surviving bag ids against the snapshot taken before /// SalvagePanelExecute. Uses GetDirectInventory(forceRefresh: true) for /// ground truth — _cache[id] is unreliable for salvage-consumed bags /// because OnDeleteObject doesn't always fire on the merge path. /// /// Outcomes (M = input bags, S = survivors): /// S == M → no merge happened (server ignored Execute / panel was empty / etc.) /// S == 1 → clean merge into a single bag /// 1 < S < M → partial merge (overflow / mixed-band / next sweep can finish it) /// private void VerifyCombineGroupResult() { var snapshot = _combineGroupSnapshot; _combineGroupSnapshot = null; if (snapshot == null || snapshot.Count == 0 || _cache == null) return; var liveIds = SnapshotDirectInventoryIds(); int survivors = 0; foreach (uint id in snapshot) { if (liveIds.Contains(id)) survivors++; } int merged = snapshot.Count - survivors; int groupNum = _combineGroupIdx + 1; int totalGroups = _combineGroups?.Count ?? 0; if (survivors == snapshot.Count) { _combineGroupsFailed++; string ids = string.Join(", ", snapshot.ConvertAll(id => $"0x{id:X8}")); Log($"[Salvage] Combine group {groupNum}/{totalGroups}: NO MERGE — all {snapshot.Count} bag(s) still in inventory. Surviving ids: {ids}. Session: {_combineGroupsSucceeded} ok / {_combineGroupsFailed} failed, {_bagsMergedThisSession} bag(s) merged."); return; } _combineGroupsSucceeded++; _bagsMergedThisSession += merged; if (survivors <= 1) { Log($"[Salvage] Combine group {groupNum}/{totalGroups}: merged {snapshot.Count} bag(s) → {survivors} survivor (+{merged} consumed). Session: {_combineGroupsSucceeded} ok / {_combineGroupsFailed} failed, {_bagsMergedThisSession} bag(s) merged."); } else { Log($"[Salvage] Combine group {groupNum}/{totalGroups}: PARTIAL merge — {snapshot.Count} bag(s) → {survivors} survivors (+{merged} consumed). Remaining bag(s) will be picked up by next sweep. Session: {_combineGroupsSucceeded} ok / {_combineGroupsFailed} failed, {_bagsMergedThisSession} bag(s) merged."); } } /// /// True when a salvage bag is under-full (structure < max) and thus worth /// merging. The #92/#91 property reads are authoritative but fail-close off /// the AC main thread (P0-2 qualities gate) — which is ALWAYS the case from /// the plugin pump. The old code then "assumed under-full", so on this ACE /// server (bags are "Salvage (N)" where N is the FILL level — /// Player_Crafting.cs ~281, see TryGetSalvageBagMaterial) every FULL /// "Salvage (100)" looked mergeable forever → a combine sweep every 30s /// that re-merged already-full bags and interrupted vendors/gameplay. /// Fix: when the properties can't be read, trust the bag NAME's trailing /// "(N)" fill level (covers both "Iron Salvage (91)" and ACE "Salvage /// (100)"); only if there's no parseable fill do we treat the bag as full /// (skip) so an unreadable bag can never drive an endless sweep. /// private bool IsBagUnderFull(uint bagId, string? name) { if (_host.TryGetObjectIntProperty(bagId, StypeStructure, out int cur) && _host.TryGetObjectIntProperty(bagId, StypeMaxStructure, out int max)) return max <= 0 || cur < max; if (TryParseTrailingNumber(name, out int fill)) return fill < 100; Log($"[Salvage] IsBagUnderFull: Structure unreadable AND name '{name}' has no numeric fill — treating 0x{bagId:X8} as full (skip) so it can't drive an endless sweep."); return false; } /// /// Resolves a salvage bag's material id from MaterialType(#131) — the only /// reliable source. The previous "parse trailing (NN) as material" fallback /// was WRONG on ACE: ACE names bags "Salvage ({Structure})" /// (Player_Crafting.cs ~line 281) — the number is the bag's FILL LEVEL, not /// its material — so the fallback scattered same-material bags across /// different bogus keys and they never combined. When the property can't be /// read we skip the bag for this sweep; the next sweep picks it up once the /// client has the bag's material cached. /// private bool TryGetSalvageBagMaterial(uint bagId, string? name, out int material) { material = 0; if (_host.TryGetObjectIntProperty(bagId, StypeMaterialType, out int mat) && mat > 0) { material = mat; return true; } return false; } /// /// Resolves the combine grouping key for a salvage BAG. /// /// ACE's server merges bags by MaterialType + under-full only /// (Player_Crafting.GetSalvageBag) — workmanship is never a server-side /// merge criterion. Banding is a client-side user preference to keep /// different-workmanship salvage in separate bags. A bag's int /// ItemWorkmanship(#105) is a cumulative SUM (TryAddSalvage), so the band /// must be derived from the AVERAGE: #105 / NumItemsInMaterial(#170). /// /// When workmanship can't be read we fall back to a "{mat}|?" key instead /// of excluding the bag — excluding every bag is exactly the original /// "never combines" bug. Same-material unknown-band bags then still merge /// with each other, which is server-safe (the server ignores workmanship). /// Returns false only when the MATERIAL itself is unknown (can't group at /// all); carries a short reason for logging. /// private bool TryGetBagCombineKey(uint bagId, string? name, RynthCore.Loot.SalvageCombineSettings? cfg, bool useBands, out string key, out string diag) { key = string.Empty; diag = string.Empty; if (!TryGetSalvageBagMaterial(bagId, name, out int mat)) { diag = "material-unknown"; return false; } if (!useBands) { key = mat.ToString(); return true; } if (TryGetBagAvgWorkmanship(bagId, out int avgWm)) { string? band = cfg!.GetBandKey(mat, avgWm); if (band != null) { key = $"{mat}|{band}"; return true; } // avg falls in a gap between configured bands — keep it separate by // exact average so identical-average bags still merge together. diag = $"avgWm {avgWm} outside bands"; key = $"{mat}|wm{avgWm}"; return true; } diag = "workmanship-unread"; key = $"{mat}|?"; return true; } /// /// Average workmanship of a salvage bag = ItemWorkmanship(#105, a cumulative /// sum) / NumItemsInMaterial(#170). Integer floor — band ranges are integer, /// so flooring is exact for grouping (bags with the same average land in the /// same band). Returns false if either property is unreadable or the bag is /// empty/fresh (#170 == 0), in which case the caller treats the band as /// unknown rather than excluding the bag. /// private bool TryGetBagAvgWorkmanship(uint bagId, out int avgWm) { avgWm = 0; if (!_host.TryGetObjectIntProperty(bagId, StypeItemWorkmanship, out int sum) || sum <= 0) return false; if (!_host.TryGetObjectIntProperty(bagId, StypeNumItemsInMaterial, out int n) || n <= 0) return false; avgWm = sum / n; if (avgWm < 1) avgWm = 1; return true; } // ── Helpers ─────────────────────────────────────────────────────────────── /// /// True if appears in a fresh walk of the player's /// inventory containers. Ground truth for "did the server actually destroy /// this item" — the cache's _byId can hold stale entries for salvage- /// consumed items because OnDeleteObject doesn't fire on every merge path. /// private bool IsItemInDirectInventory(uint id) { if (_cache == null) return false; var inv = _cache.GetDirectInventory(forceRefresh: true); foreach (var item in inv) { if (unchecked((uint)item.Id) == id) return true; } return false; } /// /// Snapshots the ids currently in the player's direct inventory as a /// HashSet for O(1) survivor counting. /// private HashSet SnapshotDirectInventoryIds() { var set = new HashSet(); if (_cache == null) return set; foreach (var item in _cache.GetDirectInventory(forceRefresh: true)) set.Add(unchecked((uint)item.Id)); return set; } /// /// True if any of 's ids are still in the /// player's direct inventory. Used by combine WaitingForResult polling. /// private bool AnySnapshotBagStillInInventory(List snapshot) { var liveIds = SnapshotDirectInventoryIds(); foreach (uint id in snapshot) { if (liveIds.Contains(id)) return true; } return false; } // Canonical UST weenie class id. Same for every UST instance on every // character and every server (the WCID is part of the weenie definition, // not the per-instance GUID). Most reliable signal we have. private const uint UstWcid = 20646; private uint FindUst() { if (_cache == null) return 0; // Pass 1 — WCID match. Universal: every UST shares weenie class 20646 // so this works on every server / variant / character regardless of // name, ItemType classification, or cache state. if (_host.HasGetObjectWcid) { foreach (var item in _cache.AllKnownObjects()) { if (!IsCarriedByPlayer(item)) continue; if (!_host.TryGetObjectWcid(unchecked((uint)item.Id), out uint wcid)) continue; if (wcid == UstWcid) return unchecked((uint)item.Id); } } // Pass 2 — type-based via the cached ObjectClass. Same intent as the // WCID pass but reads the cached classification (ItemType TinkeringTool // bit). Catches USTs whose WCID lookup hasn't been bound on the host. foreach (var item in _cache.AllKnownObjects()) { if (item.ObjectClass != AcObjectClass.Ust) continue; if (!IsCarriedByPlayer(item)) continue; return unchecked((uint)item.Id); } // Pass 3 — name-based fallback. Some items get cached before their // ItemType is read; the cache stays AcObjectClass.Unknown until then. // The name path catches those. foreach (WorldObject item in _cache.GetDirectInventory(forceRefresh: false)) { if (IsUst(item.Name)) return unchecked((uint)item.Id); } // Pass 4 — same name fallback after a forced refresh. var fresh = _cache.GetDirectInventory(forceRefresh: true); foreach (WorldObject item in fresh) { if (IsUst(item.Name)) return unchecked((uint)item.Id); } // Pass 5 — WCID retry over the freshly-walked direct inventory in case // a UST only just appeared in the cache via the forced refresh. if (_host.HasGetObjectWcid) { foreach (var item in fresh) { if (!_host.TryGetObjectWcid(unchecked((uint)item.Id), out uint wcid)) continue; if (wcid == UstWcid) return unchecked((uint)item.Id); } } // Diagnostic on miss — sample what's in inventory so we can see // whether the UST really isn't there or just has an unexpected name. int shown = 0; var names = new List(); foreach (WorldObject item in fresh) { if (string.IsNullOrEmpty(item.Name)) continue; names.Add(item.Name); if (++shown >= 40) break; } Log($"[Salvage] UST search miss. {fresh.Count} item(s) scanned. Sample: {string.Join(", ", names)}"); return 0; } /// /// True when the item lives in the player's pack (or one of the player's /// side-packs). Skips USTs lying in nearby corpses or another player's pack. /// private bool IsCarriedByPlayer(WorldObject item) { if (_cache == null) return false; uint playerId = _host.GetPlayerId(); // Fail closed when the player id isn't readable yet — matches every other // playerId==0 guard in the plugin (InventoryManager:94, WorldObjectCache:977, // FindPackFor). Returning true here counted every scanned object as ours. if (playerId == 0) return false; int pid = unchecked((int)playerId); if (item.Wielder != 0 && item.Wielder != pid) return false; if (item.Container == pid) return true; // Container==0 means "not in any pack" — that's a wielded item (ours only if // we're the wielder) or an item lying on the ground. It used to return true // for both, so ground USTs read as carried. 2026-06-03 audit P2. if (item.Container == 0) return item.Wielder == pid; var owner = _cache[item.Container]; if (owner == null) return false; if (owner.ObjectClass == AcObjectClass.Corpse) return false; return owner.Wielder == pid || owner.Container == pid; } private static bool IsUst(string? name) { if (string.IsNullOrEmpty(name)) return false; // UST names carry "Ust" as its own word (e.g. "Salvaging Ust", "Aged Legendary // Salvaging Ust", "Sturdy Iron Salvaging Ust"). A bare Contains also matched // "Just"/"Robust"/"Lustrous" (2026-06-03 audit P2); a word match keeps working // if a name ever carries a suffix, which EndsWith would not. // Exclude actual salvage bags — the "Salvage (Material)" format, via IsSalvageBag. return HasWordUst(name) && !IsSalvageBag(name); } /// True when "Ust" appears as a whole word (letter/digit boundaries). private static bool HasWordUst(string name) { for (int i = 0; i + 3 <= name.Length; i++) { if (!(name[i] is 'U' or 'u') || !(name[i + 1] is 'S' or 's') || !(name[i + 2] is 'T' or 't')) continue; if (i > 0 && char.IsLetterOrDigit(name[i - 1])) continue; if (i + 3 < name.Length && char.IsLetterOrDigit(name[i + 3])) continue; return true; } return false; } /// /// Parses a trailing "(NN)" group from a salvage-bag name (e.g. /// "Gold Salvage (91)" → 91). Returns false if the name has no trailing /// integer in parentheses. /// private static bool TryParseTrailingNumber(string? name, out int value) { value = 0; if (string.IsNullOrEmpty(name)) return false; int close = name.LastIndexOf(')'); if (close <= 0 || close != name.Length - 1) return false; int open = name.LastIndexOf('(', close - 1); if (open < 0) return false; string inside = name.Substring(open + 1, close - open - 1); return int.TryParse(inside, out value); } private static bool IsSalvageBag(string? name) { if (string.IsNullOrEmpty(name)) return false; // Two known formats observed across servers/emulators: // "Salvage (Gold)" — retail-style, material in parens // "Gold Salvage (91)" — emulator style, fullness in parens // Both contain "Salvage (" as a substring; "Salvaging Ust" doesn't. return name.Contains("Salvage (", StringComparison.OrdinalIgnoreCase); } private void Log(string message) => _host.Log(message); private void NoteError(string what) { _lastError = what; _lastErrorAt = NowMs; } /// /// One-shot view of the salvage FSM. Salvage had no snapshot (Combat/Buff/Meta /// did), so a wedged panel cycle meant reading the log backwards to work out /// which phase it died in. Read-only; safe from the UI or a chat command. /// public SalvageStateSnapshot GetStateSnapshot() { long now = NowMs; return new SalvageStateSnapshot { HasPanelApi = _host.HasSalvagePanel && _host.HasUseObject, EnableCombine = _settings.EnableCombineSalvage, Phase = _phase.ToString(), PhaseReadyInMs = Math.Max(0, _phaseReadyAt - now), QueueCount = _queue.Count, CurrentItemId = _currentItemId, CurrentUstId = _currentUstId, PanelEverOpened = _panelEverOpened, PendingCombineScan = _pendingCombineScan, RetryTrackedItems = _itemRetryCount.Count, RetryBackoffInMs = Math.Max(0, _idleRetryReadyAt - now), CombinePhase = _combinePhase.ToString(), CombineGroupIdx = _combineGroupIdx, CombineGroupCount = _combineGroups?.Count ?? 0, CombineAddIdx = _combineAddIdx, CombineOpenAttempts = _combineOpenAttempts, MsSinceCombineSweep = _lastCombineSweepAt == 0 ? -1 : now - _lastCombineSweepAt, GroupsSucceeded = _combineGroupsSucceeded, GroupsFailed = _combineGroupsFailed, BagsMerged = _bagsMergedThisSession, LastError = _lastError, MsSinceLastError = _lastErrorAt == 0 ? -1 : now - _lastErrorAt, }; } public struct SalvageStateSnapshot { public bool HasPanelApi; public bool EnableCombine; public string Phase; public long PhaseReadyInMs; public int QueueCount; public uint CurrentItemId; public uint CurrentUstId; public bool PanelEverOpened; public bool PendingCombineScan; public int RetryTrackedItems; public long RetryBackoffInMs; public string CombinePhase; public int CombineGroupIdx; public int CombineGroupCount; public int CombineAddIdx; public int CombineOpenAttempts; public long MsSinceCombineSweep; public int GroupsSucceeded; public int GroupsFailed; public int BagsMerged; public string LastError; public long MsSinceLastError; } }