| 1 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 2 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 3 | import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js"; |
| 4 | import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; |
| 5 | import { isLetterWrittenBy } from "../../../shared/items/letters.js"; |
| 6 | import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js"; |
| 7 | import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js"; |
| 8 | import { advanceCourierFlight } from "../../../shared/courier/flight.js"; |
| 9 | import { GAIT } from "../../../shared/protocol/constants.js"; |
| 10 | import { decodeChunkBlob } from "../world/chunkData.js"; |
| 11 | import { findReservedChequeIndex } from "../items/bags.js"; |
| 12 | import { randomUUID } from "node:crypto"; |
| 13 | import { |
| 14 | BANK_LETTER_AUTHOR, |
| 15 | bankRestNoticeLetterBody, |
| 16 | isBankRestNoticeLetter, |
| 17 | isCentralExchangeLetter, |
| 18 | itemNameForNotice, |
| 19 | mergeBankRestNoticeLines, |
| 20 | sourceNameForVaultDeposit |
| 21 | } from "../../../shared/courier/bankNotice.js"; |
| 22 | |
| 23 | export class CourierService |
| 24 | { |
| 25 | constructor ({ stateDb, worldDb, simulation }) |
| 26 | { |
| 27 | this.stateDb = stateDb; |
| 28 | this.worldDb = worldDb; |
| 29 | this.simulation = simulation; |
| 30 | this.bankTiles = []; |
| 31 | this.bountyOfficeTiles = []; |
| 32 | this.refreshBankIndex(); |
| 33 | this.refreshBountyOfficeIndex(); |
| 34 | } |
| 35 | |
| 36 | refreshBankIndex () |
| 37 | { |
| 38 | this.bankTiles = this.#listBlockTiles(BlockType.bank); |
| 39 | } |
| 40 | |
| 41 | refreshBountyOfficeIndex () |
| 42 | { |
| 43 | this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice); |
| 44 | } |
| 45 | |
| 46 | #listBlockTiles (typeId) |
| 47 | { |
| 48 | const revisionId = this.worldDb.getActiveRevisionId(); |
| 49 | const tiles = []; |
| 50 | for (const coord of this.worldDb.listChunkCoords(revisionId)) |
| 51 | { |
| 52 | const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId); |
| 53 | if (!row) |
| 54 | { continue; } |
| 55 | const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y); |
| 56 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 57 | { |
| 58 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 59 | { |
| 60 | const block = data.blocks[localY * CHUNK_SIZE + localX]; |
| 61 | if (block?.typeId !== typeId) |
| 62 | { continue; } |
| 63 | tiles.push({ |
| 64 | tileX: coord.chunk_x * CHUNK_SIZE + localX, |
| 65 | tileY: coord.chunk_y * CHUNK_SIZE + localY |
| 66 | }); |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | return tiles; |
| 71 | } |
| 72 | |
| 73 | nearestBank (tileX, tileY) |
| 74 | { |
| 75 | return this.#nearestTile(this.bankTiles, tileX, tileY); |
| 76 | } |
| 77 | |
| 78 | nearestBountyOffice (tileX, tileY) |
| 79 | { |
| 80 | return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY); |
| 81 | } |
| 82 | |
| 83 | isAdjacentToBountyOffice (tileX, tileY) |
| 84 | { |
| 85 | return this.bountyOfficeTiles.some((office) => |
| 86 | Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1); |
| 87 | } |
| 88 | |
| 89 | #nearestTile (tiles, tileX, tileY) |
| 90 | { |
| 91 | if (!tiles.length) |
| 92 | { return null; } |
| 93 | let best = null; |
| 94 | let bestDist = Infinity; |
| 95 | for (const tile of tiles) |
| 96 | { |
| 97 | const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY); |
| 98 | if (dist < bestDist) |
| 99 | { |
| 100 | bestDist = dist; |
| 101 | best = tile; |
| 102 | } |
| 103 | } |
| 104 | return best; |
| 105 | } |
| 106 | |
| 107 | /** |
| 108 | * Player dispatch: cargo is money or one inventory stack. |
| 109 | * destination: { kind: "bank" } | { kind: "player", firstName, lastName } |
| 110 | */ |
| 111 | dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo }) |
| 112 | { |
| 113 | const onlineId = this.simulation.characterEntities.get(characterId); |
| 114 | const bag = onlineId |
| 115 | ? this.simulation.bagOf(onlineId) |
| 116 | : this.stateDb.getBag(characterId); |
| 117 | if (!bag) |
| 118 | { |
| 119 | const error = new Error("No bag."); |
| 120 | error.userFacing = true; |
| 121 | throw error; |
| 122 | } |
| 123 | |
| 124 | let takenCargo; |
| 125 | if (cargo?.kind === "item") |
| 126 | { |
| 127 | const slot = bag.inventory?.[cargo.slotIndex | 0]; |
| 128 | if (slot?.itemId === ItemId.blankCheque) |
| 129 | { |
| 130 | const error = new Error("Blank cheques cannot be sent by pigeon."); |
| 131 | error.userFacing = true; |
| 132 | throw error; |
| 133 | } |
| 134 | if (slot?.itemId === ItemId.letter && !isLetterWrittenBy(slot, characterId)) |
| 135 | { |
| 136 | const error = new Error("You can only send letters you wrote."); |
| 137 | error.userFacing = true; |
| 138 | throw error; |
| 139 | } |
| 140 | const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null); |
| 141 | if (!taken.ok || !taken.taken) |
| 142 | { |
| 143 | const error = new Error("That item is not available."); |
| 144 | error.userFacing = true; |
| 145 | throw error; |
| 146 | } |
| 147 | bag.inventory = taken.slots; |
| 148 | const stack = taken.taken; |
| 149 | if (stack.itemId === ItemId.letter && stack.instance) |
| 150 | { stack.instance = { ...stack.instance, opened: false }; } |
| 151 | takenCargo = { kind: "item", stack }; |
| 152 | } |
| 153 | else |
| 154 | { |
| 155 | const error = new Error("Pigeon cargo must be money or one item stack."); |
| 156 | error.userFacing = true; |
| 157 | throw error; |
| 158 | } |
| 159 | |
| 160 | const dest = this.#resolveDestination(destination, originTileX, originTileY); |
| 161 | this.#persistBag(characterId, bag); |
| 162 | const transit = this.stateDb.insertCourierTransit({ |
| 163 | senderCharacterId: characterId, |
| 164 | destinationKind: dest.kind, |
| 165 | destinationCharacterId: dest.characterId ?? null, |
| 166 | vaultCharacterId: dest.vaultCharacterId ?? null, |
| 167 | cargo: takenCargo, |
| 168 | originX: originTileX + 0.5, |
| 169 | originY: originTileY + 0.5, |
| 170 | destX: dest.tileX + 0.5, |
| 171 | destY: dest.tileY + 0.5, |
| 172 | traveled: 0, |
| 173 | status: "in_transit", |
| 174 | entityId: null |
| 175 | }); |
| 176 | return { transit, bag }; |
| 177 | } |
| 178 | |
| 179 | /** |
| 180 | * System letters (gift / CE / bounty): pigeon to the player (inventory; bank if full). |
| 181 | * While offline, hold with player destination so login flies from the bank to the character |
| 182 | * — never deposit the letter straight into the vault. |
| 183 | */ |
| 184 | dispatchSystemLetter ({ characterId, originTileX, originTileY, stack }) |
| 185 | { |
| 186 | const recipientId = characterId | 0; |
| 187 | const cargo = { kind: "item", stack }; |
| 188 | const row = this.stateDb.getCharacter(recipientId); |
| 189 | return this.dispatchHeldCargo({ |
| 190 | senderCharacterId: recipientId, |
| 191 | originTileX, |
| 192 | originTileY, |
| 193 | destination: { |
| 194 | kind: "player", |
| 195 | firstName: row?.first_name ?? "Unknown", |
| 196 | lastName: row?.last_name ?? "" |
| 197 | }, |
| 198 | cargo, |
| 199 | vaultCharacterId: recipientId |
| 200 | }); |
| 201 | } |
| 202 | |
| 203 | /** |
| 204 | * Market / system dispatch already holding cargo (no bag take). |
| 205 | * When the recipient is offline, holds delivery until login (CE letters, etc.). |
| 206 | * Player-bound holds keep destinationKind "player" even though resolve would route to bank |
| 207 | * while offline — on login the pigeon then delivers to the character, not the vault. |
| 208 | */ |
| 209 | dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo, vaultCharacterId = null }) |
| 210 | { |
| 211 | const recipientId = vaultCharacterId ?? senderCharacterId; |
| 212 | if (!this.simulation.isCharacterOnline(recipientId)) |
| 213 | { |
| 214 | const dest = this.#resolveDestination(destination, originTileX, originTileY); |
| 215 | const intendedKind = destination?.kind === "player" ? "player" : dest.kind; |
| 216 | this.stateDb.insertHeldCourierDelivery({ |
| 217 | characterId: recipientId, |
| 218 | senderCharacterId, |
| 219 | originTileX, |
| 220 | originTileY, |
| 221 | destinationKind: intendedKind, |
| 222 | destinationCharacterId: dest.characterId ?? recipientId, |
| 223 | vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId, |
| 224 | cargo |
| 225 | }); |
| 226 | return null; |
| 227 | } |
| 228 | const dest = this.#resolveDestination(destination, originTileX, originTileY); |
| 229 | return this.stateDb.insertCourierTransit({ |
| 230 | senderCharacterId, |
| 231 | destinationKind: dest.kind, |
| 232 | destinationCharacterId: dest.characterId ?? null, |
| 233 | vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null, |
| 234 | cargo, |
| 235 | originX: originTileX + 0.5, |
| 236 | originY: originTileY + 0.5, |
| 237 | destX: dest.tileX + 0.5, |
| 238 | destY: dest.tileY + 0.5, |
| 239 | traveled: 0, |
| 240 | status: "in_transit", |
| 241 | entityId: null |
| 242 | }); |
| 243 | } |
| 244 | |
| 245 | /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */ |
| 246 | onCharacterEnteredWorld (characterId, tileX, tileY) |
| 247 | { |
| 248 | for (const held of this.stateDb.listHeldCourierDeliveries(characterId)) |
| 249 | { |
| 250 | this.stateDb.deleteHeldCourierDelivery(held.holdId); |
| 251 | const row = this.stateDb.getCharacter(held.destinationCharacterId ?? characterId); |
| 252 | this.dispatchHeldCargo({ |
| 253 | senderCharacterId: held.senderCharacterId, |
| 254 | originTileX: held.originTileX, |
| 255 | originTileY: held.originTileY, |
| 256 | destination: held.destinationKind === "bank" |
| 257 | ? { kind: "bank" } |
| 258 | : { |
| 259 | kind: "player", |
| 260 | firstName: row?.first_name ?? "Unknown", |
| 261 | lastName: row?.last_name ?? "" |
| 262 | }, |
| 263 | cargo: held.cargo, |
| 264 | vaultCharacterId: held.vaultCharacterId ?? characterId |
| 265 | }); |
| 266 | } |
| 267 | const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY); |
| 268 | void noticeTransit; |
| 269 | } |
| 270 | |
| 271 | step (now, dt) |
| 272 | { |
| 273 | const events = []; |
| 274 | const settings = this.simulation.settings; |
| 275 | for (const transit of this.stateDb.listActiveCourierTransits()) |
| 276 | { |
| 277 | this.#retargetPlayerDest(transit); |
| 278 | const advanced = advanceCourierFlight({ |
| 279 | originX: transit.originX, |
| 280 | originY: transit.originY, |
| 281 | destX: transit.destX, |
| 282 | destY: transit.destY, |
| 283 | traveled: transit.traveled, |
| 284 | dt, |
| 285 | settings |
| 286 | }); |
| 287 | transit.traveled = advanced.traveled; |
| 288 | transit.updatedAt = now; |
| 289 | |
| 290 | if (advanced.arrived) |
| 291 | { |
| 292 | events.push(...this.#deliver(transit, now)); |
| 293 | continue; |
| 294 | } |
| 295 | |
| 296 | events.push(...this.#syncVisiblePigeon(transit, advanced, now)); |
| 297 | this.stateDb.updateCourierTransit(transit); |
| 298 | } |
| 299 | return events; |
| 300 | } |
| 301 | |
| 302 | #retargetPlayerDest (transit) |
| 303 | { |
| 304 | if (transit.destinationKind !== "player" || !transit.destinationCharacterId) |
| 305 | { return; } |
| 306 | const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId); |
| 307 | if (onlineId) |
| 308 | { |
| 309 | const pos = this.simulation.positionOf(onlineId); |
| 310 | if (pos) |
| 311 | { |
| 312 | transit.destX = pos.tileX + 0.5; |
| 313 | transit.destY = pos.tileY + 0.5; |
| 314 | } |
| 315 | return; |
| 316 | } |
| 317 | this.#routeTransitToBank(transit, transit.destinationCharacterId); |
| 318 | } |
| 319 | |
| 320 | #routeTransitToBank (transit, vaultCharacterId) |
| 321 | { |
| 322 | const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY)) |
| 323 | ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY)); |
| 324 | if (!bank) |
| 325 | { return; } |
| 326 | transit.destinationKind = "bank"; |
| 327 | transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId; |
| 328 | transit.destX = bank.tileX + 0.5; |
| 329 | transit.destY = bank.tileY + 0.5; |
| 330 | } |
| 331 | |
| 332 | #resolveDestination (destination, originTileX, originTileY) |
| 333 | { |
| 334 | if (destination?.kind === "player") |
| 335 | { |
| 336 | const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName); |
| 337 | if (!character) |
| 338 | { |
| 339 | const error = new Error("No character with that name."); |
| 340 | error.userFacing = true; |
| 341 | throw error; |
| 342 | } |
| 343 | const onlineId = this.simulation.characterEntities.get(character.character_id); |
| 344 | if (!onlineId) |
| 345 | { |
| 346 | const bank = this.nearestBank(originTileX, originTileY) |
| 347 | ?? this.nearestBank(character.tile_x, character.tile_y); |
| 348 | if (!bank) |
| 349 | { |
| 350 | const error = new Error("No bank exists in the world yet."); |
| 351 | error.userFacing = true; |
| 352 | throw error; |
| 353 | } |
| 354 | return { |
| 355 | kind: "bank", |
| 356 | characterId: character.character_id, |
| 357 | vaultCharacterId: character.character_id, |
| 358 | tileX: bank.tileX, |
| 359 | tileY: bank.tileY |
| 360 | }; |
| 361 | } |
| 362 | const pos = this.simulation.positionOf(onlineId); |
| 363 | return { |
| 364 | kind: "player", |
| 365 | characterId: character.character_id, |
| 366 | tileX: pos.tileX, |
| 367 | tileY: pos.tileY |
| 368 | }; |
| 369 | } |
| 370 | if (destination?.kind === "bank") |
| 371 | { |
| 372 | const bank = this.nearestBank(originTileX, originTileY); |
| 373 | if (!bank) |
| 374 | { |
| 375 | const error = new Error("No bank exists in the world yet."); |
| 376 | error.userFacing = true; |
| 377 | throw error; |
| 378 | } |
| 379 | return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY }; |
| 380 | } |
| 381 | const error = new Error("Pigeon destination must be bank or player."); |
| 382 | error.userFacing = true; |
| 383 | throw error; |
| 384 | } |
| 385 | |
| 386 | #syncVisiblePigeon (transit, advanced, now) |
| 387 | { |
| 388 | const events = []; |
| 389 | const tileX = Math.floor(advanced.x); |
| 390 | const tileY = Math.floor(advanced.y); |
| 391 | if (!this.simulation.chunkIsSimulating(tileX, tileY)) |
| 392 | { |
| 393 | if (transit.entityId) |
| 394 | { |
| 395 | this.simulation.despawnEntity(transit.entityId); |
| 396 | events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY }); |
| 397 | transit.entityId = null; |
| 398 | } |
| 399 | return events; |
| 400 | } |
| 401 | |
| 402 | if (!transit.entityId || !this.simulation.entityRecord(transit.entityId)) |
| 403 | { |
| 404 | transit.entityId = null; |
| 405 | const def = mobDefinition(MobId.pigeon); |
| 406 | const entityId = this.simulation.spawnEntity({ |
| 407 | position: { tileX, tileY }, |
| 408 | movement: { gait: GAIT.walk, walkCarry: 0 }, |
| 409 | path: { tiles: [] }, |
| 410 | flight: { |
| 411 | x: advanced.x, |
| 412 | y: advanced.y, |
| 413 | targetX: transit.destX, |
| 414 | targetY: transit.destY, |
| 415 | speed: advanced.speed, |
| 416 | nextPickAt: now + 60_000, |
| 417 | lastAt: now, |
| 418 | courierId: transit.courierId |
| 419 | }, |
| 420 | appearance: { |
| 421 | sex: def.sex, |
| 422 | firstName: def.displayName, |
| 423 | lastName: "", |
| 424 | sprite: mobSpriteName(MobId.pigeon) |
| 425 | }, |
| 426 | creature: { mobTypeId: MobId.pigeon }, |
| 427 | health: { current: 1, max: 1 } |
| 428 | }, { requireResident: true }); |
| 429 | if (entityId != null) |
| 430 | { transit.entityId = entityId; } |
| 431 | return events; |
| 432 | } |
| 433 | |
| 434 | const moved = this.simulation.updateCourierFlight(transit.entityId, { |
| 435 | x: advanced.x, |
| 436 | y: advanced.y, |
| 437 | targetX: transit.destX, |
| 438 | targetY: transit.destY, |
| 439 | speed: advanced.speed, |
| 440 | lastAt: now, |
| 441 | courierId: transit.courierId |
| 442 | }, now); |
| 443 | if (moved?.despawned) |
| 444 | { |
| 445 | transit.entityId = null; |
| 446 | events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY }); |
| 447 | } |
| 448 | else if (moved?.event) |
| 449 | { events.push(moved.event); } |
| 450 | return events; |
| 451 | } |
| 452 | |
| 453 | #deliver (transit, now) |
| 454 | { |
| 455 | const events = []; |
| 456 | if (transit.entityId) |
| 457 | { |
| 458 | this.simulation.despawnEntity(transit.entityId); |
| 459 | events.push({ |
| 460 | type: "entity-despawn", |
| 461 | entityId: transit.entityId, |
| 462 | tileX: Math.floor(transit.destX), |
| 463 | tileY: Math.floor(transit.destY) |
| 464 | }); |
| 465 | transit.entityId = null; |
| 466 | } |
| 467 | |
| 468 | if (transit.destinationKind === "bank") |
| 469 | { |
| 470 | const vaultCharacterId = transit.vaultCharacterId |
| 471 | ?? transit.destinationCharacterId |
| 472 | ?? transit.senderCharacterId; |
| 473 | const toast = this.#creditVault(vaultCharacterId, transit.cargo, { |
| 474 | senderCharacterId: transit.senderCharacterId |
| 475 | }); |
| 476 | if (toast) |
| 477 | { events.push(toast); } |
| 478 | } |
| 479 | else if (transit.destinationKind === "player") |
| 480 | { |
| 481 | const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo); |
| 482 | if (!delivered) |
| 483 | { |
| 484 | const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY)) |
| 485 | ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY)); |
| 486 | if (bank) |
| 487 | { |
| 488 | transit.originX = transit.destX; |
| 489 | transit.originY = transit.destY; |
| 490 | transit.destX = bank.tileX + 0.5; |
| 491 | transit.destY = bank.tileY + 0.5; |
| 492 | transit.traveled = 0; |
| 493 | transit.destinationKind = "bank"; |
| 494 | transit.vaultCharacterId = transit.destinationCharacterId; |
| 495 | transit.updatedAt = now; |
| 496 | this.stateDb.updateCourierTransit(transit); |
| 497 | events.push({ |
| 498 | type: "pigeon-reroute-bank", |
| 499 | courierId: transit.courierId, |
| 500 | characterId: transit.destinationCharacterId |
| 501 | }); |
| 502 | return events; |
| 503 | } |
| 504 | const toast = this.#creditVault(transit.destinationCharacterId, transit.cargo, { |
| 505 | senderCharacterId: transit.senderCharacterId |
| 506 | }); |
| 507 | if (toast) |
| 508 | { events.push(toast); } |
| 509 | } |
| 510 | else |
| 511 | { |
| 512 | events.push({ |
| 513 | type: "item-bubble", |
| 514 | entityId: delivered.entityId, |
| 515 | itemId: delivered.itemId, |
| 516 | quantity: delivered.quantity |
| 517 | }); |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | transit.status = "delivered"; |
| 522 | transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY); |
| 523 | transit.updatedAt = now; |
| 524 | this.stateDb.updateCourierTransit(transit); |
| 525 | events.push({ |
| 526 | type: "pigeon-delivered", |
| 527 | courierId: transit.courierId, |
| 528 | senderCharacterId: transit.senderCharacterId, |
| 529 | destinationKind: transit.destinationKind, |
| 530 | destinationCharacterId: transit.destinationCharacterId, |
| 531 | cargo: transit.cargo |
| 532 | }); |
| 533 | return events; |
| 534 | } |
| 535 | |
| 536 | #normalizeCargo (cargo) |
| 537 | { |
| 538 | if (cargo?.kind === "money") |
| 539 | { |
| 540 | return { |
| 541 | kind: "item", |
| 542 | stack: attachOrigins({ itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) }) |
| 543 | }; |
| 544 | } |
| 545 | return cargo; |
| 546 | } |
| 547 | |
| 548 | #tryDeliverToPlayer (characterId, cargo) |
| 549 | { |
| 550 | cargo = this.#normalizeCargo(cargo); |
| 551 | const onlineId = this.simulation.characterEntities.get(characterId); |
| 552 | if (!onlineId) |
| 553 | { return null; } |
| 554 | if (cargo.kind === "item") |
| 555 | { |
| 556 | const bag = this.simulation.bagOf(onlineId); |
| 557 | if (!bag) |
| 558 | { return null; } |
| 559 | const def = itemDefinition(cargo.stack.itemId); |
| 560 | const result = insertStack(bag.inventory, cargo.stack, def); |
| 561 | if (!result.ok || result.remainder) |
| 562 | { return null; } |
| 563 | bag.inventory = result.slots; |
| 564 | this.#persistBag(characterId, bag); |
| 565 | return { |
| 566 | entityId: onlineId, |
| 567 | itemId: cargo.stack.itemId, |
| 568 | quantity: Math.max(1, cargo.stack.quantity | 0 || 1) |
| 569 | }; |
| 570 | } |
| 571 | return null; |
| 572 | } |
| 573 | |
| 574 | #creditVault (characterId, cargo, { senderCharacterId = null, recordRestNotice = true } = {}) |
| 575 | { |
| 576 | cargo = this.#normalizeCargo(cargo); |
| 577 | const onlineId = this.simulation.characterEntities.get(characterId); |
| 578 | const bag = onlineId |
| 579 | ? this.simulation.bagOf(onlineId) |
| 580 | : this.stateDb.getBag(characterId); |
| 581 | if (!bag) |
| 582 | { return null; } |
| 583 | if (cargo.kind !== "item") |
| 584 | { return null; } |
| 585 | |
| 586 | const stack = cargo.stack; |
| 587 | const isCeLetter = stack?.itemId === ItemId.letter && isCentralExchangeLetter(stack.instance); |
| 588 | const isRestNoticeLetter = stack?.itemId === ItemId.letter && isBankRestNoticeLetter(stack.instance); |
| 589 | |
| 590 | if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque") |
| 591 | { |
| 592 | this.#redeemChequeIntoVault(characterId, bag, stack); |
| 593 | this.#maybeRecordRestNotice({ |
| 594 | characterId, |
| 595 | stack, |
| 596 | senderCharacterId, |
| 597 | recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter |
| 598 | }); |
| 599 | return null; |
| 600 | } |
| 601 | |
| 602 | const def = itemDefinition(stack.itemId); |
| 603 | const vault = normalizeVault( |
| 604 | bag.vaultReserved != null |
| 605 | ? { slots: bag.vault, reserved: bag.vaultReserved } |
| 606 | : bag.vault |
| 607 | ); |
| 608 | const result = insertStackGrowable(vault.slots, stack, def); |
| 609 | bag.vault = result.slots; |
| 610 | bag.vaultReserved = vault.reserved; |
| 611 | this.#persistBag(characterId, bag); |
| 612 | |
| 613 | this.#maybeRecordRestNotice({ |
| 614 | characterId, |
| 615 | stack, |
| 616 | senderCharacterId, |
| 617 | recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter |
| 618 | }); |
| 619 | |
| 620 | if (onlineId && isRestNoticeLetter) |
| 621 | { |
| 622 | return { |
| 623 | type: "toast", |
| 624 | characterId, |
| 625 | message: "A letter arrived for you at the bank." |
| 626 | }; |
| 627 | } |
| 628 | return null; |
| 629 | } |
| 630 | |
| 631 | #maybeRecordRestNotice ({ characterId, stack, senderCharacterId, recordRestNotice }) |
| 632 | { |
| 633 | if (!recordRestNotice || !stack) |
| 634 | { return; } |
| 635 | const sender = senderCharacterId ? this.stateDb.getCharacter(senderCharacterId) : null; |
| 636 | const senderDisplayName = sender |
| 637 | ? `${sender.first_name} ${sender.last_name}`.trim() |
| 638 | : null; |
| 639 | this.stateDb.appendBankRestNotice(characterId, { |
| 640 | itemId: stack.itemId, |
| 641 | itemName: itemNameForNotice(stack), |
| 642 | quantity: stack.quantity | 0 || 1, |
| 643 | sourceName: sourceNameForVaultDeposit(stack, senderCharacterId, senderDisplayName) |
| 644 | }); |
| 645 | } |
| 646 | |
| 647 | /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */ |
| 648 | #redeemChequeIntoVault (characterId, bag, chequeStack) |
| 649 | { |
| 650 | const instance = chequeStack.instance; |
| 651 | const issuerId = instance.issuerCharacterId; |
| 652 | const goodsDef = itemDefinition(instance.itemId); |
| 653 | if (!goodsDef) |
| 654 | { return; } |
| 655 | |
| 656 | let reservedStack = null; |
| 657 | if (Number(issuerId) === Number(characterId)) |
| 658 | { |
| 659 | const reserved = [...(bag.vaultReserved ?? [])]; |
| 660 | const index = findReservedChequeIndex(reserved, instance); |
| 661 | if (index < 0) |
| 662 | { |
| 663 | // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost. |
| 664 | const def = itemDefinition(ItemId.filledCheque); |
| 665 | const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); |
| 666 | const result = insertStackGrowable(vault.slots, chequeStack, def); |
| 667 | bag.vault = result.slots; |
| 668 | bag.vaultReserved = vault.reserved; |
| 669 | this.#persistBag(characterId, bag); |
| 670 | return; |
| 671 | } |
| 672 | reservedStack = reserved[index]; |
| 673 | reserved.splice(index, 1); |
| 674 | bag.vaultReserved = reserved; |
| 675 | } |
| 676 | else |
| 677 | { |
| 678 | const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance); |
| 679 | if (!release?.ok) |
| 680 | { |
| 681 | const def = itemDefinition(ItemId.filledCheque); |
| 682 | const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); |
| 683 | const result = insertStackGrowable(vault.slots, chequeStack, def); |
| 684 | bag.vault = result.slots; |
| 685 | bag.vaultReserved = vault.reserved; |
| 686 | this.#persistBag(characterId, bag); |
| 687 | return; |
| 688 | } |
| 689 | reservedStack = release.stack; |
| 690 | } |
| 691 | |
| 692 | const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); |
| 693 | const goodsStack = attachOrigins({ |
| 694 | itemId: reservedStack.itemId, |
| 695 | quantity: reservedStack.quantity, |
| 696 | origins: normalizeOrigins(reservedStack), |
| 697 | instance: reservedStack.instance ?? null |
| 698 | }); |
| 699 | const inserted = insertStackGrowable(vault.slots, goodsStack, goodsDef); |
| 700 | bag.vault = inserted.slots; |
| 701 | bag.vaultReserved = vault.reserved; |
| 702 | this.#persistBag(characterId, bag); |
| 703 | this.#maybeRecordRestNotice({ |
| 704 | characterId, |
| 705 | stack: goodsStack, |
| 706 | senderCharacterId: null, |
| 707 | recordRestNotice: !this.simulation.characterEntities.get(characterId) |
| 708 | }); |
| 709 | } |
| 710 | |
| 711 | #persistBag (characterId, bag) |
| 712 | { |
| 713 | this.stateDb.saveBag(characterId, bag); |
| 714 | const onlineId = this.simulation.characterEntities.get(characterId); |
| 715 | if (onlineId) |
| 716 | { |
| 717 | this.simulation.applyBag(onlineId, bag); |
| 718 | this.simulation.pushInventory(characterId, bag); |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | #characterDisplayName (characterId) |
| 723 | { |
| 724 | const row = this.stateDb.getCharacter(characterId); |
| 725 | return { |
| 726 | firstName: row?.first_name ?? "Unknown", |
| 727 | lastName: row?.last_name ?? "", |
| 728 | full: row ? `${row.first_name} ${row.last_name}`.trim() : "Adventurer" |
| 729 | }; |
| 730 | } |
| 731 | |
| 732 | #dispatchBankRestNotice (characterId, tileX, tileY) |
| 733 | { |
| 734 | const entries = this.stateDb.listBankRestNotices(characterId); |
| 735 | if (!entries.length) |
| 736 | { return null; } |
| 737 | const bank = this.nearestBank(tileX, tileY); |
| 738 | if (!bank) |
| 739 | { return null; } |
| 740 | |
| 741 | const lines = mergeBankRestNoticeLines(entries.map((entry) => ({ |
| 742 | quantity: entry.quantity, |
| 743 | itemName: entry.itemName, |
| 744 | sourceName: entry.sourceName |
| 745 | }))); |
| 746 | const { full: playerName } = this.#characterDisplayName(characterId); |
| 747 | const body = bankRestNoticeLetterBody({ playerName, lines }); |
| 748 | const stack = attachOrigins({ |
| 749 | itemId: ItemId.letter, |
| 750 | quantity: 1, |
| 751 | origins: [{ origin: writtenOrigin(BANK_LETTER_AUTHOR), quantity: 1 }], |
| 752 | instance: { |
| 753 | kind: "letter", |
| 754 | letterId: randomUUID(), |
| 755 | authorCharacterId: 0, |
| 756 | authorDisplayName: BANK_LETTER_AUTHOR, |
| 757 | body, |
| 758 | opened: false, |
| 759 | writtenAt: Date.now(), |
| 760 | bankRestNotice: true |
| 761 | } |
| 762 | }); |
| 763 | this.stateDb.clearBankRestNotices(characterId); |
| 764 | return this.stateDb.insertCourierTransit({ |
| 765 | senderCharacterId: characterId, |
| 766 | destinationKind: "player", |
| 767 | destinationCharacterId: characterId, |
| 768 | vaultCharacterId: characterId, |
| 769 | cargo: { kind: "item", stack }, |
| 770 | originX: bank.tileX + 0.5, |
| 771 | originY: bank.tileY + 0.5, |
| 772 | destX: tileX + 0.5, |
| 773 | destY: tileY + 0.5, |
| 774 | traveled: 0, |
| 775 | status: "in_transit", |
| 776 | entityId: null |
| 777 | }); |
| 778 | } |
| 779 | } |