import { Component } from "../ecs/components.js"; import { syncPlayerHealth } from "../skills/service.js"; import { canEquipItem } from "../../../shared/equipment/stats.js"; import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; import { stackRulesFor } from "../../../shared/items/stackRules.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { ItemId, itemDefinition, itemSpriteNameForStack, itemDisplayName, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js"; import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicEquipment, publicSlots, takeFromSlot, takeMatchingFromSlots, countItemInSlots, cloneStack, singleItemFromStack, stackQuantity, consumeFillCharge, moveInventorySlot } from "../../../shared/items/inventory.js"; import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { randomUUID } from "node:crypto"; import { tileShoveTowardBlock } from "../simulation/tileInteract.js"; import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js"; import { ARROW_COATING_ARROWS_PER_USE } from "../../../shared/definitions/alchemy.js"; import { applyStatusEffect, emptyStatusEffects, StatusEffectType } from "../../../shared/statusEffects/rules.js"; import { attachOrigins, writtenOrigin, bankIssuedOrigin, normalizeOrigins, mergeOriginLists } from "../../../shared/items/origin.js"; import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js"; import { canCharacterPickupGroundItem } from "../../../shared/items/letters.js"; export function publicGroundItem (item) { const instance = item.stack?.instance ?? null; return { groundItemId: item.groundItemId, tileX: item.tileX, tileY: item.tileY, itemId: item.stack.itemId, quantity: item.stack.quantity, displayName: itemDisplayName(item.stack), sprite: itemSpriteNameForStack(item.stack), instance: instance && ( instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper" || instance.kind === "log" ) ? instance : null, expiresAt: item.expiresAt, droppedByCharacterId: item.droppedByCharacterId ?? null }; } export function bagView (ecs, handle) { const vault = normalizeVault(ecs.get(handle, Component.vault)); return { inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())), equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()), vault: publicSlots(vault.slots), vaultReserved: publicSlots(vault.reserved) }; } /** Remove all coin stacks from the bag for death drops. Anyone may pick them up. */ export function stripCarriedCoinsForDeath (world, characterId) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { return { stack: null, private: null }; } const handle = world.ecs.handleOf(entityId); if (handle == null) { return { stack: null, private: null }; } const inventory = ensureInventory(world.ecs, handle); let total = 0; let origins = []; const next = inventory.slots.map(cloneStack); for (let i = 0; i < next.length; i++) { const slot = next[i]; if (!slot || (slot.itemId | 0) !== ItemId.coins) { continue; } const qty = stackQuantity(slot.quantity); if (qty <= 0) { next[i] = null; continue; } total += qty; origins = mergeOriginLists(origins, normalizeOrigins(slot)); next[i] = null; } if (total <= 0) { return { stack: null, private: null }; } inventory.slots = next; return { stack: attachOrigins({ itemId: ItemId.coins, quantity: total, origins }), private: bagView(world.ecs, handle) }; } export function applyBagView (ecs, handle, bag) { const inventory = ensureInventory(ecs, handle); inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots())); const equipment = ensureEquipment(ecs, handle); const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment()); equipment.slots = nextEquip.slots; const vault = ensureVault(ecs, handle); const normalized = normalizeVault( bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault)) ? { slots: bag.vault, reserved: bag.vaultReserved } : bag.vault ); vault.slots = publicSlots(normalized.slots); vault.reserved = publicSlots(normalized.reserved); return bagView(ecs, handle); } export function handleItemCommand (world, sessionId, command, now) { switch (command.type) { case "drop-item": return dropItem(world, sessionId, command, now); case "pickup-item": return pickupItem(world, sessionId, command); case "equip-item": return equipItem(world, sessionId, command); case "unequip-item": return unequipItem(world, sessionId, command); case "move-inventory-slot": return moveInventorySlotCommand(world, sessionId, command); case "open-bank": return openBank(world, sessionId, command); case "bank-deposit": return bankMove(world, sessionId, command, "inventory", "vault"); case "bank-withdraw": return bankMove(world, sessionId, command, "vault", "inventory"); case "get-blank-cheques": return getBlankCheques(world, sessionId, command); case "return-blank-cheques": return returnBlankCheques(world, sessionId, command); case "write-cheque": return writeCheque(world, sessionId, command); case "redeem-cheque": return redeemCheque(world, sessionId, command); case "claim-inheritance": return claimInheritance(world, sessionId, command); case "write-letter": return writeLetter(world, sessionId, command); case "edit-letter": return editLetter(world, sessionId, command); case "open-letter": return openLetter(world, sessionId, command); case "eat-item": return eatItem(world, sessionId, command); case "drink-item": return drinkItem(world, sessionId, command); case "tip-arrows": return tipArrows(world, sessionId, command); default: return null; } } export function expireGroundItems (world, now) { const events = []; for (const item of [...world.groundItems.values()]) { if (item.expiresAt > now) { continue; } // Destroyed paper frees reserved vault goods; a live ground cheque keeps them reserved. if (item.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque") { world.voidFilledCheque?.(item.stack); } removeGroundItem(world, item.groundItemId); events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); } return events; } export function groundItemsInChunk (world, chunkX, chunkY) { return [...world.groundItems.values()] .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY) .map(publicGroundItem); } export function groundItemsInRegion (world, regionX, regionY, tileToRegion) { return [...world.groundItems.values()].filter((item) => tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY ); } export function addGroundItem (world, item) { world.groundItems.set(item.groundItemId, item); const key = tileKey(item.tileX, item.tileY); if (!world.groundByTile.has(key)) { world.groundByTile.set(key, new Set()); } world.groundByTile.get(key).add(item.groundItemId); } export function removeGroundItem (world, groundItemId) { const item = world.groundItems.get(groundItemId); if (!item) { return null; } world.groundItems.delete(groundItemId); const key = tileKey(item.tileX, item.tileY); world.groundByTile.get(key)?.delete(groundItemId); return item; } export function replaceGroundItems (world, items) { world.groundItems.clear(); world.groundByTile.clear(); for (const item of items ?? []) { addGroundItem(world, item); } } export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion) { for (const item of [...world.groundItems.values()]) { if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY) { removeGroundItem(world, item.groundItemId); } } for (const item of items ?? []) { addGroundItem(world, item); } } function dropItem (world, sessionId, command, now) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null); if (!taken.ok) { throw userError("That inventory slot is empty."); } inventory.slots = taken.slots; const position = world.ecs.get(handle, Component.position); const item = { groundItemId: command.groundItemId, tileX: position.tileX, tileY: position.tileY, stack: taken.taken, droppedAt: now, expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000), source: "player-drop", droppedByCharacterId: command.characterId }; addGroundItem(world, item); return { events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }], private: bagView(world.ecs, handle) }; } function pickupItem (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const item = world.groundItems.get(command.groundItemId); if (!item) { throw userError("That item is no longer on the ground."); } if (!canCharacterPickupGroundItem(item, command.characterId)) { throw userError("That item is no longer on the ground."); } const position = world.ecs.get(handle, Component.position); if (position.tileX !== item.tileX || position.tileY !== item.tileY) { throw userError("Stand on the item to pick it up."); } const def = itemDefinition(item.stack.itemId); if (!def) { throw userError("Unknown item."); } const inventory = ensureInventory(world.ecs, handle); let stackToAdd = item.stack; if (item.stack.itemId === ItemId.blankCheque) { const have = countItemInSlots(inventory.slots, ItemId.blankCheque); const room = BLANK_CHEQUE_CARRY_CAP - have; if (room <= 0) { throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); } const takeQty = Math.min(item.stack.quantity, room); stackToAdd = { ...item.stack, quantity: takeQty }; } const inserted = insertStack(inventory.slots, stackToAdd, def); if (!inserted.ok) { throw userError("Your inventory cannot hold that."); } inventory.slots = inserted.slots; const events = []; if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity) { item.stack.quantity -= stackToAdd.quantity; events.push({ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }); } else { removeGroundItem(world, item.groundItemId); events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); } return { events, private: bagView(world.ecs, handle) }; } function equipItem (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const equipment = ensureEquipment(world.ecs, handle); const slotIndex = command.slotIndex | 0; const source = inventory.slots[slotIndex]; if (!source || stackQuantity(source.quantity) <= 0) { throw userError("That inventory slot is empty."); } const def = itemDefinition(source.itemId); const slot = def?.equipment?.slot; if (!slot) { throw userError("That item cannot be equipped."); } const skills = world.ecs.get(handle, Component.skills); const equipCheck = canEquipItem(skills, def); if (!equipCheck.ok) { throw userError(equipCheck.reason); } const isArrowAmmo = def.equipment?.kind === EquipmentKind.arrowAmmo; const taken = takeFromSlot(inventory.slots, slotIndex, isArrowAmmo ? null : 1); if (!taken.ok || stackQuantity(taken.taken?.quantity) <= 0) { throw userError("That inventory slot is empty."); } if (taken.taken.itemId === ItemId.coins) { inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots; throw userError("Coins cannot be equipped."); } if (isArrowAmmo) { let slots = taken.slots; const previous = equipment.slots[slot]; if (previous) { const previousDef = itemDefinition(previous.itemId); if (previous.itemId === taken.taken.itemId) { const rules = stackRulesFor(def); const space = rules.maxStackSize - stackQuantity(previous.quantity); const add = Math.min(space, stackQuantity(taken.taken.quantity)); if (add <= 0) { inventory.slots = insertStack(slots, taken.taken, def).slots; throw userError("Your arrow stack is full."); } previous.quantity = stackQuantity(previous.quantity) + add; const leftover = stackQuantity(taken.taken.quantity) - add; if (leftover > 0) { const back = insertStack(slots, { ...taken.taken, quantity: leftover }, def); if (!back.ok) { previous.quantity = stackQuantity(previous.quantity) - add; inventory.slots = insertStack(slots, taken.taken, def).slots; throw userError("No inventory space for leftover arrows."); } slots = back.slots; } inventory.slots = slots; return { events: [], private: bagView(world.ecs, handle), appearanceChanged: false }; } const back = insertStack(slots, previous, previousDef); if (!back.ok) { inventory.slots = insertStack(slots, taken.taken, def).slots; throw userError("No inventory space to unequip the current item."); } slots = back.slots; } inventory.slots = slots; equipment.slots[slot] = taken.taken; syncPlayerHealth(world.ecs, handle); return { events: [], private: bagView(world.ecs, handle), appearanceChanged: false, healthChanged: true }; } const toEquip = singleItemFromStack(taken.taken); const previous = equipment.slots[slot]; if (previous) { const previousSingle = singleItemFromStack(previous); const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId)); if (!back.ok) { inventory.slots = insertStack(inventory.slots, toEquip, def).slots; throw userError("No inventory space to unequip the current item."); } inventory.slots = back.slots; } else { inventory.slots = taken.slots; } equipment.slots[slot] = toEquip; syncPlayerHealth(world.ecs, handle); return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true, healthChanged: true }; } function unequipItem (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const equipment = ensureEquipment(world.ecs, handle); const worn = equipment.slots[command.equipSlot]; if (!worn) { throw userError("Nothing is equipped there."); } const def = itemDefinition(worn.itemId); const toStore = def?.equipment?.kind === EquipmentKind.arrowAmmo ? cloneStack(worn) : singleItemFromStack(worn); const inserted = insertStack(inventory.slots, toStore, def); if (!inserted.ok) { throw userError("Your inventory cannot hold that."); } inventory.slots = inserted.slots; equipment.slots[command.equipSlot] = null; syncPlayerHealth(world.ecs, handle); const appearanceChanged = def?.equipment?.kind !== EquipmentKind.arrowAmmo; return { events: [], private: bagView(world.ecs, handle), appearanceChanged, healthChanged: true }; } function moveInventorySlotCommand (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const inventory = ensureInventory(world.ecs, handle); const moved = moveInventorySlot( inventory.slots, command.fromSlotIndex, command.toSlotIndex ); if (!moved.ok) { throw userError(moved.reason ?? "Could not move that item."); } if (moved.changed) { inventory.slots = moved.slots; } return { events: [], private: bagView(world.ecs, handle) }; } function eatItem (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); syncPlayerHealth(world.ecs, handle); const inventory = ensureInventory(world.ecs, handle); const health = world.ecs.get(handle, Component.health); if (!health) { throw userError("You cannot eat right now."); } if ((health.current | 0) >= (health.max | 0)) { throw userError("You are already at full health."); } const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || stackQuantity(slot.quantity) <= 0) { throw userError("That inventory slot is empty."); } const def = itemDefinition(slot.itemId); const healing = def?.healing ?? 0; if (healing <= 0) { throw userError("That cannot be eaten."); } const taken = takeFromSlot(inventory.slots, slotIndex, 1); if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1) { throw userError("That inventory slot is empty."); } inventory.slots = taken.slots; health.current = Math.min(health.max | 0, (health.current | 0) + healing); let statusEffectsChanged = false; if (def?.eatStatusEffect) { let component = world.ecs.get(handle, Component.statusEffects); if (!component) { component = world.ecs.add(handle, Component.statusEffects, emptyStatusEffects()); } applyStatusEffect(component, def.eatStatusEffect, Date.now()); statusEffectsChanged = true; } return { events: [], private: bagView(world.ecs, handle), healthChanged: true, statusEffectsChanged }; } function drinkItem (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); syncPlayerHealth(world.ecs, handle); const inventory = ensureInventory(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.potion || slot.instance?.kind !== "potion") { throw userError("That is not a potion."); } const consumed = consumeFillCharge(inventory.slots, slotIndex, { kind: "potion", itemId: ItemId.potion, returnEmptyItemId: ItemId.glassBottle }); if (!consumed.ok) { if (consumed.reason === "space") { throw userError( "Need bag space to keep the partially used potion (or empty bottle)." ); } throw userError("That inventory slot is empty."); } inventory.slots = consumed.slots; const effectResult = applyPotionEffect(world.ecs, handle, resolvePotionEffect(consumed.instance)); return { events: effectResult.events ?? [], private: bagView(world.ecs, handle), healthChanged: !!effectResult.healthChanged, appearanceChanged: !!effectResult.appearanceChanged, statusEffectsChanged: !!effectResult.statusEffectsChanged }; } /** * Apply an arrow-coating potion to untipped arrows in the bag. * Consumes one coating fill charge; tips up to ARROW_COATING_ARROWS_PER_USE arrows. */ function tipArrows (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const coatingSlotIndex = command.coatingSlotIndex | 0; const arrowSlotIndex = command.arrowSlotIndex | 0; const wantQty = Math.max(1, command.quantity | 0 || 1); const coating = inventory.slots[coatingSlotIndex]; if (!coating || coating.itemId !== ItemId.potion || coating.instance?.kind !== "potion") { throw userError("That is not a coating."); } const effect = coating.instance.effect ?? resolvePotionEffect(coating.instance); if (effect?.type !== "arrow-coating" || !effect.element) { throw userError("That brew cannot tip arrows."); } const element = effect.element; const arrowSlot = inventory.slots[arrowSlotIndex]; if (!arrowSlot) { throw userError("Select arrows to tip."); } const arrowDef = itemDefinition(arrowSlot.itemId); if (arrowDef?.equipment?.kind !== EquipmentKind.arrowAmmo) { throw userError("That is not an arrow."); } if (arrowSlot.instance?.kind === "tipped-arrow") { throw userError("Those arrows are already tipped."); } const available = stackQuantity(arrowSlot.quantity); const tipQty = Math.min(wantQty, available, ARROW_COATING_ARROWS_PER_USE); if (tipQty <= 0) { throw userError("No arrows to tip."); } const taken = takeFromSlot(inventory.slots, arrowSlotIndex, tipQty); if (!taken.ok || !taken.taken) { throw userError("Could not take those arrows."); } inventory.slots = taken.slots; const tipped = attachOrigins({ itemId: arrowSlot.itemId, quantity: tipQty, instance: { kind: "tipped-arrow", element }, origins: taken.taken.origins ?? [] }); const inserted = insertStack(inventory.slots, tipped, itemDefinition(arrowSlot.itemId)); if (!inserted.ok || inserted.remainder > 0) { const refund = insertStack( inventory.slots, attachOrigins({ itemId: arrowSlot.itemId, quantity: tipQty, instance: null, origins: taken.taken.origins ?? [] }), arrowDef ); inventory.slots = refund.slots; throw userError("Need bag space for the tipped arrows."); } inventory.slots = inserted.slots; const consumed = consumeFillCharge(inventory.slots, coatingSlotIndex, { kind: "potion", itemId: ItemId.potion, returnEmptyItemId: ItemId.glassBottle }); if (!consumed.ok) { throw userError( consumed.reason === "space" ? "Need bag space to keep the partially used coating (or empty bottle)." : "That coating is gone." ); } inventory.slots = consumed.slots; return { events: [], private: bagView(world.ecs, handle) }; } function ensureStatusEffects (ecs, handle) { let component = ecs.get(handle, Component.statusEffects); if (!component) { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); } if (!Array.isArray(component.effects)) { component.effects = []; } return component; } function applyPotionEffect (ecs, handle, effect) { const result = { healthChanged: false, appearanceChanged: false, statusEffectsChanged: false, events: [] }; if (!effect || typeof effect !== "object") { return result; } const health = ecs.get(handle, Component.health); const type = effect.type; if (type === "arrow-coating") { return result; } if (type === "heal" && health) { const amount = Math.max(0, effect.amount | 0 || 0); health.current = Math.min(health.max | 0, (health.current | 0) + amount); result.healthChanged = true; return result; } if (type === "damage" && health) { const amount = Math.max(0, effect.amount | 0 || 0); health.current = Math.max(0, (health.current | 0) - amount); result.healthChanged = true; return result; } const timed = { [StatusEffectType.healthRegen]: true, [StatusEffectType.healthDrain]: true, [StatusEffectType.foodPoisoning]: true, [StatusEffectType.staminaRegen]: true, [StatusEffectType.strengthBonus]: true, [StatusEffectType.mindBonus]: true, [StatusEffectType.staminaDrain]: true, [StatusEffectType.glow]: true, [StatusEffectType.shrink]: true, [StatusEffectType.blind]: true }; if (!timed[type]) { return result; } const component = ensureStatusEffects(ecs, handle); applyStatusEffect(component, effect, Date.now()); result.statusEffectsChanged = true; if (type === StatusEffectType.glow || type === StatusEffectType.shrink) { result.appearanceChanged = true; } return result; } function openBank (world, sessionId, command) { const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId); const position = world.ecs.get(handle, Component.position); if (!nearBank(world, position.tileX, position.tileY)) { throw userError("Stand next to a bank."); } const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank); return { events: shove ? [shove] : [], private: bagView(world.ecs, handle), bank: true }; } function bankMove (world, sessionId, command, fromKey, toKey) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const inventory = ensureInventory(world.ecs, handle); const vault = ensureVault(world.ecs, handle); if (fromKey === "inventory" && toKey === "vault") { const slot = inventory.slots[command.slotIndex | 0]; if (slot?.itemId === ItemId.filledCheque) { return redeemCheque(world, sessionId, command); } } const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots; const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null); if (!taken.ok) { throw userError("That slot is empty."); } const def = itemDefinition(taken.taken.itemId); if (toKey === "vault") { const inserted = insertStackGrowable(vault.slots, taken.taken, def); inventory.slots = taken.slots; vault.slots = inserted.slots; } else { const inserted = insertStack(inventory.slots, taken.taken, def); if (!inserted.ok) { throw userError("Not enough space."); } vault.slots = taken.slots; inventory.slots = inserted.slots; } return { events: [], private: bagView(world.ecs, handle), bank: true }; } function getBlankCheques (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const inventory = ensureInventory(world.ecs, handle); const have = countItemInSlots(inventory.slots, ItemId.blankCheque); const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have); if (!need) { return { events: [], private: bagView(world.ecs, handle), bank: true }; } const def = itemDefinition(ItemId.blankCheque); const inserted = insertStack(inventory.slots, attachOrigins({ itemId: ItemId.blankCheque, quantity: need, origins: [{ origin: bankIssuedOrigin(BANK_LETTER_AUTHOR), quantity: need }] }), def); if (!inserted.ok) { throw userError("Need inventory space for blank cheques."); } inventory.slots = inserted.slots; return { events: [], private: bagView(world.ecs, handle), bank: true }; } function returnBlankCheques (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const inventory = ensureInventory(world.ecs, handle); const slot = inventory.slots[command.slotIndex | 0]; if (!slot || slot.itemId !== ItemId.blankCheque) { throw userError("Select blank cheques."); } const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0)); const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity); if (!taken.ok) { throw userError("Select blank cheques."); } inventory.slots = taken.slots; return { events: [], private: bagView(world.ecs, handle), bank: true }; } function writeCheque (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const vault = ensureVault(world.ecs, handle); const slotIndex = command.slotIndex | 0; const blankSlot = inventory.slots[slotIndex]; if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque) { throw userError("Select a blank cheque."); } const vaultSlot = vault.slots[command.vaultSlotIndex | 0]; if (!vaultSlot) { throw userError("Select vault goods to reserve."); } const def = itemDefinition(vaultSlot.itemId); if (!def) { throw userError("Unknown item."); } const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0); const available = countItemInSlots(vault.slots, vaultSlot.itemId); if (available < quantity) { throw userError("Not enough unreserved goods in the vault."); } if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry)) { throw userError("Need a free inventory slot for the filled cheque."); } const pulled = takeMatchingFromSlots(vault.slots, { itemId: vaultSlot.itemId, quantity, instance: def.uniqueInstance ? vaultSlot.instance : null }); if (!pulled.ok) { throw userError("Not enough unreserved goods in the vault."); } const appearance = world.ecs.get(handle, Component.appearance); const issuerName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim() || "Unknown"; const chequeId = randomUUID(); const reservedStack = { itemId: pulled.taken.itemId, quantity: pulled.taken.quantity, origins: normalizeOrigins(pulled.taken), instance: pulled.taken.instance ?? null, chequeId }; vault.slots = pulled.slots; vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack]; const filled = attachOrigins({ itemId: ItemId.filledCheque, quantity: 1, origins: [{ origin: writtenOrigin(issuerName), quantity: 1 }], instance: { kind: "filled-cheque", chequeId, issuerCharacterId: command.characterId, itemId: pulled.taken.itemId, quantity: pulled.taken.quantity, reservedInstance: pulled.taken.instance ?? null, createdAt: Date.now() } }); const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1); inventory.slots = blankTaken.slots; if (!inventory.slots[slotIndex]) { inventory.slots[slotIndex] = filled; } else { const free = inventory.slots.findIndex((entry) => !entry); inventory.slots[free] = filled; } return { events: [], private: bagView(world.ecs, handle) }; } function redeemCheque (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const inventory = ensureInventory(world.ecs, handle); const vault = ensureVault(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque") { throw userError("Select a filled cheque."); } const chequeId = slot.instance.chequeId; const issuerId = slot.instance.issuerCharacterId; const goodsDef = itemDefinition(slot.instance.itemId); if (!goodsDef) { throw userError("Unknown reserved goods."); } const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1); if (!chequeTaken.ok) { throw userError("Select a filled cheque."); } inventory.slots = chequeTaken.slots; let reservedStack = null; if (Number(issuerId) === Number(command.characterId)) { const index = findReservedChequeIndex(vault.reserved, slot.instance); if (index < 0) { inventory.slots[slotIndex] = chequeTaken.taken; throw userError("That cheque cannot be redeemed."); } reservedStack = cloneStack(vault.reserved[index]); vault.reserved = vault.reserved.filter((_, i) => i !== index); } else { const release = world.releaseChequeReservation?.(issuerId, chequeId, slot.instance); if (!release?.ok) { inventory.slots[slotIndex] = chequeTaken.taken; throw userError(release?.error ?? "That cheque cannot be redeemed."); } reservedStack = release.stack; } const inserted = insertStackGrowable(vault.slots, attachOrigins({ itemId: reservedStack.itemId, quantity: reservedStack.quantity, origins: normalizeOrigins(reservedStack), instance: reservedStack.instance ?? null }), goodsDef); if (!inserted.ok) { inventory.slots[slotIndex] = chequeTaken.taken; if (Number(issuerId) === Number(command.characterId)) { vault.reserved = [...(vault.reserved ?? []), reservedStack]; } else { world.restoreChequeReservation?.(issuerId, reservedStack); } throw userError("Your vault cannot hold those goods."); } vault.slots = inserted.slots; return { events: [], private: bagView(world.ecs, handle), bank: true }; } /** Match reserved vault entry by chequeId, or by goods identity for legacy rows that lost chequeId. */ export function findReservedChequeIndex (reserved, chequeInstance) { const list = reserved ?? []; const chequeId = chequeInstance?.chequeId; if (chequeId != null) { const byId = list.findIndex((entry) => entry?.chequeId === chequeId); if (byId >= 0) { return byId; } } const itemId = chequeInstance?.itemId; const quantity = chequeInstance?.quantity | 0; if (itemId == null || quantity <= 0) { return -1; } return list.findIndex((entry) => entry && entry.chequeId == null && entry.itemId === itemId && (entry.quantity | 0) === quantity ); } function claimInheritance (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const vault = ensureVault(world.ecs, handle); const remainder = []; for (const stack of command.stacks ?? []) { const def = itemDefinition(stack.itemId); if (!def) { remainder.push(stack); continue; } const inserted = insertStackGrowable(vault.slots, stack, def); if (inserted.ok) { vault.slots = inserted.slots; } else { remainder.push(stack); } } return { events: [], private: bagView(world.ecs, handle), bank: true, remainder }; } function writeLetter (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.paper) { throw userError("Select blank paper."); } const body = normalizeLetterBody(command.body); const appearance = world.ecs.get(handle, Component.appearance); const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim(); const letterStack = attachOrigins({ itemId: ItemId.letter, quantity: 1, origins: [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }], instance: { kind: "letter", letterId: randomUUID(), authorCharacterId: command.characterId, authorDisplayName, body, opened: true, writtenAt: Date.now() } }); if (slot.quantity <= 1) { inventory.slots[slotIndex] = letterStack; return { events: [], private: bagView(world.ecs, handle) }; } const free = inventory.slots.findIndex((entry) => !entry); if (free < 0) { throw userError("Need a free inventory slot for the letter."); } slot.quantity -= 1; inventory.slots[free] = letterStack; return { events: [], private: bagView(world.ecs, handle) }; } function editLetter (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter") { throw userError("That is not a letter."); } if (slot.instance.authorCharacterId !== command.characterId) { throw userError("Only the signer can edit this letter."); } const appearance = world.ecs.get(handle, Component.appearance); const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim() || slot.instance.authorDisplayName; slot.instance = { ...slot.instance, authorDisplayName, body: normalizeLetterBody(command.body), writtenAt: Date.now() }; slot.origins = [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }]; delete slot.origin; return { events: [], private: bagView(world.ecs, handle) }; } function openLetter (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter") { throw userError("That is not a letter."); } if (slot.instance.opened !== false) { return { events: [], private: bagView(world.ecs, handle) }; } slot.instance = { ...slot.instance, opened: true }; return { events: [], private: bagView(world.ecs, handle) }; } function normalizeLetterBody (raw) { const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd(); if (body.length > LETTER_MAX_BODY_CHARS) { throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); } return body; } function requireBank (world, handle) { const position = world.ecs.get(handle, Component.position); if (!nearBank(world, position.tileX, position.tileY)) { throw userError("Stand next to a bank."); } } function nearBank (world, tileX, tileY) { for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); if (data.blocks[index]?.typeId === BlockType.bank) { return true; } } } return false; } function ensureInventory (ecs, handle) { let inventory = ecs.get(handle, Component.inventory); if (!inventory) { inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); } inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots()); return inventory; } function ensureEquipment (ecs, handle) { return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment()); } function ensureVault (ecs, handle) { let vault = ecs.get(handle, Component.vault); if (!vault) { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); } if (!Array.isArray(vault.slots)) { vault.slots = []; } if (!Array.isArray(vault.reserved)) { vault.reserved = []; } return vault; } function userError (message) { const error = new Error(message); error.userFacing = true; return error; }