BlueGit

timfa questward

Files

questward / server / src / courier / service.js

service.js

service.js 33.6 KiB Download Raw
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { isLetterWrittenBy } from "../../../shared/items/letters.js";
6import { insertStack, insertStackGrowable, takeFromSlot, normalizeVault } from "../../../shared/items/inventory.js";
7import { attachOrigins, normalizeOrigins } from "../../../shared/items/origin.js";
8import { advanceCourierFlight } from "../../../shared/courier/flight.js";
9import {
10 buildDoorwayGraph,
11 planPortalLegs,
12 buildFallbackLegs,
13 advanceAbstractTravel,
14 poseOnCourierLeg,
15 ensureCourierLegs
16} from "../../../shared/courier/doorwayGraph.js";
17import { GAIT } from "../../../shared/protocol/constants.js";
18import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
19import { decodeChunkBlob } from "../world/chunkData.js";
20import { findReservedChequeIndex } from "../items/bags.js";
21import {
22 BANK_LETTER_AUTHOR,
23 bankRestNoticeLetterBody,
24 isBankRestNoticeLetter,
25 isCentralExchangeLetter,
26 itemNameForNotice,
27 mergeBankRestNoticeLines,
28 sourceNameForVaultDeposit
29} from "../../../shared/courier/bankNotice.js";
30import { makeSystemLetterStack } from "./systemLetter.js";
31
32export class CourierService
33{
34 constructor ({ stateDb, worldDb, simulation })
35 {
36 this.stateDb = stateDb;
37 this.worldDb = worldDb;
38 this.simulation = simulation;
39 this.bankTiles = [];
40 this.bountyOfficeTiles = [];
41 this.doorwayTiles = [];
42 this.doorwayGraph = buildDoorwayGraph([]);
43 this.refreshBankIndex();
44 this.refreshBountyOfficeIndex();
45 this.refreshDoorwayIndex();
46 }
47
48 refreshBankIndex ()
49 {
50 this.bankTiles = this.#listBlockTiles(BlockType.bank);
51 }
52
53 refreshBountyOfficeIndex ()
54 {
55 this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice);
56 }
57
58 refreshDoorwayIndex ()
59 {
60 this.doorwayTiles = this.#listDoorwayTiles();
61 this.doorwayGraph = buildDoorwayGraph(this.doorwayTiles);
62 }
63
64 #listBlockTiles (typeId)
65 {
66 const revisionId = this.worldDb.getActiveRevisionId();
67 const tiles = [];
68 for (const coord of this.worldDb.listChunkCoords(revisionId))
69 {
70 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
71 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim);
72 if (!row)
73 { continue; }
74 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
75 for (let localY = 0; localY < CHUNK_SIZE; localY++)
76 {
77 for (let localX = 0; localX < CHUNK_SIZE; localX++)
78 {
79 const block = data.blocks[localY * CHUNK_SIZE + localX];
80 if (block?.typeId !== typeId)
81 { continue; }
82 tiles.push({
83 tileX: coord.chunk_x * CHUNK_SIZE + localX,
84 tileY: coord.chunk_y * CHUNK_SIZE + localY,
85 dimensionId: dim
86 });
87 }
88 }
89 }
90 return tiles;
91 }
92
93 #listDoorwayTiles ()
94 {
95 const revisionId = this.worldDb.getActiveRevisionId();
96 const tiles = [];
97 for (const coord of this.worldDb.listChunkCoords(revisionId))
98 {
99 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
100 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim);
101 if (!row)
102 { continue; }
103 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
104 for (let localY = 0; localY < CHUNK_SIZE; localY++)
105 {
106 for (let localX = 0; localX < CHUNK_SIZE; localX++)
107 {
108 const block = data.blocks[localY * CHUNK_SIZE + localX];
109 if (block?.typeId !== BlockType.doorway)
110 { continue; }
111 const config = block.config && typeof block.config === "object" ? block.config : null;
112 tiles.push({
113 tileX: coord.chunk_x * CHUNK_SIZE + localX,
114 tileY: coord.chunk_y * CHUNK_SIZE + localY,
115 dimensionId: dim,
116 targetDimensionId: config?.targetDimensionId,
117 targetTileX: config?.tileX,
118 targetTileY: config?.tileY
119 });
120 }
121 }
122 }
123 return tiles;
124 }
125
126 nearestBank (tileX, tileY, dimensionId = null)
127 {
128 return this.#nearestTile(this.bankTiles, tileX, tileY, dimensionId);
129 }
130
131 nearestBountyOffice (tileX, tileY, dimensionId = null)
132 {
133 return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY, dimensionId);
134 }
135
136 isAdjacentToBountyOffice (tileX, tileY, dimensionId = null)
137 {
138 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
139 return this.bountyOfficeTiles.some((office) =>
140 {
141 if (dim != null && normalizeDimensionId(office.dimensionId ?? OVERWORLD_ID) !== dim)
142 { return false; }
143 return Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1;
144 });
145 }
146
147 /**
148 * Prefer same-dimension tiles when dimensionId is set; otherwise / as fallback, nearest overall.
149 */
150 #nearestTile (tiles, tileX, tileY, dimensionId = null)
151 {
152 if (!tiles.length)
153 { return null; }
154 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
155 let bestSame = null;
156 let bestSameDist = Infinity;
157 let bestAny = null;
158 let bestAnyDist = Infinity;
159 for (const tile of tiles)
160 {
161 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
162 if (dist < bestAnyDist)
163 {
164 bestAnyDist = dist;
165 bestAny = tile;
166 }
167 if (dim != null
168 && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim
169 && dist < bestSameDist)
170 {
171 bestSameDist = dist;
172 bestSame = tile;
173 }
174 }
175 return bestSame ?? bestAny;
176 }
177
178 /**
179 * Player dispatch: cargo is money or one inventory stack.
180 * destination: { kind: "bank" } | { kind: "player", firstName, lastName }
181 */
182 dispatchFromPlayer ({ characterId, originTileX, originTileY, originDimensionId = OVERWORLD_ID, destination, cargo })
183 {
184 const onlineId = this.simulation.characterEntities.get(characterId);
185 const bag = onlineId
186 ? this.simulation.bagOf(onlineId)
187 : this.stateDb.getBag(characterId);
188 if (!bag)
189 {
190 const error = new Error("No bag.");
191 error.userFacing = true;
192 throw error;
193 }
194
195 let takenCargo;
196 if (cargo?.kind === "item")
197 {
198 const slot = bag.inventory?.[cargo.slotIndex | 0];
199 if (slot?.itemId === ItemId.blankCheque)
200 {
201 const error = new Error("Blank cheques cannot be sent by pigeon.");
202 error.userFacing = true;
203 throw error;
204 }
205 if (slot?.itemId === ItemId.letter && !isLetterWrittenBy(slot, characterId))
206 {
207 const error = new Error("You can only send letters you wrote.");
208 error.userFacing = true;
209 throw error;
210 }
211 const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);
212 if (!taken.ok || !taken.taken)
213 {
214 const error = new Error("That item is not available.");
215 error.userFacing = true;
216 throw error;
217 }
218 bag.inventory = taken.slots;
219 const stack = taken.taken;
220 if (stack.itemId === ItemId.letter && stack.instance)
221 { stack.instance = { ...stack.instance, opened: false }; }
222 takenCargo = { kind: "item", stack };
223 }
224 else
225 {
226 const error = new Error("Pigeon cargo must be money or one item stack.");
227 error.userFacing = true;
228 throw error;
229 }
230
231 const originDim = normalizeDimensionId(originDimensionId);
232 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
233 this.#persistBag(characterId, bag);
234 const transit = this.#insertRoutedTransit({
235 senderCharacterId: characterId,
236 destinationKind: dest.kind,
237 destinationCharacterId: dest.characterId ?? null,
238 vaultCharacterId: dest.vaultCharacterId ?? null,
239 cargo: takenCargo,
240 originTileX,
241 originTileY,
242 originDimensionId: originDim,
243 destTileX: dest.tileX,
244 destTileY: dest.tileY,
245 destDimensionId: dest.dimensionId
246 });
247 return { transit, bag };
248 }
249
250 /**
251 * Shared entry for system letters (gift / CE / bounty / church / cowardice / …).
252 * Online (not combat-logout): pigeon flies immediately.
253 * Offline / combat-logout: held until the character enters the world.
254 */
255 enqueueSystemLetter ({
256 characterId,
257 originTileX,
258 originTileY,
259 originDimensionId = OVERWORLD_ID,
260 authorDisplayName,
261 authorOrganization = null,
262 body,
263 centralExchange = false,
264 bankRestNotice = false
265 })
266 {
267 const stack = makeSystemLetterStack({
268 authorDisplayName,
269 authorOrganization,
270 body,
271 centralExchange,
272 bankRestNotice
273 });
274 return this.dispatchSystemLetter({
275 characterId,
276 originTileX,
277 originTileY,
278 originDimensionId,
279 stack
280 });
281 }
282
283 /**
284 * System letters (gift / CE / bounty): pigeon to the player (inventory; bank if full).
285 * While offline, hold with player destination so login flies from the bank to the character
286 * — never deposit the letter straight into the vault.
287 * Prefer enqueueSystemLetter when building a new system letter from author/body fields.
288 */
289 dispatchSystemLetter ({ characterId, originTileX, originTileY, originDimensionId = OVERWORLD_ID, stack })
290 {
291 const recipientId = characterId | 0;
292 const cargo = { kind: "item", stack };
293 const row = this.stateDb.getCharacter(recipientId);
294 return this.dispatchHeldCargo({
295 senderCharacterId: recipientId,
296 originTileX,
297 originTileY,
298 originDimensionId,
299 destination: {
300 kind: "player",
301 firstName: row?.first_name ?? "Unknown",
302 lastName: row?.last_name ?? ""
303 },
304 cargo,
305 vaultCharacterId: recipientId
306 });
307 }
308
309 /**
310 * Market / system dispatch already holding cargo (no bag take).
311 * When the recipient is offline, holds delivery until login (CE letters, etc.).
312 * Player-bound holds keep destinationKind "player" even though resolve would route to bank
313 * while offline — on login the pigeon then delivers to the character, not the vault.
314 */
315 dispatchHeldCargo ({
316 senderCharacterId,
317 originTileX,
318 originTileY,
319 originDimensionId = OVERWORLD_ID,
320 destination,
321 cargo,
322 vaultCharacterId = null
323 })
324 {
325 const originDim = normalizeDimensionId(originDimensionId);
326 const recipientId = vaultCharacterId ?? senderCharacterId;
327 if (!this.simulation.isCharacterOnline(recipientId))
328 {
329 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
330 const intendedKind = destination?.kind === "player" ? "player" : dest.kind;
331 this.stateDb.insertHeldCourierDelivery({
332 characterId: recipientId,
333 senderCharacterId,
334 originTileX,
335 originTileY,
336 originDimensionId: originDim,
337 destinationKind: intendedKind,
338 destinationCharacterId: dest.characterId ?? recipientId,
339 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId,
340 cargo
341 });
342 return null;
343 }
344 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
345 return this.#insertRoutedTransit({
346 senderCharacterId,
347 destinationKind: dest.kind,
348 destinationCharacterId: dest.characterId ?? null,
349 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null,
350 cargo,
351 originTileX,
352 originTileY,
353 originDimensionId: originDim,
354 destTileX: dest.tileX,
355 destTileY: dest.tileY,
356 destDimensionId: dest.dimensionId
357 });
358 }
359
360 /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */
361 onCharacterEnteredWorld (characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
362 {
363 const enterDim = normalizeDimensionId(dimensionId);
364 for (const held of this.stateDb.listHeldCourierDeliveries(characterId))
365 {
366 this.stateDb.deleteHeldCourierDelivery(held.holdId);
367 const row = this.stateDb.getCharacter(held.destinationCharacterId ?? characterId);
368 this.dispatchHeldCargo({
369 senderCharacterId: held.senderCharacterId,
370 originTileX: held.originTileX,
371 originTileY: held.originTileY,
372 originDimensionId: held.originDimensionId ?? OVERWORLD_ID,
373 destination: held.destinationKind === "bank"
374 ? { kind: "bank" }
375 : {
376 kind: "player",
377 firstName: row?.first_name ?? "Unknown",
378 lastName: row?.last_name ?? ""
379 },
380 cargo: held.cargo,
381 vaultCharacterId: held.vaultCharacterId ?? characterId
382 });
383 }
384 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY, enterDim);
385 void noticeTransit;
386 }
387
388 step (now, dt)
389 {
390 const events = [];
391 const settings = this.simulation.settings;
392 for (const transit of this.stateDb.listActiveCourierTransits())
393 {
394 ensureCourierLegs(transit);
395 this.#retargetPlayerDest(transit);
396 ensureCourierLegs(transit);
397 const advancedEvents = this.#advanceTransit(transit, now, dt, settings);
398 events.push(...advancedEvents);
399 }
400 return events;
401 }
402
403 #insertRoutedTransit ({
404 senderCharacterId,
405 destinationKind,
406 destinationCharacterId,
407 vaultCharacterId,
408 cargo,
409 originTileX,
410 originTileY,
411 originDimensionId,
412 destTileX,
413 destTileY,
414 destDimensionId
415 })
416 {
417 const originDim = normalizeDimensionId(originDimensionId);
418 const destDim = normalizeDimensionId(destDimensionId ?? OVERWORLD_ID);
419 const originX = originTileX + 0.5;
420 const originY = originTileY + 0.5;
421 const destX = destTileX + 0.5;
422 const destY = destTileY + 0.5;
423 const legs = this.#planLegs({
424 fromX: originX,
425 fromY: originY,
426 fromDimensionId: originDim,
427 toX: destX,
428 toY: destY,
429 toDimensionId: destDim
430 });
431 return this.stateDb.insertCourierTransit({
432 senderCharacterId,
433 destinationKind,
434 destinationCharacterId,
435 vaultCharacterId,
436 cargo,
437 originX,
438 originY,
439 destX,
440 destY,
441 originDimensionId: originDim,
442 destDimensionId: destDim,
443 legs,
444 legIndex: 0,
445 traveled: 0,
446 status: "in_transit",
447 entityId: null
448 });
449 }
450
451 #planLegs ({ fromX, fromY, fromDimensionId, toX, toY, toDimensionId })
452 {
453 const planned = planPortalLegs({
454 fromX,
455 fromY,
456 fromDimensionId,
457 toX,
458 toY,
459 toDimensionId,
460 graph: this.doorwayGraph
461 });
462 if (planned.mode !== "fallback")
463 { return planned.legs; }
464 return buildFallbackLegs({
465 fromX,
466 fromY,
467 fromDimensionId,
468 toX,
469 toY,
470 toDimensionId,
471 isSimulating: (tileX, tileY, dimensionId) =>
472 this.simulation.chunkIsSimulating(tileX, tileY, dimensionId),
473 settings: this.simulation.settings
474 }).legs;
475 }
476
477 #repathTransit (transit, fromX, fromY, fromDimensionId, toX, toY, toDimensionId)
478 {
479 if (transit.entityId)
480 {
481 this.simulation.despawnEntity(transit.entityId);
482 transit.entityId = null;
483 }
484 transit.originX = fromX;
485 transit.originY = fromY;
486 transit.originDimensionId = normalizeDimensionId(fromDimensionId);
487 transit.destX = toX;
488 transit.destY = toY;
489 transit.destDimensionId = normalizeDimensionId(toDimensionId);
490 transit.legs = this.#planLegs({
491 fromX,
492 fromY,
493 fromDimensionId: transit.originDimensionId,
494 toX,
495 toY,
496 toDimensionId: transit.destDimensionId
497 });
498 transit.legIndex = 0;
499 transit.traveled = 0;
500 }
501
502 #currentPose (transit)
503 {
504 ensureCourierLegs(transit);
505 const leg = transit.legs[transit.legIndex | 0];
506 const pose = poseOnCourierLeg(leg, transit.traveled);
507 if (pose)
508 { return pose; }
509 if (leg?.kind === "abstract")
510 {
511 return {
512 x: leg.fromX,
513 y: leg.fromY,
514 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? transit.originDimensionId ?? OVERWORLD_ID)
515 };
516 }
517 return {
518 x: transit.originX,
519 y: transit.originY,
520 dimensionId: normalizeDimensionId(transit.originDimensionId ?? OVERWORLD_ID)
521 };
522 }
523
524 #advanceTransit (transit, now, dt, settings)
525 {
526 const events = [];
527 ensureCourierLegs(transit);
528 let remainingDt = Math.max(0, dt);
529 let guard = 0;
530 while (remainingDt > 0 && guard++ < 16)
531 {
532 const leg = transit.legs[transit.legIndex | 0];
533 if (!leg)
534 {
535 events.push(...this.#deliver(transit, now));
536 return events;
537 }
538
539 if (leg.kind === "portal")
540 {
541 transit.traveled = 0;
542 transit.legIndex = (transit.legIndex | 0) + 1;
543 if (transit.entityId)
544 {
545 this.simulation.despawnEntity(transit.entityId);
546 events.push({
547 type: "entity-despawn",
548 entityId: transit.entityId,
549 tileX: Math.floor(leg.fromX),
550 tileY: Math.floor(leg.fromY),
551 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
552 });
553 transit.entityId = null;
554 }
555 if ((transit.legIndex | 0) >= transit.legs.length)
556 {
557 events.push(...this.#deliver(transit, now));
558 return events;
559 }
560 continue;
561 }
562
563 if (leg.kind === "abstract")
564 {
565 if (transit.entityId)
566 {
567 const pose = this.#currentPose(transit);
568 this.simulation.despawnEntity(transit.entityId);
569 events.push({
570 type: "entity-despawn",
571 entityId: transit.entityId,
572 tileX: Math.floor(pose.x),
573 tileY: Math.floor(pose.y),
574 dimensionId: pose.dimensionId
575 });
576 transit.entityId = null;
577 }
578 const advanced = advanceAbstractTravel({
579 traveled: transit.traveled,
580 distance: leg.distance ?? 0,
581 dt: remainingDt,
582 settings
583 });
584 transit.traveled = advanced.traveled;
585 transit.updatedAt = now;
586 if (!advanced.arrived)
587 {
588 this.stateDb.updateCourierTransit(transit);
589 return events;
590 }
591 remainingDt = 0;
592 transit.traveled = 0;
593 transit.legIndex = (transit.legIndex | 0) + 1;
594 if ((transit.legIndex | 0) >= transit.legs.length)
595 {
596 events.push(...this.#deliver(transit, now));
597 return events;
598 }
599 continue;
600 }
601
602 // fly leg
603 const advanced = advanceCourierFlight({
604 originX: leg.fromX,
605 originY: leg.fromY,
606 destX: leg.toX,
607 destY: leg.toY,
608 traveled: transit.traveled,
609 dt: remainingDt,
610 settings
611 });
612 transit.traveled = advanced.traveled;
613 transit.updatedAt = now;
614 if (!advanced.arrived)
615 {
616 events.push(...this.#syncVisiblePigeon(transit, advanced, now, leg));
617 this.stateDb.updateCourierTransit(transit);
618 return events;
619 }
620
621 remainingDt = 0;
622 transit.traveled = 0;
623 transit.legIndex = (transit.legIndex | 0) + 1;
624 if ((transit.legIndex | 0) >= transit.legs.length)
625 {
626 events.push(...this.#deliver(transit, now));
627 return events;
628 }
629 // Despawn at portal approach so next portal/fly starts clean.
630 if (transit.entityId)
631 {
632 this.simulation.despawnEntity(transit.entityId);
633 events.push({
634 type: "entity-despawn",
635 entityId: transit.entityId,
636 tileX: Math.floor(advanced.x),
637 tileY: Math.floor(advanced.y),
638 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
639 });
640 transit.entityId = null;
641 }
642 }
643 this.stateDb.updateCourierTransit(transit);
644 return events;
645 }
646
647 #retargetPlayerDest (transit)
648 {
649 if (transit.destinationKind !== "player" || !transit.destinationCharacterId)
650 { return; }
651 const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId);
652 if (onlineId)
653 {
654 const pos = this.simulation.positionOf(onlineId);
655 if (!pos)
656 { return; }
657 const destDim = normalizeDimensionId(pos.dimensionId ?? OVERWORLD_ID);
658 const destX = pos.tileX + 0.5;
659 const destY = pos.tileY + 0.5;
660 const prevDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
661 if (destDim !== prevDim)
662 {
663 const pose = this.#currentPose(transit);
664 this.#repathTransit(
665 transit,
666 pose.x,
667 pose.y,
668 pose.dimensionId,
669 destX,
670 destY,
671 destDim
672 );
673 return;
674 }
675 transit.destX = destX;
676 transit.destY = destY;
677 transit.destDimensionId = destDim;
678 const lastIdx = transit.legs.length - 1;
679 const last = transit.legs[lastIdx];
680 if (last?.kind === "fly"
681 && normalizeDimensionId(last.toDimensionId ?? destDim) === destDim)
682 {
683 const oldToX = last.toX;
684 const oldToY = last.toY;
685 last.toX = destX;
686 last.toY = destY;
687 if ((transit.legIndex | 0) === lastIdx)
688 {
689 const oldTotal = Math.hypot(oldToX - last.fromX, oldToY - last.fromY);
690 const newTotal = Math.hypot(destX - last.fromX, destY - last.fromY);
691 if (oldTotal > 1e-6)
692 { transit.traveled = Math.min(newTotal, (transit.traveled || 0) * (newTotal / oldTotal)); }
693 }
694 }
695 return;
696 }
697 this.#routeTransitToBank(transit, transit.destinationCharacterId);
698 }
699
700 #routeTransitToBank (transit, vaultCharacterId)
701 {
702 const pose = this.#currentPose(transit);
703 const bank = this.nearestBank(Math.floor(pose.x), Math.floor(pose.y), pose.dimensionId)
704 ?? this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY), transit.destDimensionId)
705 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY), transit.originDimensionId);
706 if (!bank)
707 { return; }
708 transit.destinationKind = "bank";
709 transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId;
710 this.#repathTransit(
711 transit,
712 pose.x,
713 pose.y,
714 pose.dimensionId,
715 bank.tileX + 0.5,
716 bank.tileY + 0.5,
717 bank.dimensionId ?? OVERWORLD_ID
718 );
719 }
720
721 #resolveDestination (destination, originTileX, originTileY, originDimensionId = OVERWORLD_ID)
722 {
723 const originDim = normalizeDimensionId(originDimensionId);
724 if (destination?.kind === "player")
725 {
726 const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);
727 if (!character)
728 {
729 const error = new Error("No character with that name.");
730 error.userFacing = true;
731 throw error;
732 }
733 const onlineId = this.simulation.characterEntities.get(character.character_id);
734 if (!onlineId)
735 {
736 const charDim = normalizeDimensionId(character.dimension_id ?? OVERWORLD_ID);
737 const bank = this.nearestBank(originTileX, originTileY, originDim)
738 ?? this.nearestBank(character.tile_x, character.tile_y, charDim);
739 if (!bank)
740 {
741 const error = new Error("No bank exists in the world yet.");
742 error.userFacing = true;
743 throw error;
744 }
745 return {
746 kind: "bank",
747 characterId: character.character_id,
748 vaultCharacterId: character.character_id,
749 tileX: bank.tileX,
750 tileY: bank.tileY,
751 dimensionId: normalizeDimensionId(bank.dimensionId ?? OVERWORLD_ID)
752 };
753 }
754 const pos = this.simulation.positionOf(onlineId);
755 return {
756 kind: "player",
757 characterId: character.character_id,
758 tileX: pos.tileX,
759 tileY: pos.tileY,
760 dimensionId: normalizeDimensionId(pos.dimensionId ?? OVERWORLD_ID)
761 };
762 }
763 if (destination?.kind === "bank")
764 {
765 const bank = this.nearestBank(originTileX, originTileY, originDim);
766 if (!bank)
767 {
768 const error = new Error("No bank exists in the world yet.");
769 error.userFacing = true;
770 throw error;
771 }
772 return {
773 kind: "bank",
774 tileX: bank.tileX,
775 tileY: bank.tileY,
776 dimensionId: normalizeDimensionId(bank.dimensionId ?? OVERWORLD_ID)
777 };
778 }
779 const error = new Error("Pigeon destination must be bank or player.");
780 error.userFacing = true;
781 throw error;
782 }
783
784 #syncVisiblePigeon (transit, advanced, now, leg)
785 {
786 const events = [];
787 const tileX = Math.floor(advanced.x);
788 const tileY = Math.floor(advanced.y);
789 const dimensionId = normalizeDimensionId(
790 leg?.fromDimensionId ?? transit.originDimensionId ?? OVERWORLD_ID
791 );
792 if (!this.simulation.chunkIsSimulating(tileX, tileY, dimensionId))
793 {
794 if (transit.entityId)
795 {
796 this.simulation.despawnEntity(transit.entityId);
797 events.push({
798 type: "entity-despawn",
799 entityId: transit.entityId,
800 tileX,
801 tileY,
802 dimensionId
803 });
804 transit.entityId = null;
805 }
806 return events;
807 }
808
809 if (!transit.entityId || !this.simulation.entityRecord(transit.entityId))
810 {
811 transit.entityId = null;
812 const def = mobDefinition(MobId.pigeon);
813 const entityId = this.simulation.spawnEntity({
814 position: { tileX, tileY, dimensionId },
815 movement: { gait: GAIT.walk, walkCarry: 0 },
816 path: { tiles: [] },
817 flight: {
818 x: advanced.x,
819 y: advanced.y,
820 targetX: leg?.toX ?? transit.destX,
821 targetY: leg?.toY ?? transit.destY,
822 speed: advanced.speed,
823 nextPickAt: now + 60_000,
824 lastAt: now,
825 courierId: transit.courierId
826 },
827 appearance: {
828 sex: def.sex,
829 firstName: def.displayName,
830 lastName: "",
831 sprite: mobSpriteName(MobId.pigeon)
832 },
833 creature: { mobTypeId: MobId.pigeon },
834 health: { current: 1, max: 1 }
835 }, { requireResident: true });
836 if (entityId != null)
837 { transit.entityId = entityId; }
838 return events;
839 }
840
841 const moved = this.simulation.updateCourierFlight(transit.entityId, {
842 x: advanced.x,
843 y: advanced.y,
844 targetX: leg?.toX ?? transit.destX,
845 targetY: leg?.toY ?? transit.destY,
846 speed: advanced.speed,
847 lastAt: now,
848 courierId: transit.courierId
849 }, now);
850 if (moved?.despawned)
851 {
852 transit.entityId = null;
853 events.push({
854 type: "entity-despawn",
855 entityId: moved.entityId,
856 tileX,
857 tileY,
858 dimensionId
859 });
860 }
861 else if (moved?.event)
862 { events.push(moved.event); }
863 return events;
864 }
865
866 #deliver (transit, now)
867 {
868 const events = [];
869 const destDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
870 if (transit.entityId)
871 {
872 this.simulation.despawnEntity(transit.entityId);
873 events.push({
874 type: "entity-despawn",
875 entityId: transit.entityId,
876 tileX: Math.floor(transit.destX),
877 tileY: Math.floor(transit.destY),
878 dimensionId: destDim
879 });
880 transit.entityId = null;
881 }
882
883 if (transit.destinationKind === "bank")
884 {
885 const vaultCharacterId = transit.vaultCharacterId
886 ?? transit.destinationCharacterId
887 ?? transit.senderCharacterId;
888 const toast = this.#creditVault(vaultCharacterId, transit.cargo, {
889 senderCharacterId: transit.senderCharacterId
890 });
891 if (toast)
892 { events.push(toast); }
893 }
894 else if (transit.destinationKind === "player")
895 {
896 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
897 if (!delivered)
898 {
899 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY), destDim)
900 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY), transit.originDimensionId);
901 if (bank)
902 {
903 const pose = {
904 x: transit.destX,
905 y: transit.destY,
906 dimensionId: destDim
907 };
908 transit.destinationKind = "bank";
909 transit.vaultCharacterId = transit.destinationCharacterId;
910 this.#repathTransit(
911 transit,
912 pose.x,
913 pose.y,
914 pose.dimensionId,
915 bank.tileX + 0.5,
916 bank.tileY + 0.5,
917 bank.dimensionId ?? OVERWORLD_ID
918 );
919 transit.updatedAt = now;
920 this.stateDb.updateCourierTransit(transit);
921 events.push({
922 type: "pigeon-reroute-bank",
923 courierId: transit.courierId,
924 characterId: transit.destinationCharacterId
925 });
926 return events;
927 }
928 const toast = this.#creditVault(transit.destinationCharacterId, transit.cargo, {
929 senderCharacterId: transit.senderCharacterId
930 });
931 if (toast)
932 { events.push(toast); }
933 }
934 else
935 {
936 events.push({
937 type: "item-bubble",
938 entityId: delivered.entityId,
939 itemId: delivered.itemId,
940 quantity: delivered.quantity
941 });
942 }
943 }
944
945 transit.status = "delivered";
946 transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY);
947 transit.updatedAt = now;
948 this.stateDb.updateCourierTransit(transit);
949 events.push({
950 type: "pigeon-delivered",
951 courierId: transit.courierId,
952 senderCharacterId: transit.senderCharacterId,
953 destinationKind: transit.destinationKind,
954 destinationCharacterId: transit.destinationCharacterId,
955 cargo: transit.cargo
956 });
957 return events;
958 }
959
960 #normalizeCargo (cargo)
961 {
962 if (cargo?.kind === "money")
963 {
964 return {
965 kind: "item",
966 stack: attachOrigins({ itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) })
967 };
968 }
969 return cargo;
970 }
971
972 #tryDeliverToPlayer (characterId, cargo)
973 {
974 cargo = this.#normalizeCargo(cargo);
975 const onlineId = this.simulation.characterEntities.get(characterId);
976 if (!onlineId)
977 { return null; }
978 if (cargo.kind === "item")
979 {
980 const bag = this.simulation.bagOf(onlineId);
981 if (!bag)
982 { return null; }
983 const def = itemDefinition(cargo.stack.itemId);
984 const result = insertStack(bag.inventory, cargo.stack, def);
985 if (!result.ok || result.remainder)
986 { return null; }
987 bag.inventory = result.slots;
988 this.#persistBag(characterId, bag);
989 return {
990 entityId: onlineId,
991 itemId: cargo.stack.itemId,
992 quantity: Math.max(1, cargo.stack.quantity | 0 || 1)
993 };
994 }
995 return null;
996 }
997
998 #creditVault (characterId, cargo, { senderCharacterId = null, recordRestNotice = true } = {})
999 {
1000 cargo = this.#normalizeCargo(cargo);
1001 const onlineId = this.simulation.characterEntities.get(characterId);
1002 const bag = onlineId
1003 ? this.simulation.bagOf(onlineId)
1004 : this.stateDb.getBag(characterId);
1005 if (!bag)
1006 { return null; }
1007 if (cargo.kind !== "item")
1008 { return null; }
1009
1010 const stack = cargo.stack;
1011 const isCeLetter = stack?.itemId === ItemId.letter && isCentralExchangeLetter(stack.instance);
1012 const isRestNoticeLetter = stack?.itemId === ItemId.letter && isBankRestNoticeLetter(stack.instance);
1013
1014 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
1015 {
1016 this.#redeemChequeIntoVault(characterId, bag, stack);
1017 this.#maybeRecordRestNotice({
1018 characterId,
1019 stack,
1020 senderCharacterId,
1021 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
1022 });
1023 return null;
1024 }
1025
1026 const def = itemDefinition(stack.itemId);
1027 const vault = normalizeVault(
1028 bag.vaultReserved != null
1029 ? { slots: bag.vault, reserved: bag.vaultReserved }
1030 : bag.vault
1031 );
1032 const result = insertStackGrowable(vault.slots, stack, def);
1033 bag.vault = result.slots;
1034 bag.vaultReserved = vault.reserved;
1035 this.#persistBag(characterId, bag);
1036
1037 this.#maybeRecordRestNotice({
1038 characterId,
1039 stack,
1040 senderCharacterId,
1041 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
1042 });
1043
1044 if (onlineId && isRestNoticeLetter)
1045 {
1046 return {
1047 type: "toast",
1048 characterId,
1049 message: "A letter arrived for you at the bank."
1050 };
1051 }
1052 return null;
1053 }
1054
1055 #maybeRecordRestNotice ({ characterId, stack, senderCharacterId, recordRestNotice })
1056 {
1057 if (!recordRestNotice || !stack)
1058 { return; }
1059 const sender = senderCharacterId ? this.stateDb.getCharacter(senderCharacterId) : null;
1060 const senderDisplayName = sender
1061 ? `${sender.first_name} ${sender.last_name}`.trim()
1062 : null;
1063 this.stateDb.appendBankRestNotice(characterId, {
1064 itemId: stack.itemId,
1065 itemName: itemNameForNotice(stack),
1066 quantity: stack.quantity | 0 || 1,
1067 sourceName: sourceNameForVaultDeposit(stack, senderCharacterId, senderDisplayName)
1068 });
1069 }
1070
1071 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
1072 #redeemChequeIntoVault (characterId, bag, chequeStack)
1073 {
1074 const instance = chequeStack.instance;
1075 const issuerId = instance.issuerCharacterId;
1076 const goodsDef = itemDefinition(instance.itemId);
1077 if (!goodsDef)
1078 { return; }
1079
1080 let reservedStack = null;
1081 if (Number(issuerId) === Number(characterId))
1082 {
1083 const reserved = [...(bag.vaultReserved ?? [])];
1084 const index = findReservedChequeIndex(reserved, instance);
1085 if (index < 0)
1086 {
1087 // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost.
1088 const def = itemDefinition(ItemId.filledCheque);
1089 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
1090 const result = insertStackGrowable(vault.slots, chequeStack, def);
1091 bag.vault = result.slots;
1092 bag.vaultReserved = vault.reserved;
1093 this.#persistBag(characterId, bag);
1094 return;
1095 }
1096 reservedStack = reserved[index];
1097 reserved.splice(index, 1);
1098 bag.vaultReserved = reserved;
1099 }
1100 else
1101 {
1102 const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance);
1103 if (!release?.ok)
1104 {
1105 const def = itemDefinition(ItemId.filledCheque);
1106 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
1107 const result = insertStackGrowable(vault.slots, chequeStack, def);
1108 bag.vault = result.slots;
1109 bag.vaultReserved = vault.reserved;
1110 this.#persistBag(characterId, bag);
1111 return;
1112 }
1113 reservedStack = release.stack;
1114 }
1115
1116 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
1117 const goodsStack = attachOrigins({
1118 itemId: reservedStack.itemId,
1119 quantity: reservedStack.quantity,
1120 origins: normalizeOrigins(reservedStack),
1121 instance: reservedStack.instance ?? null
1122 });
1123 const inserted = insertStackGrowable(vault.slots, goodsStack, goodsDef);
1124 bag.vault = inserted.slots;
1125 bag.vaultReserved = vault.reserved;
1126 this.#persistBag(characterId, bag);
1127 this.#maybeRecordRestNotice({
1128 characterId,
1129 stack: goodsStack,
1130 senderCharacterId: null,
1131 recordRestNotice: !this.simulation.characterEntities.get(characterId)
1132 });
1133 }
1134
1135 #persistBag (characterId, bag)
1136 {
1137 this.stateDb.saveBag(characterId, bag);
1138 const onlineId = this.simulation.characterEntities.get(characterId);
1139 if (onlineId)
1140 {
1141 this.simulation.applyBag(onlineId, bag);
1142 this.simulation.pushInventory(characterId, bag);
1143 }
1144 }
1145
1146 #characterDisplayName (characterId)
1147 {
1148 const row = this.stateDb.getCharacter(characterId);
1149 return {
1150 firstName: row?.first_name ?? "Unknown",
1151 lastName: row?.last_name ?? "",
1152 full: row ? `${row.first_name} ${row.last_name}`.trim() : "Adventurer"
1153 };
1154 }
1155
1156 #dispatchBankRestNotice (characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
1157 {
1158 const entries = this.stateDb.listBankRestNotices(characterId);
1159 if (!entries.length)
1160 { return null; }
1161 const dim = normalizeDimensionId(dimensionId);
1162 const bank = this.nearestBank(tileX, tileY, dim);
1163 if (!bank)
1164 { return null; }
1165
1166 const lines = mergeBankRestNoticeLines(entries.map((entry) => ({
1167 quantity: entry.quantity,
1168 itemName: entry.itemName,
1169 sourceName: entry.sourceName
1170 })));
1171 const { full: playerName } = this.#characterDisplayName(characterId);
1172 const body = bankRestNoticeLetterBody({ playerName, lines });
1173 const stack = makeSystemLetterStack({
1174 authorDisplayName: BANK_LETTER_AUTHOR,
1175 body,
1176 bankRestNotice: true
1177 });
1178 this.stateDb.clearBankRestNotices(characterId);
1179 return this.dispatchSystemLetter({
1180 characterId,
1181 originTileX: bank.tileX,
1182 originTileY: bank.tileY,
1183 originDimensionId: bank.dimensionId ?? OVERWORLD_ID,
1184 stack
1185 });
1186 }
1187}