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