import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js"; import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; import { isLetterWrittenBy } from "../../../shared/items/letters.js"; import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js"; import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js"; import { advanceCourierFlight } from "../../../shared/courier/flight.js"; import { GAIT } from "../../../shared/protocol/constants.js"; import { decodeChunkBlob } from "../world/chunkData.js"; import { findReservedChequeIndex } from "../items/bags.js"; import { randomUUID } from "node:crypto"; import { BANK_LETTER_AUTHOR, bankRestNoticeLetterBody, isBankRestNoticeLetter, isCentralExchangeLetter, itemNameForNotice, mergeBankRestNoticeLines, sourceNameForVaultDeposit } from "../../../shared/courier/bankNotice.js"; export class CourierService { constructor ({ stateDb, worldDb, simulation }) { this.stateDb = stateDb; this.worldDb = worldDb; this.simulation = simulation; this.bankTiles = []; this.bountyOfficeTiles = []; this.refreshBankIndex(); this.refreshBountyOfficeIndex(); } refreshBankIndex () { this.bankTiles = this.#listBlockTiles(BlockType.bank); } refreshBountyOfficeIndex () { this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice); } #listBlockTiles (typeId) { const revisionId = this.worldDb.getActiveRevisionId(); const tiles = []; for (const coord of this.worldDb.listChunkCoords(revisionId)) { const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId); if (!row) { continue; } const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y); for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const block = data.blocks[localY * CHUNK_SIZE + localX]; if (block?.typeId !== typeId) { continue; } tiles.push({ tileX: coord.chunk_x * CHUNK_SIZE + localX, tileY: coord.chunk_y * CHUNK_SIZE + localY }); } } } return tiles; } nearestBank (tileX, tileY) { return this.#nearestTile(this.bankTiles, tileX, tileY); } nearestBountyOffice (tileX, tileY) { return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY); } isAdjacentToBountyOffice (tileX, tileY) { return this.bountyOfficeTiles.some((office) => Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1); } #nearestTile (tiles, tileX, tileY) { if (!tiles.length) { return null; } let best = null; let bestDist = Infinity; for (const tile of tiles) { const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY); if (dist < bestDist) { bestDist = dist; best = tile; } } return best; } /** * Player dispatch: cargo is money or one inventory stack. * destination: { kind: "bank" } | { kind: "player", firstName, lastName } */ dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo }) { const onlineId = this.simulation.characterEntities.get(characterId); const bag = onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); if (!bag) { const error = new Error("No bag."); error.userFacing = true; throw error; } let takenCargo; if (cargo?.kind === "item") { const slot = bag.inventory?.[cargo.slotIndex | 0]; if (slot?.itemId === ItemId.blankCheque) { const error = new Error("Blank cheques cannot be sent by pigeon."); error.userFacing = true; throw error; } if (slot?.itemId === ItemId.letter && !isLetterWrittenBy(slot, characterId)) { const error = new Error("You can only send letters you wrote."); error.userFacing = true; throw error; } const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null); if (!taken.ok || !taken.taken) { const error = new Error("That item is not available."); error.userFacing = true; throw error; } bag.inventory = taken.slots; const stack = taken.taken; if (stack.itemId === ItemId.letter && stack.instance) { stack.instance = { ...stack.instance, opened: false }; } takenCargo = { kind: "item", stack }; } else { const error = new Error("Pigeon cargo must be money or one item stack."); error.userFacing = true; throw error; } const dest = this.#resolveDestination(destination, originTileX, originTileY); this.#persistBag(characterId, bag); const transit = this.stateDb.insertCourierTransit({ senderCharacterId: characterId, destinationKind: dest.kind, destinationCharacterId: dest.characterId ?? null, vaultCharacterId: dest.vaultCharacterId ?? null, cargo: takenCargo, originX: originTileX + 0.5, originY: originTileY + 0.5, destX: dest.tileX + 0.5, destY: dest.tileY + 0.5, traveled: 0, status: "in_transit", entityId: null }); return { transit, bag }; } /** * System letters (gift / CE / bounty): pigeon to the player (inventory; bank if full). * While offline, hold with player destination so login flies from the bank to the character * — never deposit the letter straight into the vault. */ dispatchSystemLetter ({ characterId, originTileX, originTileY, stack }) { const recipientId = characterId | 0; const cargo = { kind: "item", stack }; const row = this.stateDb.getCharacter(recipientId); return this.dispatchHeldCargo({ senderCharacterId: recipientId, originTileX, originTileY, destination: { kind: "player", firstName: row?.first_name ?? "Unknown", lastName: row?.last_name ?? "" }, cargo, vaultCharacterId: recipientId }); } /** * Market / system dispatch already holding cargo (no bag take). * When the recipient is offline, holds delivery until login (CE letters, etc.). * Player-bound holds keep destinationKind "player" even though resolve would route to bank * while offline — on login the pigeon then delivers to the character, not the vault. */ dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo, vaultCharacterId = null }) { const recipientId = vaultCharacterId ?? senderCharacterId; if (!this.simulation.isCharacterOnline(recipientId)) { const dest = this.#resolveDestination(destination, originTileX, originTileY); const intendedKind = destination?.kind === "player" ? "player" : dest.kind; this.stateDb.insertHeldCourierDelivery({ characterId: recipientId, senderCharacterId, originTileX, originTileY, destinationKind: intendedKind, destinationCharacterId: dest.characterId ?? recipientId, vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId, cargo }); return null; } const dest = this.#resolveDestination(destination, originTileX, originTileY); return this.stateDb.insertCourierTransit({ senderCharacterId, destinationKind: dest.kind, destinationCharacterId: dest.characterId ?? null, vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null, cargo, originX: originTileX + 0.5, originY: originTileY + 0.5, destX: dest.tileX + 0.5, destY: dest.tileY + 0.5, traveled: 0, status: "in_transit", entityId: null }); } /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */ onCharacterEnteredWorld (characterId, tileX, tileY) { for (const held of this.stateDb.listHeldCourierDeliveries(characterId)) { this.stateDb.deleteHeldCourierDelivery(held.holdId); const row = this.stateDb.getCharacter(held.destinationCharacterId ?? characterId); this.dispatchHeldCargo({ senderCharacterId: held.senderCharacterId, originTileX: held.originTileX, originTileY: held.originTileY, destination: held.destinationKind === "bank" ? { kind: "bank" } : { kind: "player", firstName: row?.first_name ?? "Unknown", lastName: row?.last_name ?? "" }, cargo: held.cargo, vaultCharacterId: held.vaultCharacterId ?? characterId }); } const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY); void noticeTransit; } step (now, dt) { const events = []; const settings = this.simulation.settings; for (const transit of this.stateDb.listActiveCourierTransits()) { this.#retargetPlayerDest(transit); const advanced = advanceCourierFlight({ originX: transit.originX, originY: transit.originY, destX: transit.destX, destY: transit.destY, traveled: transit.traveled, dt, settings }); transit.traveled = advanced.traveled; transit.updatedAt = now; if (advanced.arrived) { events.push(...this.#deliver(transit, now)); continue; } events.push(...this.#syncVisiblePigeon(transit, advanced, now)); this.stateDb.updateCourierTransit(transit); } return events; } #retargetPlayerDest (transit) { if (transit.destinationKind !== "player" || !transit.destinationCharacterId) { return; } const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId); if (onlineId) { const pos = this.simulation.positionOf(onlineId); if (pos) { transit.destX = pos.tileX + 0.5; transit.destY = pos.tileY + 0.5; } return; } this.#routeTransitToBank(transit, transit.destinationCharacterId); } #routeTransitToBank (transit, vaultCharacterId) { const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY)) ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY)); if (!bank) { return; } transit.destinationKind = "bank"; transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId; transit.destX = bank.tileX + 0.5; transit.destY = bank.tileY + 0.5; } #resolveDestination (destination, originTileX, originTileY) { if (destination?.kind === "player") { const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName); if (!character) { const error = new Error("No character with that name."); error.userFacing = true; throw error; } const onlineId = this.simulation.characterEntities.get(character.character_id); if (!onlineId) { const bank = this.nearestBank(originTileX, originTileY) ?? this.nearestBank(character.tile_x, character.tile_y); if (!bank) { const error = new Error("No bank exists in the world yet."); error.userFacing = true; throw error; } return { kind: "bank", characterId: character.character_id, vaultCharacterId: character.character_id, tileX: bank.tileX, tileY: bank.tileY }; } const pos = this.simulation.positionOf(onlineId); return { kind: "player", characterId: character.character_id, tileX: pos.tileX, tileY: pos.tileY }; } if (destination?.kind === "bank") { const bank = this.nearestBank(originTileX, originTileY); if (!bank) { const error = new Error("No bank exists in the world yet."); error.userFacing = true; throw error; } return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY }; } const error = new Error("Pigeon destination must be bank or player."); error.userFacing = true; throw error; } #syncVisiblePigeon (transit, advanced, now) { const events = []; const tileX = Math.floor(advanced.x); const tileY = Math.floor(advanced.y); if (!this.simulation.chunkIsSimulating(tileX, tileY)) { if (transit.entityId) { this.simulation.despawnEntity(transit.entityId); events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY }); transit.entityId = null; } return events; } if (!transit.entityId || !this.simulation.entityRecord(transit.entityId)) { transit.entityId = null; const def = mobDefinition(MobId.pigeon); const entityId = this.simulation.spawnEntity({ position: { tileX, tileY }, movement: { gait: GAIT.walk, walkCarry: 0 }, path: { tiles: [] }, flight: { x: advanced.x, y: advanced.y, targetX: transit.destX, targetY: transit.destY, speed: advanced.speed, nextPickAt: now + 60_000, lastAt: now, courierId: transit.courierId }, appearance: { sex: def.sex, firstName: def.displayName, lastName: "", sprite: mobSpriteName(MobId.pigeon) }, creature: { mobTypeId: MobId.pigeon }, health: { current: 1, max: 1 } }, { requireResident: true }); if (entityId != null) { transit.entityId = entityId; } return events; } const moved = this.simulation.updateCourierFlight(transit.entityId, { x: advanced.x, y: advanced.y, targetX: transit.destX, targetY: transit.destY, speed: advanced.speed, lastAt: now, courierId: transit.courierId }, now); if (moved?.despawned) { transit.entityId = null; events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY }); } else if (moved?.event) { events.push(moved.event); } return events; } #deliver (transit, now) { const events = []; if (transit.entityId) { this.simulation.despawnEntity(transit.entityId); events.push({ type: "entity-despawn", entityId: transit.entityId, tileX: Math.floor(transit.destX), tileY: Math.floor(transit.destY) }); transit.entityId = null; } if (transit.destinationKind === "bank") { const vaultCharacterId = transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId; const toast = this.#creditVault(vaultCharacterId, transit.cargo, { senderCharacterId: transit.senderCharacterId }); if (toast) { events.push(toast); } } else if (transit.destinationKind === "player") { const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo); if (!delivered) { const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY)) ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY)); if (bank) { transit.originX = transit.destX; transit.originY = transit.destY; transit.destX = bank.tileX + 0.5; transit.destY = bank.tileY + 0.5; transit.traveled = 0; transit.destinationKind = "bank"; transit.vaultCharacterId = transit.destinationCharacterId; transit.updatedAt = now; this.stateDb.updateCourierTransit(transit); events.push({ type: "pigeon-reroute-bank", courierId: transit.courierId, characterId: transit.destinationCharacterId }); return events; } const toast = this.#creditVault(transit.destinationCharacterId, transit.cargo, { senderCharacterId: transit.senderCharacterId }); if (toast) { events.push(toast); } } else { events.push({ type: "item-bubble", entityId: delivered.entityId, itemId: delivered.itemId, quantity: delivered.quantity }); } } transit.status = "delivered"; transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY); transit.updatedAt = now; this.stateDb.updateCourierTransit(transit); events.push({ type: "pigeon-delivered", courierId: transit.courierId, senderCharacterId: transit.senderCharacterId, destinationKind: transit.destinationKind, destinationCharacterId: transit.destinationCharacterId, cargo: transit.cargo }); return events; } #normalizeCargo (cargo) { if (cargo?.kind === "money") { return { kind: "item", stack: attachOrigins({ itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) }) }; } return cargo; } #tryDeliverToPlayer (characterId, cargo) { cargo = this.#normalizeCargo(cargo); const onlineId = this.simulation.characterEntities.get(characterId); if (!onlineId) { return null; } if (cargo.kind === "item") { const bag = this.simulation.bagOf(onlineId); if (!bag) { return null; } const def = itemDefinition(cargo.stack.itemId); const result = insertStack(bag.inventory, cargo.stack, def); if (!result.ok || result.remainder) { return null; } bag.inventory = result.slots; this.#persistBag(characterId, bag); return { entityId: onlineId, itemId: cargo.stack.itemId, quantity: Math.max(1, cargo.stack.quantity | 0 || 1) }; } return null; } #creditVault (characterId, cargo, { senderCharacterId = null, recordRestNotice = true } = {}) { cargo = this.#normalizeCargo(cargo); const onlineId = this.simulation.characterEntities.get(characterId); const bag = onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); if (!bag) { return null; } if (cargo.kind !== "item") { return null; } const stack = cargo.stack; const isCeLetter = stack?.itemId === ItemId.letter && isCentralExchangeLetter(stack.instance); const isRestNoticeLetter = stack?.itemId === ItemId.letter && isBankRestNoticeLetter(stack.instance); if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque") { this.#redeemChequeIntoVault(characterId, bag, stack); this.#maybeRecordRestNotice({ characterId, stack, senderCharacterId, recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter }); return null; } const def = itemDefinition(stack.itemId); const vault = normalizeVault( bag.vaultReserved != null ? { slots: bag.vault, reserved: bag.vaultReserved } : bag.vault ); const result = insertStackGrowable(vault.slots, stack, def); bag.vault = result.slots; bag.vaultReserved = vault.reserved; this.#persistBag(characterId, bag); this.#maybeRecordRestNotice({ characterId, stack, senderCharacterId, recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter }); if (onlineId && isRestNoticeLetter) { return { type: "toast", characterId, message: "A letter arrived for you at the bank." }; } return null; } #maybeRecordRestNotice ({ characterId, stack, senderCharacterId, recordRestNotice }) { if (!recordRestNotice || !stack) { return; } const sender = senderCharacterId ? this.stateDb.getCharacter(senderCharacterId) : null; const senderDisplayName = sender ? `${sender.first_name} ${sender.last_name}`.trim() : null; this.stateDb.appendBankRestNotice(characterId, { itemId: stack.itemId, itemName: itemNameForNotice(stack), quantity: stack.quantity | 0 || 1, sourceName: sourceNameForVaultDeposit(stack, senderCharacterId, senderDisplayName) }); } /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */ #redeemChequeIntoVault (characterId, bag, chequeStack) { const instance = chequeStack.instance; const issuerId = instance.issuerCharacterId; const goodsDef = itemDefinition(instance.itemId); if (!goodsDef) { return; } let reservedStack = null; if (Number(issuerId) === Number(characterId)) { const reserved = [...(bag.vaultReserved ?? [])]; const index = findReservedChequeIndex(reserved, instance); if (index < 0) { // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost. const def = itemDefinition(ItemId.filledCheque); const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); const result = insertStackGrowable(vault.slots, chequeStack, def); bag.vault = result.slots; bag.vaultReserved = vault.reserved; this.#persistBag(characterId, bag); return; } reservedStack = reserved[index]; reserved.splice(index, 1); bag.vaultReserved = reserved; } else { const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance); if (!release?.ok) { const def = itemDefinition(ItemId.filledCheque); const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); const result = insertStackGrowable(vault.slots, chequeStack, def); bag.vault = result.slots; bag.vaultReserved = vault.reserved; this.#persistBag(characterId, bag); return; } reservedStack = release.stack; } const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); const goodsStack = attachOrigins({ itemId: reservedStack.itemId, quantity: reservedStack.quantity, origins: normalizeOrigins(reservedStack), instance: reservedStack.instance ?? null }); const inserted = insertStackGrowable(vault.slots, goodsStack, goodsDef); bag.vault = inserted.slots; bag.vaultReserved = vault.reserved; this.#persistBag(characterId, bag); this.#maybeRecordRestNotice({ characterId, stack: goodsStack, senderCharacterId: null, recordRestNotice: !this.simulation.characterEntities.get(characterId) }); } #persistBag (characterId, bag) { this.stateDb.saveBag(characterId, bag); const onlineId = this.simulation.characterEntities.get(characterId); if (onlineId) { this.simulation.applyBag(onlineId, bag); this.simulation.pushInventory(characterId, bag); } } #characterDisplayName (characterId) { const row = this.stateDb.getCharacter(characterId); return { firstName: row?.first_name ?? "Unknown", lastName: row?.last_name ?? "", full: row ? `${row.first_name} ${row.last_name}`.trim() : "Adventurer" }; } #dispatchBankRestNotice (characterId, tileX, tileY) { const entries = this.stateDb.listBankRestNotices(characterId); if (!entries.length) { return null; } const bank = this.nearestBank(tileX, tileY); if (!bank) { return null; } const lines = mergeBankRestNoticeLines(entries.map((entry) => ({ quantity: entry.quantity, itemName: entry.itemName, sourceName: entry.sourceName }))); const { full: playerName } = this.#characterDisplayName(characterId); const body = bankRestNoticeLetterBody({ playerName, lines }); const stack = attachOrigins({ itemId: ItemId.letter, quantity: 1, origins: [{ origin: writtenOrigin(BANK_LETTER_AUTHOR), quantity: 1 }], instance: { kind: "letter", letterId: randomUUID(), authorCharacterId: 0, authorDisplayName: BANK_LETTER_AUTHOR, body, opened: false, writtenAt: Date.now(), bankRestNotice: true } }); this.stateDb.clearBankRestNotices(characterId); return this.stateDb.insertCourierTransit({ senderCharacterId: characterId, destinationKind: "player", destinationCharacterId: characterId, vaultCharacterId: characterId, cargo: { kind: "item", stack }, originX: bank.tileX + 0.5, originY: bank.tileY + 0.5, destX: tileX + 0.5, destY: tileY + 0.5, traveled: 0, status: "in_transit", entityId: null }); } }