export const INVENTORY_SLOTS = 32; export const EQUIPMENT_SLOTS = Object.freeze(["head", "chest", "legs", "boots", "weapon", "offhand"]); 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; } export function stacksMatch (left, right) { if (!left || !right) { return false; } if (left.itemId !== right.itemId) { return false; } return JSON.stringify(left.origin ?? null) === JSON.stringify(right.origin ?? null) && JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); } export function insertStack (slots, stack, definition) { if (!stack || stack.quantity <= 0) { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; } const next = slots.map(cloneStack); let remaining = stack.quantity; if (definition.stackable && !definition.uniqueInstance) { for (const slot of next) { if (!stacksMatch(slot, stack)) { continue; } const space = (definition.maxStackSize ?? 99) - slot.quantity; if (space <= 0) { continue; } const add = Math.min(space, remaining); slot.quantity += add; 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 amount = definition.stackable && !definition.uniqueInstance ? Math.min(remaining, definition.maxStackSize ?? 99) : 1; next[i] = { itemId: stack.itemId, quantity: amount, origin: stack.origin ?? null, instance: stack.instance ?? null }; remaining -= amount; if (remaining === 0) { return { ok: true, slots: next, remainder: 0 }; } if (!definition.stackable || definition.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 amount = quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, quantity | 0)); if (amount <= 0) { return { ok: false, slots, taken: null }; } const taken = { ...cloneStack(slot), quantity: amount }; if (amount >= slot.quantity) { next[slotIndex] = null; } else { slot.quantity -= amount; } return { ok: true, slots: next, taken }; } export function publicSlots (slots) { return (slots ?? emptySlots()).map((slot) => slot ? { itemId: slot.itemId, quantity: slot.quantity, origin: slot.origin ?? null, instance: slot.instance ?? null } : null); } export function publicEquipment (equipment) { const slots = {}; for (const slot of EQUIPMENT_SLOTS) { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; } return { slots }; }