Implement instant cache adjustment for item movements in inventory

This commit is contained in:
MayaTheShy
2026-03-15 22:59:58 -04:00
parent 8f24345a96
commit 8e50a79d71

View File

@@ -132,6 +132,66 @@ local activity = {
smelting = false, -- auto-smelt in progress
}
-------------------------------------------------
-- Instant cache adjustment (no scan needed)
-------------------------------------------------
--- Adjust cached counts for a single item move.
-- delta > 0 means items arrived in chestName;
-- delta < 0 means items left chestName.
local function adjustCache(itemName, chestName, delta)
if delta == 0 then return end
-- 1) catalogue: per-chest totals
local cat = cache.catalogue
if delta > 0 then
-- Items added to a chest
if not cat[itemName] then cat[itemName] = {} end
local found = false
for _, entry in ipairs(cat[itemName]) do
if entry.chest == chestName then
entry.total = entry.total + delta
found = true
break
end
end
if not found then
table.insert(cat[itemName], { chest = chestName, total = delta })
end
else
-- Items removed from a chest
if cat[itemName] then
for idx, entry in ipairs(cat[itemName]) do
if entry.chest == chestName then
entry.total = entry.total + delta -- delta is negative
if entry.total <= 0 then
table.remove(cat[itemName], idx)
end
break
end
end
-- Remove item from catalogue entirely if no sources left
if #cat[itemName] == 0 then
cat[itemName] = nil
end
end
end
-- 2) Rebuild itemList from catalogue (lightweight — just totals)
local itemList = {}
local grandTotal = 0
for name, sources in pairs(cat) do
local total = 0
for _, s in ipairs(sources) do total = total + s.total end
grandTotal = grandTotal + total
table.insert(itemList, { name = name, total = total })
end
table.sort(itemList, function(a, b) return a.total > b.total end)
cache.itemList = itemList
cache.grandTotal = grandTotal
end
-------------------------------------------------
-- Inventory helpers
-------------------------------------------------
@@ -1157,6 +1217,9 @@ local function sortBarrel()
local n = barrel.pushItems(entry.chest, slot)
if n and n > 0 then
moved = moved + n
adjustCache(item.name, entry.chest, n)
needsRedraw = true
smelterNeedsRedraw = true
print(string.format("[SORT] %s x%d -> %s", item.name, n, entry.chest))
end
if moved >= item.count then break end
@@ -1168,6 +1231,9 @@ local function sortBarrel()
local n = barrel.pushItems(chest, slot)
if n and n > 0 then
moved = moved + n
adjustCache(item.name, chest, n)
needsRedraw = true
smelterNeedsRedraw = true
print(string.format("[SORT] %s x%d -> %s", item.name, n, chest))
end
if moved >= item.count then break end
@@ -1402,6 +1468,9 @@ local function orderItem(itemName, amount)
local moved = chest.pushItems(DROPPER_NAME, slot, toMove)
if moved and moved > 0 then
remaining = remaining - moved
adjustCache(itemName, entry.chest, -moved)
needsRedraw = true
smelterNeedsRedraw = true
print(string.format("[ORDER] %s x%d from %s", itemName, moved, entry.chest))
end
if remaining <= 0 then break end