| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { syncPlayerHealth } from "../skills/service.js"; |
| 3 | import { canEquipItem } from "../../../shared/equipment/stats.js"; |
| 4 | import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; |
| 5 | import { stackRulesFor } from "../../../shared/items/stackRules.js"; |
| 6 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 7 | import { ItemId, itemDefinition, itemSpriteName, stackDisplayLabel, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js"; |
| 8 | import { |
| 9 | emptyEquipment, |
| 10 | emptySlots, |
| 11 | insertStack, |
| 12 | insertStackGrowable, |
| 13 | normalizeVault, |
| 14 | normalizeInventorySlots, |
| 15 | publicEquipment, |
| 16 | publicSlots, |
| 17 | takeFromSlot, |
| 18 | takeMatchingFromSlots, |
| 19 | countItemInSlots, |
| 20 | cloneStack, |
| 21 | singleItemFromStack, |
| 22 | stackQuantity, |
| 23 | consumeFillCharge |
| 24 | } from "../../../shared/items/inventory.js"; |
| 25 | import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js"; |
| 26 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 27 | import { randomUUID } from "node:crypto"; |
| 28 | import { tileShoveTowardBlock } from "../simulation/tileInteract.js"; |
| 29 | import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js"; |
| 30 | import { |
| 31 | applyStatusEffect, |
| 32 | emptyStatusEffects, |
| 33 | StatusEffectType |
| 34 | } from "../../../shared/statusEffects/rules.js"; |
| 35 | |
| 36 | export function publicGroundItem (item) |
| 37 | { |
| 38 | const instance = item.stack?.instance ?? null; |
| 39 | return { |
| 40 | groundItemId: item.groundItemId, |
| 41 | tileX: item.tileX, |
| 42 | tileY: item.tileY, |
| 43 | itemId: item.stack.itemId, |
| 44 | quantity: item.stack.quantity, |
| 45 | displayName: stackDisplayLabel(item.stack), |
| 46 | sprite: itemSpriteName(item.stack.itemId, instance), |
| 47 | instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper") |
| 48 | ? instance |
| 49 | : null, |
| 50 | expiresAt: item.expiresAt |
| 51 | }; |
| 52 | } |
| 53 | |
| 54 | export function bagView (ecs, handle) |
| 55 | { |
| 56 | const vault = normalizeVault(ecs.get(handle, Component.vault)); |
| 57 | return { |
| 58 | inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())), |
| 59 | equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()), |
| 60 | vault: publicSlots(vault.slots), |
| 61 | vaultReserved: publicSlots(vault.reserved) |
| 62 | }; |
| 63 | } |
| 64 | |
| 65 | export function applyBagView (ecs, handle, bag) |
| 66 | { |
| 67 | const inventory = ensureInventory(ecs, handle); |
| 68 | inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots())); |
| 69 | const equipment = ensureEquipment(ecs, handle); |
| 70 | const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment()); |
| 71 | equipment.slots = nextEquip.slots; |
| 72 | const vault = ensureVault(ecs, handle); |
| 73 | const normalized = normalizeVault( |
| 74 | bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault)) |
| 75 | ? { slots: bag.vault, reserved: bag.vaultReserved } |
| 76 | : bag.vault |
| 77 | ); |
| 78 | vault.slots = publicSlots(normalized.slots); |
| 79 | vault.reserved = publicSlots(normalized.reserved); |
| 80 | return bagView(ecs, handle); |
| 81 | } |
| 82 | |
| 83 | export function handleItemCommand (world, sessionId, command, now) |
| 84 | { |
| 85 | switch (command.type) |
| 86 | { |
| 87 | case "drop-item": |
| 88 | return dropItem(world, sessionId, command, now); |
| 89 | case "pickup-item": |
| 90 | return pickupItem(world, sessionId, command); |
| 91 | case "equip-item": |
| 92 | return equipItem(world, sessionId, command); |
| 93 | case "unequip-item": |
| 94 | return unequipItem(world, sessionId, command); |
| 95 | case "open-bank": |
| 96 | return openBank(world, sessionId, command); |
| 97 | case "bank-deposit": |
| 98 | return bankMove(world, sessionId, command, "inventory", "vault"); |
| 99 | case "bank-withdraw": |
| 100 | return bankMove(world, sessionId, command, "vault", "inventory"); |
| 101 | case "get-blank-cheques": |
| 102 | return getBlankCheques(world, sessionId, command); |
| 103 | case "return-blank-cheques": |
| 104 | return returnBlankCheques(world, sessionId, command); |
| 105 | case "write-cheque": |
| 106 | return writeCheque(world, sessionId, command); |
| 107 | case "redeem-cheque": |
| 108 | return redeemCheque(world, sessionId, command); |
| 109 | case "claim-inheritance": |
| 110 | return claimInheritance(world, sessionId, command); |
| 111 | case "write-letter": |
| 112 | return writeLetter(world, sessionId, command); |
| 113 | case "edit-letter": |
| 114 | return editLetter(world, sessionId, command); |
| 115 | case "open-letter": |
| 116 | return openLetter(world, sessionId, command); |
| 117 | case "eat-item": |
| 118 | return eatItem(world, sessionId, command); |
| 119 | case "drink-item": |
| 120 | return drinkItem(world, sessionId, command); |
| 121 | default: |
| 122 | return null; |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | export function expireGroundItems (world, now) |
| 127 | { |
| 128 | const events = []; |
| 129 | for (const item of [...world.groundItems.values()]) |
| 130 | { |
| 131 | if (item.expiresAt > now) |
| 132 | { continue; } |
| 133 | removeGroundItem(world, item.groundItemId); |
| 134 | events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); |
| 135 | } |
| 136 | return events; |
| 137 | } |
| 138 | |
| 139 | export function groundItemsInChunk (world, chunkX, chunkY) |
| 140 | { |
| 141 | return [...world.groundItems.values()] |
| 142 | .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY) |
| 143 | .map(publicGroundItem); |
| 144 | } |
| 145 | |
| 146 | export function groundItemsInRegion (world, regionX, regionY, tileToRegion) |
| 147 | { |
| 148 | return [...world.groundItems.values()].filter((item) => |
| 149 | tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY |
| 150 | ); |
| 151 | } |
| 152 | |
| 153 | export function addGroundItem (world, item) |
| 154 | { |
| 155 | world.groundItems.set(item.groundItemId, item); |
| 156 | const key = tileKey(item.tileX, item.tileY); |
| 157 | if (!world.groundByTile.has(key)) |
| 158 | { world.groundByTile.set(key, new Set()); } |
| 159 | world.groundByTile.get(key).add(item.groundItemId); |
| 160 | } |
| 161 | |
| 162 | export function removeGroundItem (world, groundItemId) |
| 163 | { |
| 164 | const item = world.groundItems.get(groundItemId); |
| 165 | if (!item) |
| 166 | { return null; } |
| 167 | world.groundItems.delete(groundItemId); |
| 168 | const key = tileKey(item.tileX, item.tileY); |
| 169 | world.groundByTile.get(key)?.delete(groundItemId); |
| 170 | return item; |
| 171 | } |
| 172 | |
| 173 | export function replaceGroundItems (world, items) |
| 174 | { |
| 175 | world.groundItems.clear(); |
| 176 | world.groundByTile.clear(); |
| 177 | for (const item of items ?? []) |
| 178 | { addGroundItem(world, item); } |
| 179 | } |
| 180 | |
| 181 | export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion) |
| 182 | { |
| 183 | for (const item of [...world.groundItems.values()]) |
| 184 | { |
| 185 | if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY) |
| 186 | { removeGroundItem(world, item.groundItemId); } |
| 187 | } |
| 188 | for (const item of items ?? []) |
| 189 | { addGroundItem(world, item); } |
| 190 | } |
| 191 | |
| 192 | function dropItem (world, sessionId, command, now) |
| 193 | { |
| 194 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 195 | const inventory = ensureInventory(world.ecs, handle); |
| 196 | const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null); |
| 197 | if (!taken.ok) |
| 198 | { throw userError("That inventory slot is empty."); } |
| 199 | inventory.slots = taken.slots; |
| 200 | const position = world.ecs.get(handle, Component.position); |
| 201 | const item = { |
| 202 | groundItemId: command.groundItemId, |
| 203 | tileX: position.tileX, |
| 204 | tileY: position.tileY, |
| 205 | stack: taken.taken, |
| 206 | droppedAt: now, |
| 207 | expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000), |
| 208 | source: "player-drop", |
| 209 | droppedByCharacterId: command.characterId |
| 210 | }; |
| 211 | addGroundItem(world, item); |
| 212 | return { |
| 213 | events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }], |
| 214 | private: bagView(world.ecs, handle) |
| 215 | }; |
| 216 | } |
| 217 | |
| 218 | function pickupItem (world, sessionId, command) |
| 219 | { |
| 220 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 221 | const item = world.groundItems.get(command.groundItemId); |
| 222 | if (!item) |
| 223 | { throw userError("That item is no longer on the ground."); } |
| 224 | const position = world.ecs.get(handle, Component.position); |
| 225 | if (position.tileX !== item.tileX || position.tileY !== item.tileY) |
| 226 | { throw userError("Stand on the item to pick it up."); } |
| 227 | const def = itemDefinition(item.stack.itemId); |
| 228 | if (!def) |
| 229 | { throw userError("Unknown item."); } |
| 230 | const inventory = ensureInventory(world.ecs, handle); |
| 231 | let stackToAdd = item.stack; |
| 232 | if (item.stack.itemId === ItemId.blankCheque) |
| 233 | { |
| 234 | const have = countItemInSlots(inventory.slots, ItemId.blankCheque); |
| 235 | const room = BLANK_CHEQUE_CARRY_CAP - have; |
| 236 | if (room <= 0) |
| 237 | { throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); } |
| 238 | const takeQty = Math.min(item.stack.quantity, room); |
| 239 | stackToAdd = { ...item.stack, quantity: takeQty }; |
| 240 | } |
| 241 | const inserted = insertStack(inventory.slots, stackToAdd, def); |
| 242 | if (!inserted.ok) |
| 243 | { throw userError("Your inventory cannot hold that."); } |
| 244 | inventory.slots = inserted.slots; |
| 245 | const events = []; |
| 246 | if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity) |
| 247 | { |
| 248 | item.stack.quantity -= stackToAdd.quantity; |
| 249 | events.push({ |
| 250 | type: "ground-item-appear", |
| 251 | ...publicGroundItem(item), |
| 252 | stack: item.stack, |
| 253 | droppedAt: item.droppedAt, |
| 254 | source: item.source, |
| 255 | droppedByCharacterId: item.droppedByCharacterId, |
| 256 | expiresAt: item.expiresAt |
| 257 | }); |
| 258 | } |
| 259 | else |
| 260 | { |
| 261 | removeGroundItem(world, item.groundItemId); |
| 262 | events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); |
| 263 | } |
| 264 | return { |
| 265 | events, |
| 266 | private: bagView(world.ecs, handle) |
| 267 | }; |
| 268 | } |
| 269 | |
| 270 | function equipItem (world, sessionId, command) |
| 271 | { |
| 272 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 273 | const inventory = ensureInventory(world.ecs, handle); |
| 274 | const equipment = ensureEquipment(world.ecs, handle); |
| 275 | const slotIndex = command.slotIndex | 0; |
| 276 | const source = inventory.slots[slotIndex]; |
| 277 | if (!source || stackQuantity(source.quantity) <= 0) |
| 278 | { throw userError("That inventory slot is empty."); } |
| 279 | const def = itemDefinition(source.itemId); |
| 280 | const slot = def?.equipment?.slot; |
| 281 | if (!slot) |
| 282 | { throw userError("That item cannot be equipped."); } |
| 283 | const skills = world.ecs.get(handle, Component.skills); |
| 284 | const equipCheck = canEquipItem(skills, def); |
| 285 | if (!equipCheck.ok) |
| 286 | { throw userError(equipCheck.reason); } |
| 287 | |
| 288 | const isArrowAmmo = def.equipment?.kind === EquipmentKind.arrowAmmo; |
| 289 | const taken = takeFromSlot(inventory.slots, slotIndex, isArrowAmmo ? null : 1); |
| 290 | if (!taken.ok || stackQuantity(taken.taken?.quantity) <= 0) |
| 291 | { throw userError("That inventory slot is empty."); } |
| 292 | if (taken.taken.itemId === ItemId.coins) |
| 293 | { |
| 294 | inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots; |
| 295 | throw userError("Coins cannot be equipped."); |
| 296 | } |
| 297 | |
| 298 | if (isArrowAmmo) |
| 299 | { |
| 300 | let slots = taken.slots; |
| 301 | const previous = equipment.slots[slot]; |
| 302 | if (previous) |
| 303 | { |
| 304 | const previousDef = itemDefinition(previous.itemId); |
| 305 | if (previous.itemId === taken.taken.itemId) |
| 306 | { |
| 307 | const rules = stackRulesFor(def); |
| 308 | const space = rules.maxStackSize - stackQuantity(previous.quantity); |
| 309 | const add = Math.min(space, stackQuantity(taken.taken.quantity)); |
| 310 | if (add <= 0) |
| 311 | { |
| 312 | inventory.slots = insertStack(slots, taken.taken, def).slots; |
| 313 | throw userError("Your arrow stack is full."); |
| 314 | } |
| 315 | previous.quantity = stackQuantity(previous.quantity) + add; |
| 316 | const leftover = stackQuantity(taken.taken.quantity) - add; |
| 317 | if (leftover > 0) |
| 318 | { |
| 319 | const back = insertStack(slots, { ...taken.taken, quantity: leftover }, def); |
| 320 | if (!back.ok) |
| 321 | { |
| 322 | previous.quantity = stackQuantity(previous.quantity) - add; |
| 323 | inventory.slots = insertStack(slots, taken.taken, def).slots; |
| 324 | throw userError("No inventory space for leftover arrows."); |
| 325 | } |
| 326 | slots = back.slots; |
| 327 | } |
| 328 | inventory.slots = slots; |
| 329 | return { events: [], private: bagView(world.ecs, handle), appearanceChanged: false }; |
| 330 | } |
| 331 | const back = insertStack(slots, previous, previousDef); |
| 332 | if (!back.ok) |
| 333 | { |
| 334 | inventory.slots = insertStack(slots, taken.taken, def).slots; |
| 335 | throw userError("No inventory space to unequip the current item."); |
| 336 | } |
| 337 | slots = back.slots; |
| 338 | } |
| 339 | inventory.slots = slots; |
| 340 | equipment.slots[slot] = taken.taken; |
| 341 | return { events: [], private: bagView(world.ecs, handle), appearanceChanged: false }; |
| 342 | } |
| 343 | |
| 344 | const toEquip = singleItemFromStack(taken.taken); |
| 345 | const previous = equipment.slots[slot]; |
| 346 | if (previous) |
| 347 | { |
| 348 | const previousSingle = singleItemFromStack(previous); |
| 349 | const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId)); |
| 350 | if (!back.ok) |
| 351 | { |
| 352 | inventory.slots = insertStack(inventory.slots, toEquip, def).slots; |
| 353 | throw userError("No inventory space to unequip the current item."); |
| 354 | } |
| 355 | inventory.slots = back.slots; |
| 356 | } |
| 357 | else |
| 358 | { inventory.slots = taken.slots; } |
| 359 | equipment.slots[slot] = toEquip; |
| 360 | return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true }; |
| 361 | } |
| 362 | |
| 363 | function unequipItem (world, sessionId, command) |
| 364 | { |
| 365 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 366 | const inventory = ensureInventory(world.ecs, handle); |
| 367 | const equipment = ensureEquipment(world.ecs, handle); |
| 368 | const worn = equipment.slots[command.equipSlot]; |
| 369 | if (!worn) |
| 370 | { throw userError("Nothing is equipped there."); } |
| 371 | const def = itemDefinition(worn.itemId); |
| 372 | const toStore = def?.equipment?.kind === EquipmentKind.arrowAmmo |
| 373 | ? cloneStack(worn) |
| 374 | : singleItemFromStack(worn); |
| 375 | const inserted = insertStack(inventory.slots, toStore, def); |
| 376 | if (!inserted.ok) |
| 377 | { throw userError("Your inventory cannot hold that."); } |
| 378 | inventory.slots = inserted.slots; |
| 379 | equipment.slots[command.equipSlot] = null; |
| 380 | const appearanceChanged = def?.equipment?.kind !== EquipmentKind.arrowAmmo; |
| 381 | return { events: [], private: bagView(world.ecs, handle), appearanceChanged }; |
| 382 | } |
| 383 | |
| 384 | function eatItem (world, sessionId, command) |
| 385 | { |
| 386 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 387 | syncPlayerHealth(world.ecs, handle); |
| 388 | const inventory = ensureInventory(world.ecs, handle); |
| 389 | const health = world.ecs.get(handle, Component.health); |
| 390 | if (!health) |
| 391 | { throw userError("You cannot eat right now."); } |
| 392 | if ((health.current | 0) >= (health.max | 0)) |
| 393 | { throw userError("You are already at full health."); } |
| 394 | const slotIndex = command.slotIndex | 0; |
| 395 | const slot = inventory.slots[slotIndex]; |
| 396 | if (!slot || stackQuantity(slot.quantity) <= 0) |
| 397 | { throw userError("That inventory slot is empty."); } |
| 398 | const def = itemDefinition(slot.itemId); |
| 399 | const healing = def?.healing ?? 0; |
| 400 | if (healing <= 0) |
| 401 | { throw userError("That cannot be eaten."); } |
| 402 | const taken = takeFromSlot(inventory.slots, slotIndex, 1); |
| 403 | if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1) |
| 404 | { throw userError("That inventory slot is empty."); } |
| 405 | inventory.slots = taken.slots; |
| 406 | health.current = Math.min(health.max | 0, (health.current | 0) + healing); |
| 407 | return { |
| 408 | events: [], |
| 409 | private: bagView(world.ecs, handle), |
| 410 | healthChanged: true |
| 411 | }; |
| 412 | } |
| 413 | |
| 414 | function drinkItem (world, sessionId, command) |
| 415 | { |
| 416 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 417 | syncPlayerHealth(world.ecs, handle); |
| 418 | const inventory = ensureInventory(world.ecs, handle); |
| 419 | const slotIndex = command.slotIndex | 0; |
| 420 | const slot = inventory.slots[slotIndex]; |
| 421 | if (!slot || slot.itemId !== ItemId.potion || slot.instance?.kind !== "potion") |
| 422 | { throw userError("That is not a potion."); } |
| 423 | const consumed = consumeFillCharge(inventory.slots, slotIndex, { |
| 424 | kind: "potion", |
| 425 | itemId: ItemId.potion, |
| 426 | returnEmptyItemId: ItemId.glassBottle |
| 427 | }); |
| 428 | if (!consumed.ok) |
| 429 | { |
| 430 | if (consumed.reason === "space") |
| 431 | { |
| 432 | throw userError( |
| 433 | "Need bag space to keep the partially used potion (or empty bottle)." |
| 434 | ); |
| 435 | } |
| 436 | throw userError("That inventory slot is empty."); |
| 437 | } |
| 438 | inventory.slots = consumed.slots; |
| 439 | const effectResult = applyPotionEffect(world.ecs, handle, resolvePotionEffect(consumed.instance)); |
| 440 | return { |
| 441 | events: effectResult.events ?? [], |
| 442 | private: bagView(world.ecs, handle), |
| 443 | healthChanged: !!effectResult.healthChanged, |
| 444 | appearanceChanged: !!effectResult.appearanceChanged, |
| 445 | statusEffectsChanged: !!effectResult.statusEffectsChanged |
| 446 | }; |
| 447 | } |
| 448 | |
| 449 | function ensureStatusEffects (ecs, handle) |
| 450 | { |
| 451 | let component = ecs.get(handle, Component.statusEffects); |
| 452 | if (!component) |
| 453 | { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); } |
| 454 | if (!Array.isArray(component.effects)) |
| 455 | { component.effects = []; } |
| 456 | return component; |
| 457 | } |
| 458 | |
| 459 | function applyPotionEffect (ecs, handle, effect) |
| 460 | { |
| 461 | const result = { |
| 462 | healthChanged: false, |
| 463 | appearanceChanged: false, |
| 464 | statusEffectsChanged: false, |
| 465 | events: [] |
| 466 | }; |
| 467 | if (!effect || typeof effect !== "object") |
| 468 | { return result; } |
| 469 | |
| 470 | const health = ecs.get(handle, Component.health); |
| 471 | const type = effect.type; |
| 472 | |
| 473 | if (type === "heal" && health) |
| 474 | { |
| 475 | const amount = Math.max(0, effect.amount | 0 || 0); |
| 476 | health.current = Math.min(health.max | 0, (health.current | 0) + amount); |
| 477 | result.healthChanged = true; |
| 478 | return result; |
| 479 | } |
| 480 | if (type === "damage" && health) |
| 481 | { |
| 482 | const amount = Math.max(0, effect.amount | 0 || 0); |
| 483 | health.current = Math.max(0, (health.current | 0) - amount); |
| 484 | result.healthChanged = true; |
| 485 | return result; |
| 486 | } |
| 487 | |
| 488 | const timed = { |
| 489 | [StatusEffectType.healthRegen]: true, |
| 490 | [StatusEffectType.staminaRegen]: true, |
| 491 | [StatusEffectType.strengthBonus]: true, |
| 492 | [StatusEffectType.mindBonus]: true, |
| 493 | [StatusEffectType.staminaDrain]: true, |
| 494 | [StatusEffectType.glow]: true, |
| 495 | [StatusEffectType.shrink]: true, |
| 496 | [StatusEffectType.blind]: true |
| 497 | }; |
| 498 | if (!timed[type]) |
| 499 | { return result; } |
| 500 | |
| 501 | const component = ensureStatusEffects(ecs, handle); |
| 502 | applyStatusEffect(component, effect, Date.now()); |
| 503 | result.statusEffectsChanged = true; |
| 504 | if (type === StatusEffectType.glow || type === StatusEffectType.shrink) |
| 505 | { result.appearanceChanged = true; } |
| 506 | return result; |
| 507 | } |
| 508 | |
| 509 | function openBank (world, sessionId, command) |
| 510 | { |
| 511 | const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId); |
| 512 | const position = world.ecs.get(handle, Component.position); |
| 513 | if (!nearBank(world, position.tileX, position.tileY)) |
| 514 | { throw userError("Stand next to a bank."); } |
| 515 | const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank); |
| 516 | return { |
| 517 | events: shove ? [shove] : [], |
| 518 | private: bagView(world.ecs, handle), |
| 519 | bank: true |
| 520 | }; |
| 521 | } |
| 522 | |
| 523 | function bankMove (world, sessionId, command, fromKey, toKey) |
| 524 | { |
| 525 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 526 | requireBank(world, handle); |
| 527 | const inventory = ensureInventory(world.ecs, handle); |
| 528 | const vault = ensureVault(world.ecs, handle); |
| 529 | if (fromKey === "inventory" && toKey === "vault") |
| 530 | { |
| 531 | const slot = inventory.slots[command.slotIndex | 0]; |
| 532 | if (slot?.itemId === ItemId.filledCheque) |
| 533 | { return redeemCheque(world, sessionId, command); } |
| 534 | } |
| 535 | const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots; |
| 536 | const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null); |
| 537 | if (!taken.ok) |
| 538 | { throw userError("That slot is empty."); } |
| 539 | const def = itemDefinition(taken.taken.itemId); |
| 540 | if (toKey === "vault") |
| 541 | { |
| 542 | const inserted = insertStackGrowable(vault.slots, taken.taken, def); |
| 543 | inventory.slots = taken.slots; |
| 544 | vault.slots = inserted.slots; |
| 545 | } |
| 546 | else |
| 547 | { |
| 548 | const inserted = insertStack(inventory.slots, taken.taken, def); |
| 549 | if (!inserted.ok) |
| 550 | { throw userError("Not enough space."); } |
| 551 | vault.slots = taken.slots; |
| 552 | inventory.slots = inserted.slots; |
| 553 | } |
| 554 | return { events: [], private: bagView(world.ecs, handle), bank: true }; |
| 555 | } |
| 556 | |
| 557 | function getBlankCheques (world, sessionId, command) |
| 558 | { |
| 559 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 560 | requireBank(world, handle); |
| 561 | const inventory = ensureInventory(world.ecs, handle); |
| 562 | const have = countItemInSlots(inventory.slots, ItemId.blankCheque); |
| 563 | const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have); |
| 564 | if (!need) |
| 565 | { return { events: [], private: bagView(world.ecs, handle), bank: true }; } |
| 566 | const def = itemDefinition(ItemId.blankCheque); |
| 567 | const inserted = insertStack(inventory.slots, { itemId: ItemId.blankCheque, quantity: need }, def); |
| 568 | if (!inserted.ok) |
| 569 | { throw userError("Need inventory space for blank cheques."); } |
| 570 | inventory.slots = inserted.slots; |
| 571 | return { events: [], private: bagView(world.ecs, handle), bank: true }; |
| 572 | } |
| 573 | |
| 574 | function returnBlankCheques (world, sessionId, command) |
| 575 | { |
| 576 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 577 | requireBank(world, handle); |
| 578 | const inventory = ensureInventory(world.ecs, handle); |
| 579 | const slot = inventory.slots[command.slotIndex | 0]; |
| 580 | if (!slot || slot.itemId !== ItemId.blankCheque) |
| 581 | { throw userError("Select blank cheques."); } |
| 582 | const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0)); |
| 583 | const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity); |
| 584 | if (!taken.ok) |
| 585 | { throw userError("Select blank cheques."); } |
| 586 | inventory.slots = taken.slots; |
| 587 | return { events: [], private: bagView(world.ecs, handle), bank: true }; |
| 588 | } |
| 589 | |
| 590 | function writeCheque (world, sessionId, command) |
| 591 | { |
| 592 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 593 | const inventory = ensureInventory(world.ecs, handle); |
| 594 | const vault = ensureVault(world.ecs, handle); |
| 595 | const slotIndex = command.slotIndex | 0; |
| 596 | const blankSlot = inventory.slots[slotIndex]; |
| 597 | if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque) |
| 598 | { throw userError("Select a blank cheque."); } |
| 599 | const vaultSlot = vault.slots[command.vaultSlotIndex | 0]; |
| 600 | if (!vaultSlot) |
| 601 | { throw userError("Select vault goods to reserve."); } |
| 602 | const def = itemDefinition(vaultSlot.itemId); |
| 603 | if (!def) |
| 604 | { throw userError("Unknown item."); } |
| 605 | const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0); |
| 606 | const available = countItemInSlots(vault.slots, vaultSlot.itemId); |
| 607 | if (available < quantity) |
| 608 | { throw userError("Not enough unreserved goods in the vault."); } |
| 609 | if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry)) |
| 610 | { throw userError("Need a free inventory slot for the filled cheque."); } |
| 611 | |
| 612 | const pulled = takeMatchingFromSlots(vault.slots, { |
| 613 | itemId: vaultSlot.itemId, |
| 614 | quantity, |
| 615 | instance: def.uniqueInstance ? vaultSlot.instance : null |
| 616 | }); |
| 617 | if (!pulled.ok) |
| 618 | { throw userError("Not enough unreserved goods in the vault."); } |
| 619 | |
| 620 | const chequeId = randomUUID(); |
| 621 | const reservedStack = { |
| 622 | itemId: pulled.taken.itemId, |
| 623 | quantity: pulled.taken.quantity, |
| 624 | origin: pulled.taken.origin ?? null, |
| 625 | instance: pulled.taken.instance ?? null, |
| 626 | chequeId |
| 627 | }; |
| 628 | vault.slots = pulled.slots; |
| 629 | vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack]; |
| 630 | |
| 631 | const filled = { |
| 632 | itemId: ItemId.filledCheque, |
| 633 | quantity: 1, |
| 634 | origin: null, |
| 635 | instance: { |
| 636 | kind: "filled-cheque", |
| 637 | chequeId, |
| 638 | issuerCharacterId: command.characterId, |
| 639 | itemId: pulled.taken.itemId, |
| 640 | quantity: pulled.taken.quantity, |
| 641 | reservedInstance: pulled.taken.instance ?? null, |
| 642 | createdAt: Date.now() |
| 643 | } |
| 644 | }; |
| 645 | const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1); |
| 646 | inventory.slots = blankTaken.slots; |
| 647 | if (!inventory.slots[slotIndex]) |
| 648 | { inventory.slots[slotIndex] = filled; } |
| 649 | else |
| 650 | { |
| 651 | const free = inventory.slots.findIndex((entry) => !entry); |
| 652 | inventory.slots[free] = filled; |
| 653 | } |
| 654 | return { events: [], private: bagView(world.ecs, handle) }; |
| 655 | } |
| 656 | |
| 657 | function redeemCheque (world, sessionId, command) |
| 658 | { |
| 659 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 660 | requireBank(world, handle); |
| 661 | const inventory = ensureInventory(world.ecs, handle); |
| 662 | const vault = ensureVault(world.ecs, handle); |
| 663 | const slotIndex = command.slotIndex | 0; |
| 664 | const slot = inventory.slots[slotIndex]; |
| 665 | if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque") |
| 666 | { throw userError("Select a filled cheque."); } |
| 667 | |
| 668 | const chequeId = slot.instance.chequeId; |
| 669 | const issuerId = slot.instance.issuerCharacterId; |
| 670 | const goodsDef = itemDefinition(slot.instance.itemId); |
| 671 | if (!goodsDef) |
| 672 | { throw userError("Unknown reserved goods."); } |
| 673 | |
| 674 | const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1); |
| 675 | if (!chequeTaken.ok) |
| 676 | { throw userError("Select a filled cheque."); } |
| 677 | inventory.slots = chequeTaken.slots; |
| 678 | |
| 679 | let reservedStack = null; |
| 680 | if (Number(issuerId) === Number(command.characterId)) |
| 681 | { |
| 682 | const index = findReservedChequeIndex(vault.reserved, slot.instance); |
| 683 | if (index < 0) |
| 684 | { |
| 685 | inventory.slots[slotIndex] = chequeTaken.taken; |
| 686 | throw userError("That cheque cannot be redeemed."); |
| 687 | } |
| 688 | reservedStack = cloneStack(vault.reserved[index]); |
| 689 | vault.reserved = vault.reserved.filter((_, i) => i !== index); |
| 690 | } |
| 691 | else |
| 692 | { |
| 693 | const release = world.releaseChequeReservation?.(issuerId, chequeId, slot.instance); |
| 694 | if (!release?.ok) |
| 695 | { |
| 696 | inventory.slots[slotIndex] = chequeTaken.taken; |
| 697 | throw userError(release?.error ?? "That cheque cannot be redeemed."); |
| 698 | } |
| 699 | reservedStack = release.stack; |
| 700 | } |
| 701 | |
| 702 | const inserted = insertStackGrowable(vault.slots, { |
| 703 | itemId: reservedStack.itemId, |
| 704 | quantity: reservedStack.quantity, |
| 705 | origin: reservedStack.origin ?? null, |
| 706 | origins: reservedStack.origins ?? null, |
| 707 | instance: reservedStack.instance ?? null |
| 708 | }, goodsDef); |
| 709 | if (!inserted.ok) |
| 710 | { |
| 711 | inventory.slots[slotIndex] = chequeTaken.taken; |
| 712 | if (Number(issuerId) === Number(command.characterId)) |
| 713 | { vault.reserved = [...(vault.reserved ?? []), reservedStack]; } |
| 714 | else |
| 715 | { world.restoreChequeReservation?.(issuerId, reservedStack); } |
| 716 | throw userError("Your vault cannot hold those goods."); |
| 717 | } |
| 718 | vault.slots = inserted.slots; |
| 719 | return { events: [], private: bagView(world.ecs, handle), bank: true }; |
| 720 | } |
| 721 | |
| 722 | /** Match reserved vault entry by chequeId, or by goods identity for legacy rows that lost chequeId. */ |
| 723 | export function findReservedChequeIndex (reserved, chequeInstance) |
| 724 | { |
| 725 | const list = reserved ?? []; |
| 726 | const chequeId = chequeInstance?.chequeId; |
| 727 | if (chequeId != null) |
| 728 | { |
| 729 | const byId = list.findIndex((entry) => entry?.chequeId === chequeId); |
| 730 | if (byId >= 0) |
| 731 | { return byId; } |
| 732 | } |
| 733 | const itemId = chequeInstance?.itemId; |
| 734 | const quantity = chequeInstance?.quantity | 0; |
| 735 | if (itemId == null || quantity <= 0) |
| 736 | { return -1; } |
| 737 | return list.findIndex((entry) => |
| 738 | entry |
| 739 | && entry.chequeId == null |
| 740 | && entry.itemId === itemId |
| 741 | && (entry.quantity | 0) === quantity |
| 742 | ); |
| 743 | } |
| 744 | |
| 745 | function claimInheritance (world, sessionId, command) |
| 746 | { |
| 747 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 748 | requireBank(world, handle); |
| 749 | const vault = ensureVault(world.ecs, handle); |
| 750 | const remainder = []; |
| 751 | for (const stack of command.stacks ?? []) |
| 752 | { |
| 753 | const def = itemDefinition(stack.itemId); |
| 754 | if (!def) |
| 755 | { |
| 756 | remainder.push(stack); |
| 757 | continue; |
| 758 | } |
| 759 | const inserted = insertStackGrowable(vault.slots, stack, def); |
| 760 | if (inserted.ok) |
| 761 | { vault.slots = inserted.slots; } |
| 762 | else |
| 763 | { remainder.push(stack); } |
| 764 | } |
| 765 | return { events: [], private: bagView(world.ecs, handle), bank: true, remainder }; |
| 766 | } |
| 767 | |
| 768 | function writeLetter (world, sessionId, command) |
| 769 | { |
| 770 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 771 | const inventory = ensureInventory(world.ecs, handle); |
| 772 | const slotIndex = command.slotIndex | 0; |
| 773 | const slot = inventory.slots[slotIndex]; |
| 774 | if (!slot || slot.itemId !== ItemId.paper) |
| 775 | { throw userError("Select blank paper."); } |
| 776 | const body = normalizeLetterBody(command.body); |
| 777 | const appearance = world.ecs.get(handle, Component.appearance); |
| 778 | const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim(); |
| 779 | const letterStack = { |
| 780 | itemId: ItemId.letter, |
| 781 | quantity: 1, |
| 782 | origin: null, |
| 783 | instance: { |
| 784 | kind: "letter", |
| 785 | letterId: randomUUID(), |
| 786 | authorCharacterId: command.characterId, |
| 787 | authorDisplayName, |
| 788 | body, |
| 789 | opened: true, |
| 790 | writtenAt: Date.now() |
| 791 | } |
| 792 | }; |
| 793 | if (slot.quantity <= 1) |
| 794 | { |
| 795 | inventory.slots[slotIndex] = letterStack; |
| 796 | return { events: [], private: bagView(world.ecs, handle) }; |
| 797 | } |
| 798 | const free = inventory.slots.findIndex((entry) => !entry); |
| 799 | if (free < 0) |
| 800 | { throw userError("Need a free inventory slot for the letter."); } |
| 801 | slot.quantity -= 1; |
| 802 | inventory.slots[free] = letterStack; |
| 803 | return { events: [], private: bagView(world.ecs, handle) }; |
| 804 | } |
| 805 | |
| 806 | function editLetter (world, sessionId, command) |
| 807 | { |
| 808 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 809 | const inventory = ensureInventory(world.ecs, handle); |
| 810 | const slotIndex = command.slotIndex | 0; |
| 811 | const slot = inventory.slots[slotIndex]; |
| 812 | if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter") |
| 813 | { throw userError("That is not a letter."); } |
| 814 | if (slot.instance.authorCharacterId !== command.characterId) |
| 815 | { throw userError("Only the signer can edit this letter."); } |
| 816 | const appearance = world.ecs.get(handle, Component.appearance); |
| 817 | const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim() |
| 818 | || slot.instance.authorDisplayName; |
| 819 | slot.instance = { |
| 820 | ...slot.instance, |
| 821 | authorDisplayName, |
| 822 | body: normalizeLetterBody(command.body), |
| 823 | writtenAt: Date.now() |
| 824 | }; |
| 825 | return { events: [], private: bagView(world.ecs, handle) }; |
| 826 | } |
| 827 | |
| 828 | function openLetter (world, sessionId, command) |
| 829 | { |
| 830 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 831 | const inventory = ensureInventory(world.ecs, handle); |
| 832 | const slotIndex = command.slotIndex | 0; |
| 833 | const slot = inventory.slots[slotIndex]; |
| 834 | if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter") |
| 835 | { throw userError("That is not a letter."); } |
| 836 | if (slot.instance.opened !== false) |
| 837 | { return { events: [], private: bagView(world.ecs, handle) }; } |
| 838 | slot.instance = { ...slot.instance, opened: true }; |
| 839 | return { events: [], private: bagView(world.ecs, handle) }; |
| 840 | } |
| 841 | |
| 842 | function normalizeLetterBody (raw) |
| 843 | { |
| 844 | const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd(); |
| 845 | if (body.length > LETTER_MAX_BODY_CHARS) |
| 846 | { throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); } |
| 847 | return body; |
| 848 | } |
| 849 | |
| 850 | function requireBank (world, handle) |
| 851 | { |
| 852 | const position = world.ecs.get(handle, Component.position); |
| 853 | if (!nearBank(world, position.tileX, position.tileY)) |
| 854 | { throw userError("Stand next to a bank."); } |
| 855 | } |
| 856 | |
| 857 | function nearBank (world, tileX, tileY) |
| 858 | { |
| 859 | for (let dy = -1; dy <= 1; dy++) |
| 860 | { |
| 861 | for (let dx = -1; dx <= 1; dx++) |
| 862 | { |
| 863 | const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); |
| 864 | const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); |
| 865 | if (data.blocks[index]?.typeId === BlockType.bank) |
| 866 | { return true; } |
| 867 | } |
| 868 | } |
| 869 | return false; |
| 870 | } |
| 871 | |
| 872 | function ensureInventory (ecs, handle) |
| 873 | { |
| 874 | let inventory = ecs.get(handle, Component.inventory); |
| 875 | if (!inventory) |
| 876 | { inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); } |
| 877 | inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots()); |
| 878 | return inventory; |
| 879 | } |
| 880 | |
| 881 | function ensureEquipment (ecs, handle) |
| 882 | { |
| 883 | return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment()); |
| 884 | } |
| 885 | |
| 886 | function ensureVault (ecs, handle) |
| 887 | { |
| 888 | let vault = ecs.get(handle, Component.vault); |
| 889 | if (!vault) |
| 890 | { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); } |
| 891 | if (!Array.isArray(vault.slots)) |
| 892 | { vault.slots = []; } |
| 893 | if (!Array.isArray(vault.reserved)) |
| 894 | { vault.reserved = []; } |
| 895 | return vault; |
| 896 | } |
| 897 | |
| 898 | function userError (message) |
| 899 | { |
| 900 | const error = new Error(message); |
| 901 | error.userFacing = true; |
| 902 | return error; |
| 903 | } |