export const INVENTORY_SLOTS = 32; export const EQUIPMENT_SLOTS = Object.freeze(["head", "chest", "legs", "boots", "weapon", "offhand"]); import { attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins } from "./origin.js"; import { stackRulesFor } from "./stackRules.js"; import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js"; /** Stack counts can exceed 32-bit range (coin stacks up to 999B). */ export function stackQuantity (value) { const n = Number(value); if (!Number.isFinite(n) || n <= 0) { return 0; } const q = Math.floor(n); return Number.isSafeInteger(q) ? q : 0; } export function emptySlots (count = INVENTORY_SLOTS) { return Array.from({ length: count }, () => null); } export function emptyEquipment () { const slots = {}; for (const slot of EQUIPMENT_SLOTS) { slots[slot] = null; } return { slots }; } export function cloneStack (stack) { return stack ? structuredClone(stack) : null; } /** One item from a stack, preserving a single origin slice (for equip). */ export function singleItemFromStack (stack) { if (!stack) { return null; } const split = splitOrigins(normalizeOrigins(stack), 1); return { itemId: stack.itemId, quantity: 1, instance: stack.instance ? cloneStack(stack.instance) : null, origins: split.taken }; } export function stacksMatch (left, right, definition, { inVault = false } = {}) { if (!left || !right || left.itemId !== right.itemId) { return false; } const rules = stackRulesFor(definition, { inVault }); if (rules.uniqueInstance) { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); } return rules.stackable; } function stackPayload (stack, quantity, origins) { return { itemId: stack.itemId, quantity, instance: stack.instance ?? null, origins: origins.map((entry) => ({ origin: entry.origin ?? null, quantity: stackQuantity(entry.quantity) })).filter((entry) => entry.quantity > 0) }; } export function insertStack (slots, stack, definition, options = {}) { if (!stack || stack.quantity <= 0) { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; } const rules = stackRulesFor(definition, options); const next = slots.map(cloneStack); let remaining = stackQuantity(stack.quantity); let pendingOrigins = normalizeOrigins(stack); if (rules.stackable && !rules.uniqueInstance) { for (const slot of next) { if (!slot || slot.itemId !== stack.itemId) { continue; } if (slot.instance != null || stack.instance != null) { continue; } const space = rules.maxStackSize - stackQuantity(slot.quantity); if (space <= 0) { continue; } const add = Math.min(space, remaining); const split = splitOrigins(pendingOrigins, add); slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken); slot.quantity = stackQuantity(slot.quantity) + add; delete slot.origin; pendingOrigins = split.remain; remaining -= add; if (remaining === 0) { return { ok: true, slots: next, remainder: 0 }; } } } for (let i = 0; i < next.length; i++) { if (next[i]) { continue; } const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize; const amount = rules.stackable && !rules.uniqueInstance ? Math.min(remaining, cap) : 1; const split = splitOrigins(pendingOrigins, amount); next[i] = stackPayload(stack, amount, split.taken); pendingOrigins = split.remain; remaining -= amount; if (remaining === 0) { return { ok: true, slots: next, remainder: 0 }; } if (!rules.stackable || rules.uniqueInstance) { break; } } return { ok: false, slots, remainder: remaining }; } export function takeFromSlot (slots, slotIndex, quantity = null) { const next = slots.map(cloneStack); const slot = next[slotIndex]; if (!slot) { return { ok: false, slots, taken: null }; } const maxQty = stackQuantity(slot.quantity); const amount = quantity == null ? maxQty : Math.min(maxQty, Math.max(1, stackQuantity(quantity))); if (amount <= 0) { return { ok: false, slots, taken: null }; } const split = splitOrigins(normalizeOrigins(slot), amount); const taken = stackPayload(slot, amount, split.taken); if (amount >= maxQty) { next[slotIndex] = null; } else { slot.quantity = maxQty - amount; slot.origins = split.remain; delete slot.origin; } return { ok: true, slots: next, taken }; } /** Like insertStack, but grows the slot array when capacity runs out (vault). */ export function insertStackGrowable (slots, stack, definition) { if (!stack || stack.quantity <= 0) { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; } let next = (slots ?? []).map(cloneStack); let remaining = stackQuantity(stack.quantity); let pendingOrigins = normalizeOrigins(stack); const rules = stackRulesFor(definition, { inVault: true }); if (rules.stackable && !rules.uniqueInstance) { for (const slot of next) { if (!slot || slot.itemId !== stack.itemId || slot.instance != null || stack.instance != null) { continue; } const space = rules.maxStackSize - stackQuantity(slot.quantity); if (space <= 0) { continue; } const add = Math.min(space, remaining); const split = splitOrigins(pendingOrigins, add); slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken); slot.quantity = stackQuantity(slot.quantity) + add; delete slot.origin; pendingOrigins = split.remain; remaining -= add; if (remaining === 0) { return { ok: true, slots: next, remainder: 0 }; } } } while (remaining > 0) { const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize; const amount = rules.stackable && !rules.uniqueInstance ? Math.min(remaining, cap) : 1; const split = splitOrigins(pendingOrigins, amount); next.push(stackPayload(stack, amount, split.taken)); pendingOrigins = split.remain; remaining -= amount; if (!rules.stackable || rules.uniqueInstance) { break; } } return { ok: remaining === 0, slots: next, remainder: remaining }; } /** Take `quantity` of matching goods from vault slots (any slots). */ export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null }) { let remaining = Math.max(0, stackQuantity(quantity)); if (!remaining) { return { ok: false, slots, taken: null }; } const next = (slots ?? []).map(cloneStack); const takenOrigins = []; for (let i = 0; i < next.length && remaining > 0; i++) { const slot = next[i]; if (!slot || slot.itemId !== itemId) { continue; } if (instance != null) { if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance)) { continue; } } const amount = Math.min(stackQuantity(slot.quantity), remaining); const split = splitOrigins(normalizeOrigins(slot), amount); takenOrigins.push(...split.taken); if (amount >= stackQuantity(slot.quantity)) { next[i] = null; } else { slot.quantity = stackQuantity(slot.quantity) - amount; slot.origins = split.remain; delete slot.origin; } remaining -= amount; } const compact = next.filter((slot) => slot); if (remaining > 0) { return { ok: false, slots, taken: null }; } return { ok: true, slots: compact, taken: attachOrigins({ itemId, quantity: stackQuantity(quantity), instance: instance ?? null, origins: mergeOriginLists([], takenOrigins) }) }; } export function countItemInSlots (slots, itemId) { let total = 0; for (const slot of slots ?? []) { if (slot?.itemId === itemId) { total += stackQuantity(slot.quantity); } } return total; } export function countCoinsInSlots (slots) { return countItemInSlots(slots, ItemId.coins); } /** Add coin stacks, splitting at max stack size (999B). */ export function addCoinsToSlots (slots, amount, { growable = false } = {}) { const def = itemDefinition(ItemId.coins); if (!def || amount <= 0) { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; } let next = (slots ?? []).map(cloneStack); if (!growable && next.length < INVENTORY_SLOTS) { const padded = emptySlots(); for (let i = 0; i < next.length; i++) { padded[i] = next[i]; } next = padded; } let remaining = stackQuantity(amount); const insert = growable ? insertStackGrowable : insertStack; while (remaining > 0) { const chunk = Math.min(remaining, def.maxStackSize ?? 99); const result = insert(next, { itemId: ItemId.coins, quantity: chunk }, def); next = result.slots; const placed = chunk - (result.remainder ?? 0); remaining -= placed; if (!result.ok || result.remainder > 0) { return { ok: false, slots: next, remainder: remaining }; } } return { ok: true, slots: next, remainder: 0 }; } /** Convert legacy currency counters into coin stacks. */ export function migrateBagCoins (bag) { let inventory = bag.inventory ?? emptySlots(); let vault = bag.vault ?? []; if (bag.currency > 0) { const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false }); inventory = added.slots; } if (bag.vaultCurrency > 0) { const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true }); vault = added.slots; } return { ...bag, inventory, vault, currency: 0, vaultCurrency: 0 }; } export function migrateInheritanceCoins (inheritance) { if (!inheritance?.currency) { return inheritance; } const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true }); return { ...inheritance, slots: added.slots, currency: 0 }; } /** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */ export function normalizeInventorySlots (slots) { return capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP); } export function capItemTotalInSlots (slots, itemId, cap) { const next = (slots ?? []).map(cloneStack); let total = countItemInSlots(next, itemId); if (total <= cap) { return next; } let toRemove = total - cap; for (let i = next.length - 1; i >= 0 && toRemove > 0; i--) { const slot = next[i]; if (!slot || slot.itemId !== itemId) { continue; } const beforeQty = stackQuantity(slot.quantity); const drop = Math.min(beforeQty, toRemove); const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop); slot.quantity = beforeQty - drop; slot.origins = remain; delete slot.origin; toRemove -= drop; if (slot.quantity <= 0) { next[i] = null; } } return next; } export function normalizeVault (raw) { if (Array.isArray(raw)) { return { slots: raw.map(cloneStack), reserved: [] }; } return { slots: (raw?.slots ?? []).map(cloneStack), reserved: (raw?.reserved ?? []).map(cloneStack) }; } export function serializeVault (vault) { const normalized = normalizeVault(vault); return { slots: publicSlots(normalized.slots), reserved: publicSlots(normalized.reserved) }; } export function publicSlots (slots) { return (slots ?? emptySlots()).map((slot) => { if (!slot) { return null; } const payload = attachOrigins(cloneStack(slot)); const next = { itemId: payload.itemId, quantity: payload.quantity, origins: payload.origins, instance: payload.instance ?? null }; // Cheque reservations keep chequeId so redeem can match the paper to vault goods. if (payload.chequeId != null) { next.chequeId = payload.chequeId; } return next; }); } export function publicEquipment (equipment) { const slots = {}; for (const slot of EQUIPMENT_SLOTS) { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; } return { slots }; }