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