| 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 { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js"; |
| 6 | import { advanceCourierFlight } from "../../../shared/courier/flight.js"; |
| 7 | import { GAIT } from "../../../shared/protocol/constants.js"; |
| 8 | import { decodeChunkBlob } from "../world/chunkData.js"; |
| 9 | import { findReservedChequeIndex } from "../items/bags.js"; |
| 10 | |
| 11 | export class CourierService |
| 12 | { |
| 13 | constructor ({ stateDb, worldDb, simulation }) |
| 14 | { |
| 15 | this.stateDb = stateDb; |
| 16 | this.worldDb = worldDb; |
| 17 | this.simulation = simulation; |
| 18 | this.bankTiles = []; |
| 19 | this.refreshBankIndex(); |
| 20 | } |
| 21 | |
| 22 | refreshBankIndex () |
| 23 | { |
| 24 | const revisionId = this.worldDb.getActiveRevisionId(); |
| 25 | const banks = []; |
| 26 | for (const coord of this.worldDb.listChunkCoords(revisionId)) |
| 27 | { |
| 28 | const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId); |
| 29 | if (!row) |
| 30 | { continue; } |
| 31 | const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId); |
| 32 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 33 | { |
| 34 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 35 | { |
| 36 | const block = data.blocks[localY * CHUNK_SIZE + localX]; |
| 37 | if (block?.typeId !== BlockType.bank) |
| 38 | { continue; } |
| 39 | banks.push({ |
| 40 | tileX: coord.chunk_x * CHUNK_SIZE + localX, |
| 41 | tileY: coord.chunk_y * CHUNK_SIZE + localY |
| 42 | }); |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | this.bankTiles = banks; |
| 47 | } |
| 48 | |
| 49 | nearestBank (tileX, tileY) |
| 50 | { |
| 51 | if (!this.bankTiles.length) |
| 52 | { return null; } |
| 53 | let best = null; |
| 54 | let bestDist = Infinity; |
| 55 | for (const bank of this.bankTiles) |
| 56 | { |
| 57 | const dist = Math.hypot(bank.tileX - tileX, bank.tileY - tileY); |
| 58 | if (dist < bestDist) |
| 59 | { |
| 60 | bestDist = dist; |
| 61 | best = bank; |
| 62 | } |
| 63 | } |
| 64 | return best; |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Player dispatch: cargo is money or one inventory stack. |
| 69 | * destination: { kind: "bank" } | { kind: "player", firstName, lastName } |
| 70 | */ |
| 71 | dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo }) |
| 72 | { |
| 73 | const onlineId = this.simulation.characterEntities.get(characterId); |
| 74 | const bag = onlineId |
| 75 | ? this.simulation.bagOf(onlineId) |
| 76 | : this.stateDb.getBag(characterId); |
| 77 | if (!bag) |
| 78 | { |
| 79 | const error = new Error("No bag."); |
| 80 | error.userFacing = true; |
| 81 | throw error; |
| 82 | } |
| 83 | |
| 84 | let takenCargo; |
| 85 | if (cargo?.kind === "item") |
| 86 | { |
| 87 | const slot = bag.inventory?.[cargo.slotIndex | 0]; |
| 88 | if (slot?.itemId === ItemId.blankCheque) |
| 89 | { |
| 90 | const error = new Error("Blank cheques cannot be sent by pigeon."); |
| 91 | error.userFacing = true; |
| 92 | throw error; |
| 93 | } |
| 94 | if (slot?.itemId === ItemId.letter) |
| 95 | { |
| 96 | if (Number(slot.instance?.authorCharacterId) !== Number(characterId)) |
| 97 | { |
| 98 | const error = new Error("You can only send letters you wrote."); |
| 99 | error.userFacing = true; |
| 100 | throw error; |
| 101 | } |
| 102 | } |
| 103 | const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null); |
| 104 | if (!taken.ok || !taken.taken) |
| 105 | { |
| 106 | const error = new Error("That item is not available."); |
| 107 | error.userFacing = true; |
| 108 | throw error; |
| 109 | } |
| 110 | bag.inventory = taken.slots; |
| 111 | const stack = taken.taken; |
| 112 | if (stack.itemId === ItemId.letter && stack.instance) |
| 113 | { stack.instance = { ...stack.instance, opened: false }; } |
| 114 | takenCargo = { kind: "item", stack }; |
| 115 | } |
| 116 | else |
| 117 | { |
| 118 | const error = new Error("Pigeon cargo must be money or one item stack."); |
| 119 | error.userFacing = true; |
| 120 | throw error; |
| 121 | } |
| 122 | |
| 123 | const dest = this.#resolveDestination(destination, originTileX, originTileY); |
| 124 | this.#persistBag(characterId, bag); |
| 125 | const transit = this.stateDb.insertCourierTransit({ |
| 126 | senderCharacterId: characterId, |
| 127 | destinationKind: dest.kind, |
| 128 | destinationCharacterId: dest.characterId ?? null, |
| 129 | cargo: takenCargo, |
| 130 | originX: originTileX + 0.5, |
| 131 | originY: originTileY + 0.5, |
| 132 | destX: dest.tileX + 0.5, |
| 133 | destY: dest.tileY + 0.5, |
| 134 | traveled: 0, |
| 135 | status: "in_transit", |
| 136 | entityId: null |
| 137 | }); |
| 138 | return { transit, bag }; |
| 139 | } |
| 140 | |
| 141 | /** Market / system dispatch already holding cargo (no bag take). */ |
| 142 | dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo }) |
| 143 | { |
| 144 | const dest = this.#resolveDestination(destination, originTileX, originTileY); |
| 145 | return this.stateDb.insertCourierTransit({ |
| 146 | senderCharacterId, |
| 147 | destinationKind: dest.kind, |
| 148 | destinationCharacterId: dest.characterId ?? null, |
| 149 | cargo, |
| 150 | originX: originTileX + 0.5, |
| 151 | originY: originTileY + 0.5, |
| 152 | destX: dest.tileX + 0.5, |
| 153 | destY: dest.tileY + 0.5, |
| 154 | traveled: 0, |
| 155 | status: "in_transit", |
| 156 | entityId: null |
| 157 | }); |
| 158 | } |
| 159 | |
| 160 | step (now, dt) |
| 161 | { |
| 162 | const events = []; |
| 163 | const settings = this.simulation.settings; |
| 164 | for (const transit of this.stateDb.listActiveCourierTransits()) |
| 165 | { |
| 166 | this.#retargetPlayerDest(transit); |
| 167 | const advanced = advanceCourierFlight({ |
| 168 | originX: transit.originX, |
| 169 | originY: transit.originY, |
| 170 | destX: transit.destX, |
| 171 | destY: transit.destY, |
| 172 | traveled: transit.traveled, |
| 173 | dt, |
| 174 | settings |
| 175 | }); |
| 176 | transit.traveled = advanced.traveled; |
| 177 | transit.updatedAt = now; |
| 178 | |
| 179 | if (advanced.arrived) |
| 180 | { |
| 181 | events.push(...this.#deliver(transit, now)); |
| 182 | continue; |
| 183 | } |
| 184 | |
| 185 | events.push(...this.#syncVisiblePigeon(transit, advanced, now)); |
| 186 | this.stateDb.updateCourierTransit(transit); |
| 187 | } |
| 188 | return events; |
| 189 | } |
| 190 | |
| 191 | #retargetPlayerDest (transit) |
| 192 | { |
| 193 | if (transit.destinationKind !== "player" || !transit.destinationCharacterId) |
| 194 | { return; } |
| 195 | const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId); |
| 196 | if (onlineId) |
| 197 | { |
| 198 | const pos = this.simulation.positionOf(onlineId); |
| 199 | if (pos) |
| 200 | { |
| 201 | transit.destX = pos.tileX + 0.5; |
| 202 | transit.destY = pos.tileY + 0.5; |
| 203 | } |
| 204 | return; |
| 205 | } |
| 206 | const character = this.stateDb.getCharacter(transit.destinationCharacterId); |
| 207 | if (character) |
| 208 | { |
| 209 | transit.destX = character.tile_x + 0.5; |
| 210 | transit.destY = character.tile_y + 0.5; |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | #resolveDestination (destination, originTileX, originTileY) |
| 215 | { |
| 216 | if (destination?.kind === "player") |
| 217 | { |
| 218 | const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName); |
| 219 | if (!character) |
| 220 | { |
| 221 | const error = new Error("No character with that name."); |
| 222 | error.userFacing = true; |
| 223 | throw error; |
| 224 | } |
| 225 | const onlineId = this.simulation.characterEntities.get(character.character_id); |
| 226 | const pos = onlineId ? this.simulation.positionOf(onlineId) : null; |
| 227 | return { |
| 228 | kind: "player", |
| 229 | characterId: character.character_id, |
| 230 | tileX: pos?.tileX ?? character.tile_x, |
| 231 | tileY: pos?.tileY ?? character.tile_y |
| 232 | }; |
| 233 | } |
| 234 | if (destination?.kind === "bank") |
| 235 | { |
| 236 | const bank = this.nearestBank(originTileX, originTileY); |
| 237 | if (!bank) |
| 238 | { |
| 239 | const error = new Error("No bank exists in the world yet."); |
| 240 | error.userFacing = true; |
| 241 | throw error; |
| 242 | } |
| 243 | return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY }; |
| 244 | } |
| 245 | const error = new Error("Pigeon destination must be bank or player."); |
| 246 | error.userFacing = true; |
| 247 | throw error; |
| 248 | } |
| 249 | |
| 250 | #syncVisiblePigeon (transit, advanced, now) |
| 251 | { |
| 252 | const events = []; |
| 253 | const tileX = Math.floor(advanced.x); |
| 254 | const tileY = Math.floor(advanced.y); |
| 255 | if (!this.simulation.chunkIsSimulating(tileX, tileY)) |
| 256 | { |
| 257 | if (transit.entityId) |
| 258 | { |
| 259 | this.simulation.despawnEntity(transit.entityId); |
| 260 | events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY }); |
| 261 | transit.entityId = null; |
| 262 | } |
| 263 | return events; |
| 264 | } |
| 265 | |
| 266 | if (!transit.entityId || !this.simulation.entityRecord(transit.entityId)) |
| 267 | { |
| 268 | transit.entityId = null; |
| 269 | const def = mobDefinition(MobId.pigeon); |
| 270 | const entityId = this.simulation.spawnEntity({ |
| 271 | position: { tileX, tileY }, |
| 272 | movement: { gait: GAIT.walk, walkCarry: 0 }, |
| 273 | path: { tiles: [] }, |
| 274 | flight: { |
| 275 | x: advanced.x, |
| 276 | y: advanced.y, |
| 277 | targetX: transit.destX, |
| 278 | targetY: transit.destY, |
| 279 | speed: advanced.speed, |
| 280 | nextPickAt: now + 60_000, |
| 281 | lastAt: now, |
| 282 | courierId: transit.courierId |
| 283 | }, |
| 284 | appearance: { |
| 285 | sex: def.sex, |
| 286 | firstName: def.displayName, |
| 287 | lastName: "", |
| 288 | sprite: mobSpriteName(MobId.pigeon) |
| 289 | }, |
| 290 | creature: { mobTypeId: MobId.pigeon }, |
| 291 | health: { current: 1, max: 1 } |
| 292 | }, { requireResident: true }); |
| 293 | if (entityId != null) |
| 294 | { transit.entityId = entityId; } |
| 295 | return events; |
| 296 | } |
| 297 | |
| 298 | const moved = this.simulation.updateCourierFlight(transit.entityId, { |
| 299 | x: advanced.x, |
| 300 | y: advanced.y, |
| 301 | targetX: transit.destX, |
| 302 | targetY: transit.destY, |
| 303 | speed: advanced.speed, |
| 304 | lastAt: now, |
| 305 | courierId: transit.courierId |
| 306 | }, now); |
| 307 | if (moved?.despawned) |
| 308 | { |
| 309 | transit.entityId = null; |
| 310 | events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY }); |
| 311 | } |
| 312 | else if (moved?.event) |
| 313 | { events.push(moved.event); } |
| 314 | return events; |
| 315 | } |
| 316 | |
| 317 | #deliver (transit, now) |
| 318 | { |
| 319 | const events = []; |
| 320 | if (transit.entityId) |
| 321 | { |
| 322 | this.simulation.despawnEntity(transit.entityId); |
| 323 | events.push({ |
| 324 | type: "entity-despawn", |
| 325 | entityId: transit.entityId, |
| 326 | tileX: Math.floor(transit.destX), |
| 327 | tileY: Math.floor(transit.destY) |
| 328 | }); |
| 329 | transit.entityId = null; |
| 330 | } |
| 331 | |
| 332 | if (transit.destinationKind === "bank") |
| 333 | { this.#creditVault(transit.senderCharacterId, transit.cargo); } |
| 334 | else if (transit.destinationKind === "player") |
| 335 | { |
| 336 | const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo); |
| 337 | if (!delivered) |
| 338 | { |
| 339 | const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY)) |
| 340 | ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY)); |
| 341 | if (bank) |
| 342 | { |
| 343 | transit.originX = transit.destX; |
| 344 | transit.originY = transit.destY; |
| 345 | transit.destX = bank.tileX + 0.5; |
| 346 | transit.destY = bank.tileY + 0.5; |
| 347 | transit.traveled = 0; |
| 348 | transit.destinationKind = "bank"; |
| 349 | transit.updatedAt = now; |
| 350 | this.stateDb.updateCourierTransit(transit); |
| 351 | events.push({ |
| 352 | type: "pigeon-reroute-bank", |
| 353 | courierId: transit.courierId, |
| 354 | characterId: transit.destinationCharacterId |
| 355 | }); |
| 356 | return events; |
| 357 | } |
| 358 | this.#creditVault(transit.destinationCharacterId, transit.cargo); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | transit.status = "delivered"; |
| 363 | transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY); |
| 364 | transit.updatedAt = now; |
| 365 | this.stateDb.updateCourierTransit(transit); |
| 366 | events.push({ |
| 367 | type: "pigeon-delivered", |
| 368 | courierId: transit.courierId, |
| 369 | senderCharacterId: transit.senderCharacterId, |
| 370 | destinationKind: transit.destinationKind, |
| 371 | destinationCharacterId: transit.destinationCharacterId, |
| 372 | cargo: transit.cargo |
| 373 | }); |
| 374 | return events; |
| 375 | } |
| 376 | |
| 377 | #normalizeCargo (cargo) |
| 378 | { |
| 379 | if (cargo?.kind === "money") |
| 380 | { |
| 381 | return { |
| 382 | kind: "item", |
| 383 | stack: { itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) } |
| 384 | }; |
| 385 | } |
| 386 | return cargo; |
| 387 | } |
| 388 | |
| 389 | #tryDeliverToPlayer (characterId, cargo) |
| 390 | { |
| 391 | cargo = this.#normalizeCargo(cargo); |
| 392 | const onlineId = this.simulation.characterEntities.get(characterId); |
| 393 | if (onlineId) |
| 394 | { |
| 395 | if (cargo.kind === "item") |
| 396 | { |
| 397 | const bag = this.simulation.bagOf(onlineId); |
| 398 | if (!bag) |
| 399 | { return false; } |
| 400 | const def = itemDefinition(cargo.stack.itemId); |
| 401 | const result = insertStack(bag.inventory, cargo.stack, def); |
| 402 | if (!result.ok || result.remainder) |
| 403 | { return false; } |
| 404 | bag.inventory = result.slots; |
| 405 | this.#persistBag(characterId, bag); |
| 406 | return true; |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | if (cargo.kind === "item") |
| 411 | { |
| 412 | this.#creditVault(characterId, cargo); |
| 413 | return true; |
| 414 | } |
| 415 | return false; |
| 416 | } |
| 417 | |
| 418 | #creditVault (characterId, cargo) |
| 419 | { |
| 420 | cargo = this.#normalizeCargo(cargo); |
| 421 | const onlineId = this.simulation.characterEntities.get(characterId); |
| 422 | const bag = onlineId |
| 423 | ? this.simulation.bagOf(onlineId) |
| 424 | : this.stateDb.getBag(characterId); |
| 425 | if (!bag) |
| 426 | { return; } |
| 427 | if (cargo.kind !== "item") |
| 428 | { return; } |
| 429 | |
| 430 | const stack = cargo.stack; |
| 431 | if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque") |
| 432 | { |
| 433 | this.#redeemChequeIntoVault(characterId, bag, stack); |
| 434 | return; |
| 435 | } |
| 436 | |
| 437 | const def = itemDefinition(stack.itemId); |
| 438 | const vault = normalizeVault( |
| 439 | bag.vaultReserved != null |
| 440 | ? { slots: bag.vault, reserved: bag.vaultReserved } |
| 441 | : bag.vault |
| 442 | ); |
| 443 | const result = insertStackGrowable(vault.slots, stack, def); |
| 444 | bag.vault = result.slots; |
| 445 | bag.vaultReserved = vault.reserved; |
| 446 | this.#persistBag(characterId, bag); |
| 447 | } |
| 448 | |
| 449 | /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */ |
| 450 | #redeemChequeIntoVault (characterId, bag, chequeStack) |
| 451 | { |
| 452 | const instance = chequeStack.instance; |
| 453 | const issuerId = instance.issuerCharacterId; |
| 454 | const goodsDef = itemDefinition(instance.itemId); |
| 455 | if (!goodsDef) |
| 456 | { return; } |
| 457 | |
| 458 | let reservedStack = null; |
| 459 | if (Number(issuerId) === Number(characterId)) |
| 460 | { |
| 461 | const reserved = [...(bag.vaultReserved ?? [])]; |
| 462 | const index = findReservedChequeIndex(reserved, instance); |
| 463 | if (index < 0) |
| 464 | { |
| 465 | // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost. |
| 466 | const def = itemDefinition(ItemId.filledCheque); |
| 467 | const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); |
| 468 | const result = insertStackGrowable(vault.slots, chequeStack, def); |
| 469 | bag.vault = result.slots; |
| 470 | bag.vaultReserved = vault.reserved; |
| 471 | this.#persistBag(characterId, bag); |
| 472 | return; |
| 473 | } |
| 474 | reservedStack = reserved[index]; |
| 475 | reserved.splice(index, 1); |
| 476 | bag.vaultReserved = reserved; |
| 477 | } |
| 478 | else |
| 479 | { |
| 480 | const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance); |
| 481 | if (!release?.ok) |
| 482 | { |
| 483 | const def = itemDefinition(ItemId.filledCheque); |
| 484 | const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); |
| 485 | const result = insertStackGrowable(vault.slots, chequeStack, def); |
| 486 | bag.vault = result.slots; |
| 487 | bag.vaultReserved = vault.reserved; |
| 488 | this.#persistBag(characterId, bag); |
| 489 | return; |
| 490 | } |
| 491 | reservedStack = release.stack; |
| 492 | } |
| 493 | |
| 494 | const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); |
| 495 | const inserted = insertStackGrowable(vault.slots, { |
| 496 | itemId: reservedStack.itemId, |
| 497 | quantity: reservedStack.quantity, |
| 498 | origin: reservedStack.origin ?? null, |
| 499 | origins: reservedStack.origins ?? null, |
| 500 | instance: reservedStack.instance ?? null |
| 501 | }, goodsDef); |
| 502 | bag.vault = inserted.slots; |
| 503 | bag.vaultReserved = vault.reserved; |
| 504 | this.#persistBag(characterId, bag); |
| 505 | } |
| 506 | |
| 507 | #persistBag (characterId, bag) |
| 508 | { |
| 509 | this.stateDb.saveBag(characterId, bag); |
| 510 | const onlineId = this.simulation.characterEntities.get(characterId); |
| 511 | if (onlineId) |
| 512 | { |
| 513 | this.simulation.applyBag(onlineId, bag); |
| 514 | this.simulation.pushInventory(characterId, bag); |
| 515 | } |
| 516 | } |
| 517 | } |