BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 74.3 KiB Download Raw
1import {
2 CHUNK_SIZE,
3 DEFAULT_CHUNK_LOADER,
4 GAIT,
5 REGION_RUNTIME_STATE,
6 VISIBLE_CHUNK_RADIUS,
7 STATIC_CHUNK_RADIUS,
8 WORLD_YEAR_OFFSET
9} from "../../../shared/protocol/constants.js";
10import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js";
11import {
12 chunkKey,
13 chunkToRegion,
14 chunksInRegion,
15 parseChunkKey,
16 parseRegionKey,
17 regionKey,
18 regionTileBounds,
19 tileToChunk,
20 tileToLocal,
21 tileToRegion,
22 visibleChunkCoords
23} from "../world/coordinates.js";
24import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
25import { closedNeighborEdges } from "../world/chunkFlags.js";
26import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
27import { InProcessWorker } from "./inProcessWorker.js";
28import { ThreadWorker } from "./threadWorker.js";
29import { WorkerMessage } from "./protocol.js";
30import { replicaNeededForOwnedChunks } from "./workerWorld.js";
31import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
32import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
33import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
34import { mobComponents } from "./spawners.js";
35import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
36import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
37import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
38import { BlockType } from "../../../shared/definitions/tiles.js";
39import { ItemId } from "../../../shared/definitions/items.js";
40import { seasonIdAt } from "../../../shared/world/season.js";
41import { CourierService } from "../courier/service.js";
42import { MarketService } from "../market/service.js";
43import { BountyService } from "../bounty/service.js";
44import { BarberService } from "../barber/service.js";
45import { findReservedChequeIndex } from "../items/bags.js";
46import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
47import { QuestContentCache } from "../quests/contentCache.js";
48import { QuestRuntime } from "../quests/runtime.js";
49import { chebyshev } from "../combat/service.js";
50
51export class Simulation
52{
53 constructor (worldDb, stateDb, options = {})
54 {
55 this.worldDb = worldDb;
56 this.stateDb = stateDb;
57 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
58 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
59 this.pinRegion = options.pinRegion ?? null;
60 this.nowFn = options.now ?? (() => Date.now());
61 this.workers = [];
62 this.regionOwner = new Map();
63 this.regionGraceUntil = new Map();
64 this.directory = new Map();
65 this.characterEntities = new Map();
66 this.commandQueue = [];
67 this.replication = [];
68 this.pendingPrivate = [];
69 this.courier = null;
70 this.market = null;
71 this.altarTiles = [];
72 this.authoredCache = new Map();
73 this.simulatingChunkKeys = new Set();
74 this.nextEntityId = 1;
75 this.nextGroundItemId = stateDb.nextGroundItemId();
76 this.tickIndex = 0;
77 this.movementTickCounter = 0;
78 this.lastTickAt = null;
79 this.movementAccumulator = 0;
80 this.activeRevisionId = worldDb.getActiveRevisionId();
81 this.settings = worldDb.getLiveSettings();
82 this.questContent = new QuestContentCache(worldDb);
83 this.dimensions = this.#loadDimensionsCache();
84 this.quests = null;
85
86 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
87 for (let workerId = 0; workerId < this.workerCount; workerId++)
88 {
89 const worker = new WorkerImpl(workerId);
90 worker.call({
91 type: WorkerMessage.configure,
92 settings: this.settings,
93 activeRevisionId: this.activeRevisionId
94 });
95 this.workers.push(worker);
96 }
97 for (const worker of this.workers)
98 {
99 if (!worker.world)
100 { continue; }
101 worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
102 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
103 }
104 this.courier = new CourierService({
105 stateDb: this.stateDb,
106 worldDb: this.worldDb,
107 simulation: this
108 });
109 this.market = new MarketService({
110 stateDb: this.stateDb,
111 worldDb: this.worldDb,
112 simulation: this
113 });
114 this.bounty = new BountyService(this.stateDb, this, this.courier);
115 this.barber = new BarberService(this.stateDb, this);
116 this.quests = new QuestRuntime({
117 stateDb: this.stateDb,
118 content: this.questContent,
119 simulation: this
120 });
121 this.#refreshAltarIndex();
122 }
123
124 get now ()
125 {
126 return this.nowFn();
127 }
128
129 applySettings (settings)
130 {
131 this.settings = { ...this.settings, ...settings };
132 this.#configureWorkers();
133 }
134
135 /** Sparse last-sale map for editor base-price readouts. */
136 itemLastSalesSnapshot ()
137 {
138 return this.market?.snapshot?.() ?? {};
139 }
140
141 syncItemLastSales (lastSales)
142 {
143 const sales = {};
144 for (const [itemId, sale] of lastSales?.entries?.() ?? [])
145 { sales[String(itemId)] = sale; }
146 for (const worker of this.workers)
147 {
148 worker.call({
149 type: WorkerMessage.setItemLastSales,
150 sales
151 });
152 }
153 }
154
155 reloadWorld ()
156 {
157 this.activeRevisionId = this.worldDb.getActiveRevisionId();
158 this.settings = this.worldDb.getLiveSettings();
159 this.dimensions = this.#loadDimensionsCache();
160 this.authoredCache.clear();
161 this.#configureWorkers();
162 for (const [key, workerId] of this.regionOwner)
163 {
164 const { regionX, regionY, dimensionId } = parseRegionKey(key);
165 this.workers[workerId].call({
166 type: WorkerMessage.replaceRegionChunks,
167 regionX,
168 regionY,
169 dimensionId,
170 chunks: this.#regionChunkBlobs(regionX, regionY, dimensionId)
171 });
172 }
173 this.#syncAllReplicas();
174 this.courier?.refreshBankIndex();
175 this.courier?.refreshBountyOfficeIndex();
176 this.market?.refreshIndex();
177 this.questContent.reload();
178 this.quests?.closeAllSessions();
179 this.#refreshAltarIndex();
180 }
181
182 enqueue (sessionId, command)
183 {
184 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
185 }
186
187 step (now = this.now)
188 {
189 this.tickIndex += 1;
190 if ((this.tickIndex % 1200) === 0)
191 { this.worldDb.purgeExpiredDimensions(now); }
192 const events = [];
193 const commands = this.commandQueue.splice(0);
194 for (const item of commands)
195 {
196 try
197 {
198 events.push(...this.#routeCommand(item));
199 }
200 catch (error)
201 {
202 events.push({
203 sessionId: item.sessionId,
204 type: "command-error",
205 message: error.userFacing ? error.message : "Command failed."
206 });
207 }
208 }
209
210 this.#recalculateActivation(now);
211
212 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
213 const expectedDt = 1 / simHz;
214 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
215 ? expectedDt
216 : Math.min(0.25, (now - this.lastTickAt) / 1000);
217 this.lastTickAt = now;
218
219 {
220 const transfers = [];
221 const remoteMelee = [];
222 const remoteRanged = [];
223 for (const worker of this.workers)
224 {
225 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
226 for (const event of result?.events ?? [])
227 {
228 if (event.type === "remote-melee-resolve")
229 {
230 remoteMelee.push(event);
231 continue;
232 }
233 if (event.type === "remote-ranged-resolve")
234 {
235 remoteRanged.push(event);
236 continue;
237 }
238 if (event.type === "entity-move")
239 { this.#applyMoveToDirectory(event); }
240 if (event.type === "entity-despawn")
241 { this.#forget(event.entityId); }
242 if (event.type === "skills-updated")
243 {
244 this.#applySkillsUpdated(event);
245 events.push(...this.#skillLevelUpEvents(event));
246 continue;
247 }
248 if (event.type === "spells-updated")
249 {
250 this.#applySpellsUpdated(event);
251 continue;
252 }
253 if (event.type === "inventory" && event.characterId)
254 {
255 this.#saveBagFromView(event.characterId, {
256 inventory: event.inventory,
257 equipment: event.equipment,
258 vault: event.vault,
259 vaultReserved: event.vaultReserved
260 });
261 }
262 if (event.type === "player-died")
263 {
264 events.push(...this.#applyPlayerDeath(event));
265 continue;
266 }
267 if (event.type === "mob-killed")
268 {
269 events.push(...this.#applyMobKilled(event));
270 continue;
271 }
272 if (event.type === "dialogue-walk-away")
273 {
274 const closed = this.quests?.closeDialogue(event.characterId, "walk-away");
275 events.push(...this.#mapQuestPrivateEvents(
276 closed?.events ?? [],
277 event.sessionId,
278 event.characterId
279 ));
280 continue;
281 }
282 this.#persistGroundEvent(event);
283 if (event.type !== "skills-updated")
284 { events.push(event); }
285 }
286 for (const request of result?.transferRequests ?? [])
287 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
288 }
289 for (const payload of remoteMelee)
290 { events.push(...this.#applyRemoteMelee(payload)); }
291 for (const payload of remoteRanged)
292 { events.push(...this.#applyRemoteRanged(payload)); }
293 if (transfers.length)
294 {
295 events.push(...this.#applyTransfers(transfers));
296 this.#recalculateActivation(now);
297 }
298 }
299
300 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
301 this.movementAccumulator += dt * movementHz;
302 while (this.movementAccumulator >= 1)
303 {
304 this.movementAccumulator -= 1;
305 this.movementTickCounter += 1;
306 const transfers = [];
307 for (const worker of this.workers)
308 {
309 const result = worker.call({ type: WorkerMessage.stepMovement, now });
310 for (const event of result?.events ?? [])
311 {
312 if (event.type === "entity-move")
313 { this.#applyMoveToDirectory(event); }
314 if (event.type === "skills-updated")
315 {
316 this.#applySkillsUpdated(event);
317 events.push(...this.#skillLevelUpEvents(event));
318 continue;
319 }
320 if (event.type === "spells-updated")
321 {
322 this.#applySpellsUpdated(event);
323 continue;
324 }
325 this.#persistGroundEvent(event);
326 if (event.type !== "skills-updated")
327 { events.push(event); }
328 }
329 for (const request of result?.transferRequests ?? [])
330 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
331 }
332 events.push(...this.#applyTransfers(transfers));
333 this.#recalculateActivation(now);
334 }
335
336 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
337 { events.push(...this.#stepSpawners()); }
338
339 if (this.courier)
340 { events.push(...this.courier.step(now, dt)); }
341 if (this.market)
342 { events.push(...this.market.step(now)); }
343
344 this.#syncGhosts();
345 events.push(...this.pendingPrivate.splice(0));
346 return { now, events, replication: this.drainReplication() };
347 }
348
349 drainReplication ()
350 {
351 return this.replication.splice(0);
352 }
353
354 worldTime (now = this.now)
355 {
356 const date = new Date(now);
357 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
358 return {
359 unixMs: now,
360 worldUnixMs: date.getTime(),
361 iso: date.toISOString(),
362 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600,
363 season: seasonIdAt(now)
364 };
365 }
366
367 spawnCharacter (sessionId, character)
368 {
369 this.despawnCharacter(character.character_id);
370 // Despawn may have just written the live tile; never trust a stale row snapshot.
371 const row = this.stateDb.getCharacter(character.character_id) ?? character;
372 let tileX = row.tile_x;
373 let tileY = row.tile_y;
374 let dimensionId = normalizeDimensionId(row.dimension_id ?? OVERWORLD_ID);
375 const gait = row.gait || character.gait || GAIT.walk;
376
377 // Soft-deleted / purged interiors eject to overworld spawn.
378 if (!this.#isDimensionUsable(dimensionId))
379 {
380 dimensionId = OVERWORLD_ID;
381 const spawn = this.findOpenSpawn();
382 if (!spawn)
383 {
384 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
385 error.userFacing = true;
386 throw error;
387 }
388 tileX = spawn.tileX;
389 tileY = spawn.tileY;
390 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
391 }
392
393 const preferred = this.#findResumeTile(tileX, tileY, 24, dimensionId);
394 if (!preferred)
395 {
396 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
397 error.userFacing = true;
398 throw error;
399 }
400 if (
401 preferred.tileX !== tileX
402 || preferred.tileY !== tileY
403 || normalizeDimensionId(preferred.dimensionId ?? dimensionId) !== dimensionId
404 )
405 {
406 tileX = preferred.tileX;
407 tileY = preferred.tileY;
408 dimensionId = normalizeDimensionId(preferred.dimensionId ?? dimensionId);
409 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
410 }
411
412 const bag = this.stateDb.getBag(character.character_id) ?? {
413 inventory: emptySlots(),
414 equipment: emptyEquipment(),
415 vault: [],
416 vaultReserved: []
417 };
418 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
419 const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells();
420 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
421 if (enforceMinimumSkillLevels(skills))
422 { this.stateDb.saveSkills(character.character_id, skills); }
423 const maxHealth = playerMaxHealth(skills);
424 const maxStamina = playerMaxStamina(skills);
425 const isDead = !!row.is_dead;
426 const savedHealth = row.health_current;
427 const currentHealth = isDead
428 ? 0
429 : savedHealth != null
430 ? Math.max(0, Math.min(maxHealth, savedHealth | 0))
431 : maxHealth;
432 const entityId = this.nextEntityId++;
433 const components = {
434 position: { tileX, tileY, dimensionId },
435 movement: { gait, walkCarry: 0 },
436 path: { tiles: [] },
437 appearance: {
438 sex: character.sex ?? row.sex,
439 firstName: character.first_name ?? row.first_name,
440 lastName: character.last_name ?? row.last_name,
441 ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character))
442 },
443 character: {
444 characterId: character.character_id ?? row.character_id,
445 accountId: character.account_id ?? row.account_id
446 },
447 networkIdentity: { sessionId },
448 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
449 inventory: { slots: bag.inventory ?? emptySlots() },
450 equipment: bag.equipment ?? emptyEquipment(),
451 vault: {
452 slots: bag.vault ?? [],
453 reserved: bag.vaultReserved ?? []
454 },
455 health: { current: currentHealth, max: maxHealth },
456 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
457 combat: { targetEntityId: null, nextSwingAt: 0 },
458 skills,
459 spells,
460 spellcasting: {
461 armedSpellId: null,
462 repeatSpellId: null,
463 repeatTargetEntityId: null,
464 nextCastAt: 0
465 },
466 };
467 if (isDead)
468 { components.dead = {}; }
469 this.#ensureCoverage(tileX, tileY, components.chunkLoader, dimensionId);
470 const workerId = this.#ownerOfTile(tileX, tileY, dimensionId);
471 const view = this.workers[workerId].call({
472 type: WorkerMessage.spawn,
473 entityId,
474 components
475 });
476 this.#remember(view, workerId);
477 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
478 this.#queueReplication(replicationSpawn(view));
479 this.#recalculateActivation(this.now);
480 this.#syncGhosts();
481 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
482 return entityId;
483 }
484
485 isCharacterOnline (characterId)
486 {
487 return this.characterEntities.has(characterId);
488 }
489
490 reattachCharacterSession (characterId, sessionId)
491 {
492 const entityId = this.characterEntities.get(characterId | 0);
493 if (!entityId)
494 { return null; }
495 const record = this.directory.get(entityId);
496 if (!record)
497 { return null; }
498 const result = this.workers[record.workerId].call({
499 type: WorkerMessage.reattachSession,
500 characterId,
501 sessionId
502 });
503 if (!result?.ok)
504 { return null; }
505 this.market?.reattachSession?.(characterId, sessionId);
506 return entityId;
507 }
508
509 spawnEntity (components, options = {})
510 {
511 const entityId = options.entityId ?? this.nextEntityId++;
512 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
513 const position = components.position;
514 if (!position)
515 { throw new Error("spawnEntity requires position."); }
516 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
517 position.dimensionId = dimensionId;
518 if (options.requireResident)
519 {
520 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
521 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId))
522 { return null; }
523 const view = this.workers[workerId].call({
524 type: WorkerMessage.spawn,
525 entityId,
526 components
527 });
528 this.#remember(view, workerId);
529 if (components.appearance)
530 { this.#queueReplication(replicationSpawn(view)); }
531 this.#syncGhosts();
532 return entityId;
533 }
534 if (components.chunkLoader)
535 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); }
536 else
537 {
538 this.#ensureRegion(
539 tileToRegion(position.tileX),
540 tileToRegion(position.tileY),
541 null,
542 dimensionId
543 );
544 }
545 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
546 const view = this.workers[workerId].call({
547 type: WorkerMessage.spawn,
548 entityId,
549 components
550 });
551 this.#remember(view, workerId);
552 if (components.appearance)
553 { this.#queueReplication(replicationSpawn(view)); }
554 this.#recalculateActivation(this.now);
555 this.#syncGhosts();
556 return entityId;
557 }
558
559 despawnEntity (entityId)
560 {
561 const record = this.directory.get(entityId);
562 if (!record)
563 { return; }
564 const dropped = this.workers[record.workerId].call({
565 type: WorkerMessage.despawn,
566 entityId
567 });
568 if (dropped)
569 { this.#queueReplication(replicationDespawn(dropped)); }
570 this.#forget(entityId);
571 }
572
573 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
574 {
575 const loaders = this.#allLoaders();
576 const { chunkSim } = accumulateLoaderRefs(loaders);
577 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0;
578 }
579
580 updateCourierFlight (entityId, flightPatch, now = this.now)
581 {
582 const record = this.directory.get(entityId);
583 if (!record)
584 { return { despawned: true, entityId }; }
585 const tileX = Math.floor(flightPatch.x);
586 const tileY = Math.floor(flightPatch.y);
587 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
588 const owner = this.#ownerOfTile(tileX, tileY, dimensionId);
589 if (owner == null || owner !== record.workerId)
590 {
591 this.despawnEntity(entityId);
592 return { despawned: true, entityId };
593 }
594 const result = this.workers[owner].call({
595 type: WorkerMessage.updateFlight,
596 entityId,
597 flight: flightPatch,
598 now
599 });
600 if (result?.transferRequest)
601 {
602 const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);
603 this.#recalculateActivation(now);
604 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
605 if (move)
606 {
607 this.#applyMoveToDirectory(move);
608 return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };
609 }
610 this.despawnEntity(entityId);
611 return { despawned: true, entityId };
612 }
613 if (result?.event)
614 {
615 this.#applyMoveToDirectory(result.event);
616 return { event: result.event };
617 }
618 return null;
619 }
620
621 applyBag (entityId, bag)
622 {
623 const record = this.directory.get(entityId);
624 if (!record)
625 { return null; }
626 return this.workers[record.workerId].call({
627 type: WorkerMessage.applyBag,
628 entityId,
629 bag
630 });
631 }
632
633 /**
634 * Persist hair + patch live appearance; returns public view.
635 */
636 setCharacterHair (characterId, hair)
637 {
638 const row = this.stateDb.updateCharacterHair(characterId, hair);
639 const entityId = this.characterEntities.get(characterId);
640 if (!entityId)
641 { return { row, view: null }; }
642 const fields = appearanceHairFields({
643 sex: row.sex,
644 style: hair.style,
645 hue: hair.hue,
646 saturation: hair.saturation,
647 darkness: hair.darkness
648 });
649 const record = this.directory.get(entityId);
650 if (!record)
651 { return { row, view: null }; }
652 const view = this.workers[record.workerId].call({
653 type: WorkerMessage.applyAppearance,
654 entityId,
655 appearance: fields
656 });
657 if (view)
658 {
659 this.#remember(view, record.workerId);
660 this.#queueReplication(replicationAppearance(view));
661 }
662 return { row, view };
663 }
664
665 pushSkills (characterId, skills)
666 {
667 this.pendingPrivate.push({
668 type: "skills",
669 characterId,
670 skills
671 });
672 }
673
674 pushSpells (characterId, payload)
675 {
676 this.pendingPrivate.push({
677 type: "spells",
678 characterId,
679 ...payload
680 });
681 }
682
683 skillsOf (entityId)
684 {
685 const record = this.directory.get(entityId);
686 if (!record)
687 { return null; }
688 return this.workers[record.workerId].call({
689 type: WorkerMessage.inspectSkills,
690 entityId
691 });
692 }
693
694 spellsOf (entityId)
695 {
696 const record = this.directory.get(entityId);
697 if (!record)
698 { return null; }
699 return this.workers[record.workerId].call({
700 type: WorkerMessage.inspectSpells,
701 entityId
702 });
703 }
704
705 staminaOf (entityId)
706 {
707 const record = this.directory.get(entityId);
708 if (!record)
709 { return null; }
710 return this.workers[record.workerId].call({
711 type: WorkerMessage.inspectStamina,
712 entityId
713 });
714 }
715
716 pushInventory (characterId, bag)
717 {
718 this.pendingPrivate.push({
719 type: "inventory",
720 characterId,
721 inventory: bag.inventory,
722 equipment: bag.equipment,
723 vault: bag.vault,
724 vaultReserved: bag.vaultReserved
725 });
726 }
727
728 dispatchPigeon ({ characterId, destination, cargo })
729 {
730 const entityId = this.characterEntities.get(characterId);
731 const position = entityId ? this.positionOf(entityId) : null;
732 if (!position)
733 {
734 const error = new Error("Enter the world before sending a pigeon.");
735 error.userFacing = true;
736 throw error;
737 }
738 return this.courier.dispatchFromPlayer({
739 characterId,
740 originTileX: position.tileX,
741 originTileY: position.tileY,
742 destination,
743 cargo
744 });
745 }
746
747 /**
748 * Path an idle CE clerk to a staff-side station tile.
749 */
750 stationExchangeClerk (stationTileX, stationTileY)
751 {
752 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
753 if (owner == null)
754 { return { ok: false, reason: "unowned" }; }
755 return this.workers[owner].call({
756 type: WorkerMessage.stationExchangeClerk,
757 stationTileX,
758 stationTileY
759 });
760 }
761
762 /**
763 * When a player uses a marketplace counter, path idle CE clerks to the
764 * opposite side of each adjacent counter (staff side).
765 */
766 stationExchangeClerks (playerTileX, playerTileY)
767 {
768 const results = [];
769 for (const tile of this.market?.marketTiles ?? [])
770 {
771 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
772 { continue; }
773 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
774 { continue; }
775 const stationTileX = tile.tileX + (tile.tileX - playerTileX);
776 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
777 if (stationTileX === playerTileX && stationTileY === playerTileY)
778 { continue; }
779 results.push(this.stationExchangeClerk(stationTileX, stationTileY));
780 }
781 return results;
782 }
783
784 /** Release a CE clerk stationed at the given staff-side tile. */
785 releaseExchangeClerk (stationTileX, stationTileY)
786 {
787 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
788 if (owner == null)
789 { return { ok: false, reason: "unowned" }; }
790 return this.workers[owner].call({
791 type: WorkerMessage.releaseExchangeClerk,
792 stationTileX,
793 stationTileY
794 });
795 }
796
797 despawnCharacter (characterId)
798 {
799 this.market?.leaveExchangeStations?.(characterId);
800 const entityId = this.characterEntities.get(characterId);
801 if (!entityId)
802 { return; }
803 const record = this.directory.get(entityId);
804 if (!record)
805 {
806 this.characterEntities.delete(characterId);
807 return;
808 }
809 this.#saveBag(entityId, record.workerId);
810 const dropped = this.workers[record.workerId].call({
811 type: WorkerMessage.despawnCharacter,
812 characterId
813 });
814 if (dropped)
815 {
816 this.stateDb.saveCharacterPosition(
817 characterId,
818 dropped.tileX,
819 dropped.tileY,
820 dropped.gait ?? GAIT.walk,
821 dropped.dimensionId ?? OVERWORLD_ID
822 );
823 if (dropped.health != null)
824 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
825 this.#queueReplication(replicationDespawn(dropped));
826 }
827 this.#forget(entityId);
828 this.#recalculateActivation(this.now);
829 this.#syncGhosts();
830 }
831
832 entityForCharacter (characterId)
833 {
834 return this.characterEntities.get(characterId) ?? null;
835 }
836
837 entityRecord (entityId)
838 {
839 const record = this.directory.get(entityId);
840 return record ? { ...record } : null;
841 }
842
843 positionOf (entityId)
844 {
845 const record = this.directory.get(entityId);
846 return record
847 ? {
848 tileX: record.tileX,
849 tileY: record.tileY,
850 dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID)
851 }
852 : null;
853 }
854
855 bagOf (entityId)
856 {
857 const record = this.directory.get(entityId);
858 if (!record)
859 { return null; }
860 return this.workers[record.workerId].call({
861 type: WorkerMessage.inspectBag,
862 entityId
863 });
864 }
865
866 snapshotFor (entityId)
867 {
868 const record = this.directory.get(entityId);
869 if (!record)
870 { return []; }
871 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
872 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
873 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId));
874 }
875
876 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
877 snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS)
878 {
879 const record = this.directory.get(entityId);
880 if (!record)
881 { return []; }
882 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
883 const centerChunkX = tileToChunk(record.tileX);
884 const centerChunkY = tileToChunk(record.tileY);
885 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
886 const entityKeys = new Set(
887 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
888 .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId))
889 );
890 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
891 .map((coord) =>
892 {
893 const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId);
894 const staticOnly = !entityKeys.has(key);
895 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId);
896 return { ...snapshot, staticOnly };
897 });
898 }
899
900 snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
901 {
902 const dim = normalizeDimensionId(dimensionId);
903 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim));
904 if (owner == null)
905 { return this.#syntheticSnapshot(chunkX, chunkY, dim); }
906 return this.workers[owner].call({
907 type: WorkerMessage.snapshotChunk,
908 chunkX,
909 chunkY,
910 dimensionId: dim,
911 staticOnly: !!staticOnly
912 });
913 }
914
915 findOpenSpawn ()
916 {
917 const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID);
918 for (const coord of coords)
919 {
920 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID);
921 if (!data.open)
922 { continue; }
923 for (let localY = 0; localY < CHUNK_SIZE; localY++)
924 {
925 for (let localX = 0; localX < CHUNK_SIZE; localX++)
926 {
927 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
928 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
929 if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID))
930 { return { tileX, tileY, dimensionId: OVERWORLD_ID }; }
931 }
932 }
933 }
934 return null;
935 }
936
937 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
938 #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID)
939 {
940 const dim = normalizeDimensionId(dimensionId);
941 return this.#findNearbyEnterable(tileX, tileY, radius, dim)
942 ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn());
943 }
944
945 #isDimensionUsable (dimensionId)
946 {
947 const dim = normalizeDimensionId(dimensionId);
948 if (dim === OVERWORLD_ID)
949 { return true; }
950 const record = this.getDimensionRecord(dim);
951 if (!record)
952 { return false; }
953 if (record.deletedAt != null)
954 { return false; }
955 if (record.purgeAfter != null && record.purgeAfter <= this.now)
956 { return false; }
957 return true;
958 }
959
960 #loadDimensionsCache ()
961 {
962 const map = new Map();
963 for (const dim of this.worldDb.listDimensions(this.activeRevisionId))
964 { map.set(dim.dimensionId, dim); }
965 if (!map.has(OVERWORLD_ID))
966 {
967 map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, {
968 defaultGroundTypeId: this.settings.defaultGroundTypeId
969 }));
970 }
971 return map;
972 }
973
974 getDimensionRecord (dimensionId)
975 {
976 const dim = normalizeDimensionId(dimensionId);
977 return this.dimensions?.get(dim)
978 ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim)
979 ?? (dim === OVERWORLD_ID
980 ? defaultDimensionRecord(OVERWORLD_ID, {
981 defaultGroundTypeId: this.settings.defaultGroundTypeId
982 })
983 : null);
984 }
985
986 listDimensionRecords ()
987 {
988 return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))];
989 }
990
991 #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID)
992 {
993 const dim = normalizeDimensionId(dimensionId);
994 for (let radius = 0; radius <= maxRadius; radius++)
995 {
996 for (let dy = -radius; dy <= radius; dy++)
997 {
998 for (let dx = -radius; dx <= radius; dx++)
999 {
1000 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1001 { continue; }
1002 const tileX = originX + dx;
1003 const tileY = originY + dy;
1004 if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim))
1005 { return { tileX, tileY, dimensionId: dim }; }
1006 }
1007 }
1008 }
1009 return null;
1010 }
1011
1012 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
1013 {
1014 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1015 if (!data.open)
1016 { return false; }
1017 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1018 }
1019
1020 debugWorld ()
1021 {
1022 const loaders = this.#allLoaders();
1023 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
1024 const simulatingChunks = [...chunkSim.entries()]
1025 .filter(([, count]) => count > 0)
1026 .map(([key]) => key)
1027 .sort();
1028 return {
1029 tickIndex: this.tickIndex,
1030 workerCount: this.workers.length,
1031 workerMode: this.workerMode,
1032 simulatingChunks,
1033 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
1034 ...parseRegionKey(key),
1035 workerId,
1036 state: REGION_RUNTIME_STATE.resident,
1037 refs: regionRes.get(key) ?? 0,
1038 graceUntil: this.regionGraceUntil.get(key) ?? null
1039 })),
1040 entities: [...this.directory.values()].map((entity) => ({
1041 entityId: entity.entityId,
1042 workerId: entity.workerId,
1043 tileX: entity.tileX,
1044 tileY: entity.tileY,
1045 characterId: entity.characterId
1046 }))
1047 };
1048 }
1049
1050 async shutdown ()
1051 {
1052 for (const characterId of [...this.characterEntities.keys()])
1053 { this.despawnCharacter(characterId); }
1054 this.forceUnloadAll();
1055 await Promise.all(this.workers.map((worker) => worker.terminate()));
1056 }
1057
1058 forceUnloadAll ()
1059 {
1060 for (const key of [...this.regionOwner.keys()])
1061 {
1062 const { regionX, regionY } = parseRegionKey(key);
1063 this.#unloadRegion(regionX, regionY);
1064 }
1065 }
1066
1067 #configureWorkers ()
1068 {
1069 for (const worker of this.workers)
1070 {
1071 worker.call({
1072 type: WorkerMessage.configure,
1073 settings: this.settings,
1074 activeRevisionId: this.activeRevisionId
1075 });
1076 }
1077 }
1078
1079 #routeCommand (item)
1080 {
1081 if (item.command.type === "respawn")
1082 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
1083 if (item.command.type === "enter-doorway")
1084 {
1085 return this.#relocateCharacterThroughDoorway(
1086 item.sessionId,
1087 item.command.characterId,
1088 item.command.tileX,
1089 item.command.tileY
1090 );
1091 }
1092 if (
1093 item.command.type === "open-market"
1094 || item.command.type === "place-market-sell"
1095 || item.command.type === "place-market-buy"
1096 || item.command.type === "cancel-market-order"
1097 || item.command.type === "close-market"
1098 )
1099 {
1100 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1101 return result?.events ?? [];
1102 }
1103 if (
1104 item.command.type === "open-bounty"
1105 || item.command.type === "raise-bounty"
1106 || item.command.type === "get-character-bounty"
1107 || item.command.type === "close-bounty"
1108 )
1109 {
1110 const result = this.bounty.handleCommand(item.sessionId, item.command);
1111 return result?.events ?? [];
1112 }
1113 if (
1114 item.command.type === "open-barber"
1115 || item.command.type === "set-hair"
1116 || item.command.type === "close-barber"
1117 )
1118 {
1119 const result = this.barber.handleCommand(item.sessionId, item.command);
1120 return result?.events ?? [];
1121 }
1122 if (
1123 item.command.type === "dialogue-choose"
1124 || item.command.type === "dialogue-advance"
1125 || item.command.type === "close-dialogue"
1126 || item.command.type === "request-quests"
1127 )
1128 { return this.#handleQuestCommand(item); }
1129 const entityId = this.characterEntities.get(item.command.characterId);
1130 const record = entityId ? this.directory.get(entityId) : null;
1131 if (!record)
1132 {
1133 const error = new Error("Character is not in the world.");
1134 error.userFacing = true;
1135 throw error;
1136 }
1137 if (item.command.type === "drop-item" && item.command.groundItemId == null)
1138 { item.command.groundItemId = this.nextGroundItemId++; }
1139 if (item.command.type === "attack")
1140 {
1141 const targetRecord = this.directory.get(item.command.targetEntityId);
1142 if (!targetRecord)
1143 {
1144 const error = new Error("Target is not here.");
1145 error.userFacing = true;
1146 throw error;
1147 }
1148 const events = this.#finishRoutedCommand(item, record);
1149 if (targetRecord.workerId !== record.workerId)
1150 {
1151 this.workers[targetRecord.workerId].call({
1152 type: WorkerMessage.remoteCombatEngage,
1153 attackerEntityId: record.entityId,
1154 targetEntityId: item.command.targetEntityId,
1155 now: item.receivedAt ?? this.now
1156 });
1157 }
1158 return events;
1159 }
1160 return this.#finishRoutedCommand(item, record);
1161 }
1162
1163 #finishRoutedCommand (item, record)
1164 {
1165 const result = this.workers[record.workerId].call({
1166 type: WorkerMessage.command,
1167 sessionId: item.sessionId,
1168 command: item.command,
1169 now: item.receivedAt ?? this.now
1170 });
1171 const view = this.workers[record.workerId].call({
1172 type: WorkerMessage.inspect,
1173 entityId: record.entityId
1174 });
1175 if (view)
1176 { this.#remember(view, record.workerId); }
1177 if (result?.private)
1178 { this.#saveBagFromView(item.command.characterId, result.private); }
1179 if (result?.appearanceChanged && view)
1180 { this.#queueReplication(replicationAppearance(view)); }
1181 if (result?.remainder)
1182 {
1183 this.stateDb.saveInheritance(
1184 this.stateDb.getCharacter(item.command.characterId).account_id,
1185 { slots: result.remainder }
1186 );
1187 }
1188 for (const event of result?.events ?? [])
1189 { this.#persistGroundEvent(event); }
1190 const events = [];
1191 for (const event of result?.events ?? [])
1192 {
1193 if (event.type === "skills-updated")
1194 {
1195 this.#applySkillsUpdated(event);
1196 events.push(...this.#skillLevelUpEvents(event));
1197 continue;
1198 }
1199 if (event.type === "spells-updated")
1200 {
1201 this.#applySpellsUpdated(event);
1202 continue;
1203 }
1204 if (event.type === "open-dialogue")
1205 {
1206 events.push(...this.#handleOpenDialogue(event));
1207 continue;
1208 }
1209 events.push(event);
1210 }
1211 if (item.command.type === "attack" && item.command.targetEntityId != null)
1212 {
1213 events.push(...this.#mapQuestPrivateEvents(
1214 this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []
1215 ));
1216 }
1217 if (result?.private)
1218 {
1219 events.push({
1220 type: "inventory",
1221 sessionId: item.sessionId,
1222 bank: !!result.bank,
1223 cauldron: result.cauldron,
1224 cauldronState: result.cauldronState ?? null,
1225 alchemyResult: result.alchemyResult ?? null,
1226 ...result.private
1227 });
1228 }
1229 if (result?.statusEffectsChanged && view)
1230 {
1231 events.push({
1232 type: "status-effects",
1233 sessionId: item.sessionId,
1234 characterId: view.characterId ?? item.command.characterId,
1235 effects: view.statusEffects ?? [],
1236 blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind")
1237 });
1238 }
1239 if (result?.healthChanged && view)
1240 {
1241 events.push({
1242 type: "entity-health",
1243 entityId: view.entityId,
1244 characterId: view.characterId ?? item.command.characterId,
1245 health: view.health,
1246 maxHealth: view.maxHealth,
1247 tileX: view.tileX,
1248 tileY: view.tileY
1249 });
1250 }
1251 return events;
1252 }
1253
1254 #applyRemoteMelee (payload)
1255 {
1256 const targetRecord = this.directory.get(payload.targetId);
1257 if (!targetRecord)
1258 { return []; }
1259 const result = this.workers[targetRecord.workerId].call({
1260 ...payload,
1261 type: WorkerMessage.applyRemoteMelee
1262 });
1263 const events = [];
1264 for (const event of result?.events ?? [])
1265 {
1266 if (event.type === "entity-despawn")
1267 { this.#forget(event.entityId); }
1268 if (event.type === "skills-updated")
1269 {
1270 this.#applySkillsUpdated(event);
1271 events.push(...this.#skillLevelUpEvents(event));
1272 continue;
1273 }
1274 if (event.type === "spells-updated")
1275 {
1276 this.#applySpellsUpdated(event);
1277 continue;
1278 }
1279 if (event.type === "player-died")
1280 {
1281 events.push(...this.#applyPlayerDeath(event));
1282 continue;
1283 }
1284 if (event.type === "mob-killed")
1285 {
1286 events.push(...this.#applyMobKilled(event));
1287 continue;
1288 }
1289 this.#persistGroundEvent(event);
1290 if (event.type !== "skills-updated")
1291 { events.push(event); }
1292 }
1293 for (const forward of result?.forwards ?? [])
1294 {
1295 if (forward.type !== "forward-combat-xp")
1296 { continue; }
1297 const attackerRecord = this.directory.get(forward.entityId);
1298 if (!attackerRecord)
1299 { continue; }
1300 const xpResult = this.workers[attackerRecord.workerId].call({
1301 type: WorkerMessage.applyCombatHitXp,
1302 entityId: forward.entityId,
1303 profile: forward.profile,
1304 damage: forward.damage
1305 });
1306 for (const xpEvent of xpResult?.events ?? [])
1307 {
1308 if (xpEvent.type === "skills-updated")
1309 {
1310 this.#applySkillsUpdated(xpEvent);
1311 events.push(...this.#skillLevelUpEvents(xpEvent));
1312 continue;
1313 }
1314 events.push(xpEvent);
1315 }
1316 }
1317 return events;
1318 }
1319
1320 #applyRemoteRanged (payload)
1321 {
1322 const targetRecord = this.directory.get(payload.targetId);
1323 if (!targetRecord)
1324 { return []; }
1325 const result = this.workers[targetRecord.workerId].call({
1326 ...payload,
1327 type: WorkerMessage.applyRemoteRanged
1328 });
1329 const events = [];
1330 for (const event of result?.events ?? [])
1331 {
1332 if (event.type === "entity-despawn")
1333 { this.#forget(event.entityId); }
1334 if (event.type === "skills-updated")
1335 {
1336 this.#applySkillsUpdated(event);
1337 events.push(...this.#skillLevelUpEvents(event));
1338 continue;
1339 }
1340 if (event.type === "spells-updated")
1341 {
1342 this.#applySpellsUpdated(event);
1343 continue;
1344 }
1345 if (event.type === "player-died")
1346 {
1347 events.push(...this.#applyPlayerDeath(event));
1348 continue;
1349 }
1350 if (event.type === "mob-killed")
1351 {
1352 events.push(...this.#applyMobKilled(event));
1353 continue;
1354 }
1355 this.#persistGroundEvent(event);
1356 if (event.type !== "skills-updated")
1357 { events.push(event); }
1358 }
1359 for (const forward of result?.forwards ?? [])
1360 {
1361 if (forward.type !== "forward-combat-xp")
1362 { continue; }
1363 const attackerRecord = this.directory.get(forward.entityId);
1364 if (!attackerRecord)
1365 { continue; }
1366 const xpResult = this.workers[attackerRecord.workerId].call({
1367 type: WorkerMessage.applyCombatHitXp,
1368 entityId: forward.entityId,
1369 profile: forward.profile,
1370 damage: forward.damage
1371 });
1372 for (const xpEvent of xpResult?.events ?? [])
1373 {
1374 if (xpEvent.type === "skills-updated")
1375 {
1376 this.#applySkillsUpdated(xpEvent);
1377 events.push(...this.#skillLevelUpEvents(xpEvent));
1378 continue;
1379 }
1380 events.push(xpEvent);
1381 }
1382 }
1383 return events;
1384 }
1385
1386 #handleQuestCommand (item)
1387 {
1388 const characterId = item.command.characterId | 0;
1389 const sessionId = item.sessionId;
1390 if (!this.quests)
1391 { return []; }
1392 if (item.command.type === "request-quests")
1393 {
1394 const snap = this.quests.questSnapshot(characterId);
1395 return [{ type: "quests-snapshot", sessionId, characterId, ...snap }];
1396 }
1397 if (item.command.type === "close-dialogue")
1398 {
1399 const closed = this.quests.closeDialogue(characterId, "client");
1400 return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId);
1401 }
1402 if (item.command.type === "dialogue-choose")
1403 {
1404 const result = this.quests.chooseDialogue(characterId, item.command.trigger);
1405 if (!result.ok)
1406 {
1407 const error = new Error(result.error || "Choice failed.");
1408 error.userFacing = true;
1409 throw error;
1410 }
1411 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1412 }
1413 if (item.command.type === "dialogue-advance")
1414 {
1415 const result = this.quests.advanceDialogue(characterId);
1416 if (!result.ok)
1417 {
1418 const error = new Error(result.error || "Cannot advance.");
1419 error.userFacing = true;
1420 throw error;
1421 }
1422 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1423 }
1424 return [];
1425 }
1426
1427 #handleOpenDialogue (event)
1428 {
1429 const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId);
1430 if (!result.ok)
1431 {
1432 return [{
1433 type: "toast",
1434 characterId: event.characterId,
1435 sessionId: event.sessionId,
1436 message: result.error || "Nothing to say."
1437 }];
1438 }
1439 this.#pinDialogueNpc(event.entityId, event.characterId);
1440 return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId);
1441 }
1442
1443 #pinDialogueNpc (entityId, characterId)
1444 {
1445 const record = this.directory.get(entityId | 0);
1446 if (!record)
1447 { return; }
1448 this.workers[record.workerId]?.call?.({
1449 type: WorkerMessage.pinDialogue,
1450 entityId: entityId | 0,
1451 characterId: characterId | 0
1452 });
1453 }
1454
1455 #unpinDialogueNpc (entityId, characterId)
1456 {
1457 const record = this.directory.get(entityId | 0);
1458 if (!record)
1459 { return; }
1460 this.workers[record.workerId]?.call?.({
1461 type: WorkerMessage.unpinDialogue,
1462 entityId: entityId | 0,
1463 characterId: characterId | 0
1464 });
1465 }
1466
1467 #mapQuestPrivateEvents (events, sessionId = null, characterId = null)
1468 {
1469 const out = [];
1470 let needSnapshot = false;
1471 for (const event of events ?? [])
1472 {
1473 const cid = event.characterId ?? characterId;
1474 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1475 if (event.type === "dialogueStep")
1476 {
1477 out.push({
1478 type: "dialogue-step",
1479 sessionId: sid,
1480 characterId: cid,
1481 dialogueId: event.dialogueId,
1482 stepId: event.stepId,
1483 label: event.label,
1484 npcEntityId: event.npcEntityId,
1485 lines: event.lines
1486 });
1487 }
1488 else if (event.type === "dialogueChoices")
1489 {
1490 out.push({
1491 type: "dialogue-choices",
1492 sessionId: sid,
1493 characterId: cid,
1494 dialogueId: event.dialogueId,
1495 stepId: event.stepId,
1496 npcEntityId: event.npcEntityId,
1497 triggers: event.triggers
1498 });
1499 }
1500 else if (event.type === "dialogueClose")
1501 {
1502 if (event.npcEntityId != null && cid != null)
1503 { this.#unpinDialogueNpc(event.npcEntityId, cid); }
1504 out.push({
1505 type: "dialogue-close",
1506 sessionId: sid,
1507 characterId: cid,
1508 reason: event.reason
1509 });
1510 }
1511 else if (event.type === "questStepComplete")
1512 {
1513 out.push({
1514 type: "quest-step-complete",
1515 sessionId: sid,
1516 characterId: cid,
1517 questId: event.questId,
1518 title: event.title
1519 });
1520 needSnapshot = true;
1521 }
1522 else if (event.type === "questsDirty")
1523 { needSnapshot = true; }
1524 else if (event.type === "inventoryDirty" && cid != null)
1525 {
1526 const onlineId = this.characterEntities.get(cid | 0);
1527 if (onlineId)
1528 {
1529 const live = this.bagOf(onlineId);
1530 if (live)
1531 { this.pushInventory(cid, live); }
1532 }
1533 }
1534 }
1535 if (needSnapshot && characterId != null)
1536 {
1537 const snap = this.quests.questSnapshot(characterId);
1538 out.push({
1539 type: "quests-snapshot",
1540 sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
1541 characterId,
1542 ...snap
1543 });
1544 }
1545 return out;
1546 }
1547
1548 #sessionIdForCharacter (characterId)
1549 {
1550 const entityId = this.characterEntities.get(characterId | 0);
1551 const record = entityId != null ? this.directory.get(entityId) : null;
1552 return record?.sessionId ?? null;
1553 }
1554
1555 #applyMobKilled (event)
1556 {
1557 const out = [event];
1558 const attackerRecord = this.directory.get(event.attackerId);
1559 const killerCharacterId = attackerRecord?.characterId ?? null;
1560 const killerPos = attackerRecord
1561 ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
1562 : null;
1563 if (killerCharacterId && this.quests)
1564 {
1565 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
1566 mobTypeId: event.mobTypeId,
1567 spawnerId: event.spawnerId
1568 })));
1569 }
1570 out.push(...this.#mapQuestPrivateEvents(
1571 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
1572 ));
1573 let bountyAwarded = 0;
1574 if (killerCharacterId && (event.bounty | 0) > 0)
1575 {
1576 bountyAwarded = event.bounty | 0;
1577 const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1578 out.push({
1579 type: "toast",
1580 characterId: killerCharacterId,
1581 message: `Bounty +${bountyAwarded} (total ${total})`
1582 });
1583 }
1584
1585 if (killerCharacterId && killerPos)
1586 {
1587 if (bountyAwarded > 0)
1588 { this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); }
1589 if (event.townGuard)
1590 { this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); }
1591 }
1592 return out;
1593 }
1594
1595 /**
1596 * Send up to `count` town guards at the killer. Prefer idle guards.
1597 * When `spawnerId` is set, only that spawner's guards are used.
1598 */
1599 #dispatchTownGuards (targetEntityId, killerPos, spawnerId, count)
1600 {
1601 const want = Math.max(0, count | 0);
1602 if (want <= 0 || targetEntityId == null || !killerPos)
1603 { return; }
1604 const candidates = [];
1605 for (const worker of this.workers)
1606 {
1607 const result = worker.call({
1608 type: WorkerMessage.listTownGuardsNear,
1609 tileX: killerPos.tileX,
1610 tileY: killerPos.tileY,
1611 spawnerId,
1612 limit: 32
1613 });
1614 for (const guard of result?.guards ?? [])
1615 { candidates.push(guard); }
1616 }
1617 candidates.sort((a, b) => Number(a.busy) - Number(b.busy));
1618 let sent = 0;
1619 for (const guard of candidates)
1620 {
1621 if (sent >= want)
1622 { break; }
1623 if (guard.entityId === targetEntityId)
1624 { continue; }
1625 const record = this.directory.get(guard.entityId);
1626 if (!record)
1627 { continue; }
1628 this.workers[record.workerId].call({
1629 type: WorkerMessage.engageTarget,
1630 attackerEntityId: guard.entityId,
1631 targetEntityId,
1632 now: this.now
1633 });
1634 sent += 1;
1635 }
1636 }
1637
1638 #applyPlayerDeath (event)
1639 {
1640 const record = this.directory.get(event.entityId);
1641 if (!record)
1642 { return [event]; }
1643 this.stateDb.setCharacterDead(event.characterId, true);
1644 this.stateDb.saveCharacterPosition(
1645 event.characterId,
1646 event.tileX,
1647 event.tileY,
1648 record.gait ?? GAIT.walk,
1649 record.dimensionId ?? OVERWORLD_ID
1650 );
1651 this.bounty?.settleKill(
1652 event.characterId,
1653 event.attackerId,
1654 event.tileX,
1655 event.tileY
1656 );
1657 for (const worker of this.workers)
1658 {
1659 worker.call({
1660 type: WorkerMessage.clearCombat,
1661 entityId: event.entityId,
1662 targetEntityId: event.entityId
1663 });
1664 }
1665 const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()
1666 || "someone";
1667 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1668 const killerName = attackerRecord?.appearance
1669 ? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()
1670 || attackerRecord.appearance.displayName
1671 || "someone")
1672 : "someone";
1673 const corpseOrigin = lootOrigin(victimName, killerName);
1674 const result = this.workers[record.workerId].call({
1675 type: WorkerMessage.spawnCorpseDrops,
1676 characterId: event.characterId,
1677 tileX: event.tileX,
1678 tileY: event.tileY,
1679 now: this.now,
1680 drops: [
1681 {
1682 groundItemId: this.nextGroundItemId++,
1683 stack: attachOrigins({
1684 itemId: ItemId.bones,
1685 quantity: 1,
1686 origins: [{ origin: corpseOrigin, quantity: 1 }]
1687 })
1688 },
1689 {
1690 groundItemId: this.nextGroundItemId++,
1691 stack: attachOrigins({
1692 itemId: ItemId.skull,
1693 quantity: 1,
1694 origins: [{ origin: corpseOrigin, quantity: 1 }]
1695 })
1696 }
1697 ]
1698 });
1699 const events = [event];
1700 for (const dropEvent of result?.events ?? [])
1701 {
1702 this.#persistGroundEvent(dropEvent);
1703 events.push(dropEvent);
1704 }
1705 return events;
1706 }
1707
1708 #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY)
1709 {
1710 const entityId = this.characterEntities.get(characterId);
1711 const record = entityId ? this.directory.get(entityId) : null;
1712 if (!record)
1713 {
1714 const error = new Error("Character is not in the world.");
1715 error.userFacing = true;
1716 throw error;
1717 }
1718 const tileX = doorwayTileX | 0;
1719 const tileY = doorwayTileY | 0;
1720 if (chebyshev(record.tileX, record.tileY, tileX, tileY) > 1)
1721 {
1722 const error = new Error("You are too far from that doorway.");
1723 error.userFacing = true;
1724 throw error;
1725 }
1726 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1727 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId);
1728 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
1729 if (block?.typeId !== BlockType.doorway)
1730 {
1731 const error = new Error("There is no doorway there.");
1732 error.userFacing = true;
1733 throw error;
1734 }
1735 const config = block.config && typeof block.config === "object" ? block.config : null;
1736 const targetRaw = config?.targetDimensionId;
1737 if (targetRaw == null || String(targetRaw).trim() === "")
1738 {
1739 const error = new Error("That doorway leads nowhere.");
1740 error.userFacing = true;
1741 throw error;
1742 }
1743 const targetDimensionId = normalizeDimensionId(targetRaw);
1744 const destTileX = Number(config.tileX);
1745 const destTileY = Number(config.tileY);
1746 if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY))
1747 {
1748 const error = new Error("That doorway leads nowhere.");
1749 error.userFacing = true;
1750 throw error;
1751 }
1752 const destX = destTileX | 0;
1753 const destY = destTileY | 0;
1754 if (!this.#isDimensionUsable(targetDimensionId))
1755 {
1756 const error = new Error("That place is no longer reachable.");
1757 error.userFacing = true;
1758 throw error;
1759 }
1760 if (!this.isEnterable(destX, destY, targetDimensionId))
1761 {
1762 const error = new Error("The other side is blocked.");
1763 error.userFacing = true;
1764 throw error;
1765 }
1766
1767 const events = [];
1768 if (this.quests)
1769 {
1770 const closed = this.quests.closeDialogue(characterId, "doorway");
1771 if (closed?.events?.length)
1772 { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); }
1773 }
1774
1775 const loader = { ...DEFAULT_CHUNK_LOADER };
1776 this.#ensureCoverage(destX, destY, loader, targetDimensionId);
1777 const result = this.workers[record.workerId].call({
1778 type: WorkerMessage.relocateEntity,
1779 entityId,
1780 tileX: destX,
1781 tileY: destY,
1782 dimensionId: targetDimensionId
1783 });
1784 if (!result?.accepted)
1785 {
1786 const error = new Error("Could not enter that doorway.");
1787 error.userFacing = true;
1788 throw error;
1789 }
1790 let moveEvents = [];
1791 if (result.transferRequest)
1792 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1793 else if (result.event)
1794 {
1795 this.#applyMoveToDirectory(result.event);
1796 moveEvents = [result.event];
1797 const view = this.workers[record.workerId].call({
1798 type: WorkerMessage.inspect,
1799 entityId
1800 });
1801 if (view)
1802 { this.#remember(view, record.workerId); }
1803 }
1804 if (!moveEvents.length)
1805 {
1806 const error = new Error("Could not enter that doorway.");
1807 error.userFacing = true;
1808 throw error;
1809 }
1810 this.stateDb.saveCharacterPosition(
1811 characterId,
1812 destX,
1813 destY,
1814 record.gait ?? GAIT.walk,
1815 targetDimensionId
1816 );
1817 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
1818 this.#recalculateActivation(this.now);
1819 this.#syncGhosts();
1820 const dimRecord = this.getDimensionRecord(targetDimensionId);
1821 events.push(...moveEvents, {
1822 type: "dimension-changed",
1823 sessionId,
1824 characterId,
1825 entityId,
1826 dimensionId: targetDimensionId,
1827 tileX: destX,
1828 tileY: destY,
1829 lightingMode: dimRecord?.lightingMode ?? "dayNight",
1830 seasonMode: dimRecord?.seasonMode ?? "auto"
1831 });
1832 return events;
1833 }
1834
1835 #respawnCharacter (sessionId, characterId)
1836 {
1837 const row = this.stateDb.getCharacter(characterId);
1838 if (!row?.is_dead)
1839 {
1840 const error = new Error("You are not dead.");
1841 error.userFacing = true;
1842 throw error;
1843 }
1844 const entityId = this.characterEntities.get(characterId);
1845 const record = entityId ? this.directory.get(entityId) : null;
1846 if (!record)
1847 {
1848 const error = new Error("Character is not in the world.");
1849 error.userFacing = true;
1850 throw error;
1851 }
1852 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
1853 if (!destination)
1854 {
1855 const error = new Error("No open tile is available for respawn.");
1856 error.userFacing = true;
1857 throw error;
1858 }
1859 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
1860 const loader = { ...DEFAULT_CHUNK_LOADER };
1861 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID);
1862 const result = this.workers[record.workerId].call({
1863 type: WorkerMessage.applyRespawn,
1864 entityId,
1865 sessionId,
1866 tileX: destination.tileX,
1867 tileY: destination.tileY,
1868 maxHealth: playerMaxHealth(skills),
1869 maxStamina: playerMaxStamina(skills)
1870 });
1871 if (!result?.accepted)
1872 {
1873 const error = new Error("That respawn tile is no longer available.");
1874 error.userFacing = true;
1875 throw error;
1876 }
1877 let moveEvents = [];
1878 if (result.transferRequest)
1879 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1880 else if (result.event)
1881 {
1882 this.#applyMoveToDirectory(result.event);
1883 moveEvents = [result.event];
1884 const view = this.workers[record.workerId].call({
1885 type: WorkerMessage.inspect,
1886 entityId
1887 });
1888 if (view)
1889 { this.#remember(view, record.workerId); }
1890 }
1891 if (!moveEvents.length)
1892 {
1893 const error = new Error("Respawn transfer failed.");
1894 error.userFacing = true;
1895 throw error;
1896 }
1897 this.stateDb.setCharacterDead(characterId, false);
1898 const respawnHealth = playerMaxHealth(skills);
1899 this.stateDb.saveCharacterHealth(characterId, respawnHealth);
1900 this.stateDb.saveCharacterPosition(
1901 characterId,
1902 destination.tileX,
1903 destination.tileY,
1904 record.gait ?? GAIT.walk,
1905 destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
1906 );
1907 this.#recalculateActivation(this.now);
1908 this.#syncGhosts();
1909 return [
1910 ...moveEvents,
1911 {
1912 type: "player-respawned",
1913 entityId,
1914 characterId,
1915 sessionId,
1916 tileX: destination.tileX,
1917 tileY: destination.tileY,
1918 health: playerMaxHealth(skills),
1919 maxHealth: playerMaxHealth(skills),
1920 stamina: playerMaxStamina(skills),
1921 maxStamina: playerMaxStamina(skills)
1922 }
1923 ];
1924 }
1925
1926 #refreshAltarIndex ()
1927 {
1928 const altars = [];
1929 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
1930 {
1931 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
1932 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim);
1933 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1934 {
1935 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1936 {
1937 const block = data.blocks[localY * CHUNK_SIZE + localX];
1938 if (block?.typeId !== BlockType.churchAltar)
1939 { continue; }
1940 altars.push({
1941 tileX: coord.chunk_x * CHUNK_SIZE + localX,
1942 tileY: coord.chunk_y * CHUNK_SIZE + localY,
1943 dimensionId: dim
1944 });
1945 }
1946 }
1947 }
1948 this.altarTiles = altars;
1949 }
1950
1951 #findRespawnDestination (originX, originY, entityId)
1952 {
1953 const record = this.directory.get(entityId);
1954 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
1955 const ordered = [...this.altarTiles].sort((left, right) =>
1956 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1957 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1958 );
1959 for (const altar of ordered)
1960 {
1961 const adjacent = [];
1962 for (let dy = -1; dy <= 1; dy++)
1963 {
1964 for (let dx = -1; dx <= 1; dx++)
1965 {
1966 if (dx === 0 && dy === 0)
1967 { continue; }
1968 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId });
1969 }
1970 }
1971 adjacent.sort((left, right) =>
1972 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1973 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1974 );
1975 const tile = adjacent.find((entry) =>
1976 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
1977 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
1978 );
1979 if (tile)
1980 { return tile; }
1981 }
1982 for (let radius = 0; radius <= 24; radius++)
1983 {
1984 for (let dy = -radius; dy <= radius; dy++)
1985 {
1986 for (let dx = -radius; dx <= radius; dx++)
1987 {
1988 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1989 { continue; }
1990 const tileX = originX + dx;
1991 const tileY = originY + dy;
1992 if (this.isEnterable(tileX, tileY, dimensionId)
1993 && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId))
1994 { return { tileX, tileY, dimensionId }; }
1995 }
1996 }
1997 }
1998 return this.findOpenSpawn();
1999 }
2000
2001 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
2002 {
2003 const dim = normalizeDimensionId(dimensionId);
2004 for (const record of this.directory.values())
2005 {
2006 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2007 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2008 { return true; }
2009 }
2010 return false;
2011 }
2012
2013 #recalculateActivation (now)
2014 {
2015 const loaders = this.#allLoaders();
2016 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
2017
2018 for (const [key, count] of regionRes)
2019 {
2020 if (count <= 0)
2021 { continue; }
2022 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2023 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId);
2024 this.regionGraceUntil.delete(key);
2025 }
2026
2027 for (const [key] of [...this.regionOwner.entries()])
2028 {
2029 if ((regionRes.get(key) ?? 0) > 0)
2030 { continue; }
2031 if (!this.regionGraceUntil.has(key))
2032 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
2033 if (now >= this.regionGraceUntil.get(key))
2034 {
2035 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2036 this.#unloadRegion(regionX, regionY, dimensionId);
2037 }
2038 }
2039
2040 for (const [workerId, worker] of this.workers.entries())
2041 {
2042 const chunkKeys = [];
2043 for (const [key, count] of chunkSim)
2044 {
2045 if (count <= 0)
2046 { continue; }
2047 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2048 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId)
2049 { chunkKeys.push(key); }
2050 }
2051 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
2052 }
2053 this.#syncAllReplicas();
2054
2055 const nextSimulating = new Set();
2056 for (const [key, count] of chunkSim)
2057 {
2058 if (count > 0)
2059 { nextSimulating.add(key); }
2060 }
2061 let preheated = false;
2062 for (const key of nextSimulating)
2063 {
2064 if (!this.simulatingChunkKeys.has(key))
2065 {
2066 preheated = true;
2067 break;
2068 }
2069 }
2070 this.simulatingChunkKeys = nextSimulating;
2071 if (preheated)
2072 { this.#stepSpawners(); }
2073 }
2074
2075 #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
2076 {
2077 const dim = normalizeDimensionId(dimensionId);
2078 const coverage = loaderCoverage(tileX, tileY, loader, dim);
2079 let preferred = this.#ownerOfTile(tileX, tileY, dim);
2080 for (const region of coverage.residentRegions)
2081 {
2082 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim);
2083 if (preferred == null)
2084 { preferred = owner; }
2085 }
2086 }
2087
2088 #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2089 {
2090 const dim = normalizeDimensionId(dimensionId);
2091 const key = regionKey(regionX, regionY, dim);
2092 if (this.regionOwner.has(key))
2093 { return this.regionOwner.get(key); }
2094 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim);
2095 this.workers[workerId].call({
2096 type: WorkerMessage.assignRegion,
2097 regionX,
2098 regionY,
2099 dimensionId: dim,
2100 chunks: this.#regionChunkBlobs(regionX, regionY, dim)
2101 });
2102 this.regionOwner.set(key, workerId);
2103 this.#restorePersistent(regionX, regionY, workerId);
2104 this.#restoreGroundItems(regionX, regionY, workerId);
2105 return workerId;
2106 }
2107
2108 #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2109 {
2110 const dim = normalizeDimensionId(dimensionId);
2111 const key = regionKey(regionX, regionY, dim);
2112 const workerId = this.regionOwner.get(key);
2113 if (workerId == null)
2114 { return; }
2115 const bounds = regionTileBounds(regionX, regionY);
2116 const { dropped, groundItems } = this.workers[workerId].call({
2117 type: WorkerMessage.dropRegion,
2118 regionX,
2119 regionY,
2120 dimensionId: dim
2121 });
2122 const persistent = [];
2123 for (const record of dropped ?? [])
2124 {
2125 if (record.characterId)
2126 {
2127 this.stateDb.saveCharacterPosition(
2128 record.characterId,
2129 record.tileX,
2130 record.tileY,
2131 record.gait ?? GAIT.walk,
2132 record.dimensionId ?? OVERWORLD_ID
2133 );
2134 }
2135 if (record.persistent)
2136 { persistent.push(record); }
2137 this.#forget(record.entityId);
2138 }
2139 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
2140 for (const item of groundItems ?? [])
2141 { this.stateDb.upsertGroundItem(item); }
2142 this.regionOwner.delete(key);
2143 this.regionGraceUntil.delete(key);
2144 }
2145
2146 #restorePersistent (regionX, regionY, workerId)
2147 {
2148 const bounds = regionTileBounds(regionX, regionY);
2149 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
2150 for (const row of rows)
2151 {
2152 if (this.directory.has(row.entity_id))
2153 { continue; }
2154 const components = JSON.parse(row.components_blob);
2155 const view = this.workers[workerId].call({
2156 type: WorkerMessage.spawn,
2157 entityId: row.entity_id,
2158 components
2159 });
2160 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
2161 this.#remember(view, workerId);
2162 }
2163 }
2164
2165 #applyTransfers (requests)
2166 {
2167 const events = [];
2168 for (const request of requests)
2169 {
2170 const destWorkerId = this.#ensureRegion(
2171 request.toRegionX,
2172 request.toRegionY,
2173 request.fromWorkerId,
2174 request.dimensionId ?? OVERWORLD_ID
2175 );
2176 if (destWorkerId === request.fromWorkerId)
2177 {
2178 this.workers[request.fromWorkerId].call({
2179 type: WorkerMessage.abortTransfer,
2180 entityId: request.entityId
2181 });
2182 continue;
2183 }
2184 let result;
2185 try
2186 {
2187 result = this.workers[destWorkerId].call({
2188 type: WorkerMessage.applyTransfer,
2189 payload: request.payload,
2190 destTileX: request.destTileX,
2191 destTileY: request.destTileY,
2192 dimensionId: request.dimensionId ?? OVERWORLD_ID
2193 });
2194 }
2195 catch
2196 {
2197 result = { accepted: false };
2198 }
2199 if (!result?.accepted)
2200 {
2201 this.workers[request.fromWorkerId].call({
2202 type: WorkerMessage.abortTransfer,
2203 entityId: request.entityId
2204 });
2205 continue;
2206 }
2207 this.workers[request.fromWorkerId].call({
2208 type: WorkerMessage.commitTransfer,
2209 entityId: request.entityId
2210 });
2211 this.#remember(result.entity, destWorkerId);
2212 events.push({
2213 type: "entity-move",
2214 entityId: request.entityId,
2215 fromTileX: request.fromTileX,
2216 fromTileY: request.fromTileY,
2217 fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId,
2218 tileX: result.entity.tileX,
2219 tileY: result.entity.tileY,
2220 dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID,
2221 gait: result.entity.gait
2222 });
2223 }
2224 return events;
2225 }
2226
2227 #syncAllReplicas ()
2228 {
2229 for (const [workerId, worker] of this.workers.entries())
2230 {
2231 const ownedKeys = new Set();
2232 for (const [key, owner] of this.regionOwner)
2233 {
2234 if (owner !== workerId)
2235 { continue; }
2236 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2237 for (const chunk of chunksInRegion(regionX, regionY))
2238 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); }
2239 }
2240 const replicas = [];
2241 for (const key of replicaNeededForOwnedChunks(ownedKeys))
2242 {
2243 if (ownedKeys.has(key))
2244 { continue; }
2245 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2246 replicas.push({
2247 chunkX,
2248 chunkY,
2249 dimensionId,
2250 data: this.#authoredChunk(chunkX, chunkY, dimensionId)
2251 });
2252 }
2253 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
2254 }
2255 }
2256
2257 #syncGhosts ()
2258 {
2259 const entities = [];
2260 for (const worker of this.workers)
2261 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
2262 for (const [workerId, worker] of this.workers.entries())
2263 {
2264 const ghosts = entities.filter((entity) =>
2265 {
2266 const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID);
2267 if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId)
2268 { return false; }
2269 return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim);
2270 });
2271 worker.call({ type: WorkerMessage.setGhosts, ghosts });
2272 }
2273 }
2274
2275 #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID)
2276 {
2277 const dim = normalizeDimensionId(dimensionId);
2278 const chunkX = tileToChunk(tileX);
2279 const chunkY = tileToChunk(tileY);
2280 for (const [key, owner] of this.regionOwner)
2281 {
2282 if (owner !== workerId)
2283 { continue; }
2284 const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key);
2285 if (regionDim !== dim)
2286 { continue; }
2287 for (const chunk of chunksInRegion(regionX, regionY))
2288 {
2289 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
2290 { return true; }
2291 }
2292 }
2293 return false;
2294 }
2295
2296 #allLoaders ()
2297 {
2298 const loaders = [];
2299 for (const worker of this.workers)
2300 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
2301 return loaders;
2302 }
2303
2304 #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID)
2305 {
2306 const dim = normalizeDimensionId(dimensionId);
2307 const votes = new Map();
2308 for (const loader of loaders)
2309 {
2310 const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
2311 if (loaderDim !== dim)
2312 { continue; }
2313 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
2314 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
2315 { continue; }
2316 const record = this.directory.get(loader.entityId);
2317 if (record?.workerId == null)
2318 { continue; }
2319 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
2320 }
2321 let best = null;
2322 let bestVotes = -1;
2323 for (const [workerId, count] of votes)
2324 {
2325 if (count > bestVotes)
2326 {
2327 best = workerId;
2328 bestVotes = count;
2329 }
2330 }
2331 return best;
2332 }
2333
2334 #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2335 {
2336 const dim = normalizeDimensionId(dimensionId);
2337 const pinned = this.pinRegion?.(regionX, regionY, dim);
2338 if (pinned != null)
2339 { return pinned; }
2340
2341 const neighborOwners = [];
2342 for (let dy = -1; dy <= 1; dy++)
2343 {
2344 for (let dx = -1; dx <= 1; dx++)
2345 {
2346 if (dx === 0 && dy === 0)
2347 { continue; }
2348 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim));
2349 if (owner != null)
2350 { neighborOwners.push(owner); }
2351 }
2352 }
2353
2354 const scores = this.workers.map((_, workerId) => ({
2355 workerId,
2356 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
2357 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
2358 }));
2359
2360 if (preferredWorkerId != null && scores[preferredWorkerId])
2361 {
2362 const preferred = scores[preferredWorkerId];
2363 if (preferred.neighbors > 0 || neighborOwners.length === 0)
2364 { return preferredWorkerId; }
2365 }
2366
2367 scores.sort((left, right) =>
2368 right.neighbors - left.neighbors
2369 || left.load - right.load
2370 || left.workerId - right.workerId
2371 );
2372 return scores[0].workerId;
2373 }
2374
2375 #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID)
2376 {
2377 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null;
2378 }
2379
2380 #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2381 {
2382 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId);
2383 }
2384
2385 #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID)
2386 {
2387 const dim = normalizeDimensionId(dimensionId);
2388 return chunksInRegion(regionX, regionY).map((coord) => ({
2389 chunkX: coord.chunkX,
2390 chunkY: coord.chunkY,
2391 dimensionId: dim,
2392 data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim)
2393 }));
2394 }
2395
2396 #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2397 {
2398 const dim = normalizeDimensionId(dimensionId);
2399 const key = chunkKey(chunkX, chunkY, dim);
2400 if (this.authoredCache.has(key))
2401 { return this.authoredCache.get(key); }
2402 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim);
2403 const dimRecord = this.getDimensionRecord(dim);
2404 const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId;
2405 const data = row
2406 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
2407 : createEmptyChunkData(defaultGroundTypeId);
2408 this.authoredCache.set(key, data);
2409 return data;
2410 }
2411
2412 #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2413 {
2414 const dim = normalizeDimensionId(dimensionId);
2415 const data = this.#authoredChunk(chunkX, chunkY, dim);
2416 return {
2417 chunkX,
2418 chunkY,
2419 dimensionId: dim,
2420 open: data.open,
2421 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open),
2422 grounds: data.grounds,
2423 blocks: data.blocks,
2424 light: data.light,
2425 entities: [],
2426 groundItems: []
2427 };
2428 }
2429
2430 #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID)
2431 {
2432 const dim = normalizeDimensionId(dimensionId);
2433 for (const record of this.directory.values())
2434 {
2435 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2436 if (record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2437 { return record.entityId; }
2438 }
2439 return null;
2440 }
2441
2442 #queueReplication (event)
2443 {
2444 if (event)
2445 { this.replication.push(event); }
2446 }
2447
2448 #stepSpawners ()
2449 {
2450 const events = [];
2451 for (const worker of this.workers)
2452 {
2453 const result = worker.call({ type: WorkerMessage.stepSpawners });
2454 for (const request of result?.spawnRequests ?? [])
2455 {
2456 try
2457 {
2458 this.spawnEntity(mobComponents(request), { requireResident: true });
2459 }
2460 catch
2461 { continue; }
2462 }
2463 }
2464 return events;
2465 }
2466
2467 #restoreGroundItems (regionX, regionY, workerId)
2468 {
2469 const bounds = regionTileBounds(regionX, regionY);
2470 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
2471 .filter((item) => item.expiresAt > this.now);
2472 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
2473 this.workers[workerId].call({
2474 type: WorkerMessage.setGroundItems,
2475 regionX,
2476 regionY,
2477 items
2478 });
2479 }
2480
2481 #persistGroundEvent (event)
2482 {
2483 if (event.type === "ground-item-appear")
2484 {
2485 this.stateDb.upsertGroundItem({
2486 groundItemId: event.groundItemId,
2487 tileX: event.tileX,
2488 tileY: event.tileY,
2489 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
2490 droppedAt: event.droppedAt ?? this.now,
2491 expiresAt: event.expiresAt,
2492 source: event.source ?? "player-drop",
2493 droppedByCharacterId: event.droppedByCharacterId ?? null
2494 });
2495 }
2496 if (event.type === "ground-item-despawn")
2497 { this.stateDb.deleteGroundItem(event.groundItemId); }
2498 }
2499
2500 #saveBag (entityId, workerId)
2501 {
2502 const record = this.directory.get(entityId);
2503 const bag = this.workers[workerId].call({
2504 type: WorkerMessage.inspectBag,
2505 entityId
2506 });
2507 if (!bag || !record?.characterId)
2508 { return; }
2509 this.#saveBagFromView(record.characterId, bag);
2510 const skills = this.workers[workerId].call({
2511 type: WorkerMessage.inspectSkills,
2512 entityId
2513 });
2514 if (skills)
2515 { this.stateDb.saveSkills(record.characterId, skills); }
2516 }
2517
2518 #applySkillsUpdated (event)
2519 {
2520 if (!event?.characterId || !event.stored)
2521 { return; }
2522 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
2523 this.pushSkills(event.characterId, event.skills ?? []);
2524 }
2525
2526 #applySpellsUpdated (event)
2527 {
2528 if (!event?.characterId || !event.stored)
2529 { return; }
2530 this.stateDb.saveSpells(event.characterId, event.stored);
2531 this.pushSpells(event.characterId, {
2532 spells: event.spells ?? [],
2533 autoCast: !!event.autoCast
2534 });
2535 }
2536
2537 #skillLevelUpEvents (event)
2538 {
2539 const levelUps = event?.levelUps ?? [];
2540 if (!levelUps.length)
2541 { return []; }
2542 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
2543 if (entityId == null)
2544 { return []; }
2545 const record = this.directory.get(entityId);
2546 const tileX = record?.tileX ?? 0;
2547 const tileY = record?.tileY ?? 0;
2548 return levelUps.map((levelUp) => ({
2549 type: "skill-level-up",
2550 entityId,
2551 characterId: event.characterId,
2552 tileX,
2553 tileY,
2554 skillId: levelUp.skillId,
2555 level: levelUp.level,
2556 displayName: levelUp.displayName,
2557 icon: levelUp.icon
2558 }));
2559 }
2560
2561 #saveBagFromView (characterId, bag)
2562 {
2563 this.stateDb.saveBag(characterId, {
2564 inventory: bag.inventory,
2565 equipment: bag.equipment,
2566 vault: bag.vault,
2567 vaultReserved: bag.vaultReserved
2568 });
2569 }
2570
2571 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
2572 {
2573 const onlineId = this.characterEntities.get(issuerCharacterId);
2574 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
2575 if (!bag)
2576 { return { ok: false, error: "Issuer vault not found." }; }
2577 const reserved = [...(bag.vaultReserved ?? [])];
2578 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
2579 if (index < 0)
2580 { return { ok: false, error: "That cheque cannot be redeemed." }; }
2581 const [stack] = reserved.splice(index, 1);
2582 bag.vaultReserved = reserved;
2583 this.stateDb.saveBag(issuerCharacterId, bag);
2584 if (onlineId)
2585 {
2586 this.applyBag(onlineId, bag);
2587 this.pushInventory(issuerCharacterId, bag);
2588 }
2589 return { ok: true, stack };
2590 }
2591
2592 restoreChequeReservation (issuerCharacterId, stack)
2593 {
2594 const onlineId = this.characterEntities.get(issuerCharacterId);
2595 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
2596 if (!bag)
2597 { return; }
2598 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
2599 this.stateDb.saveBag(issuerCharacterId, bag);
2600 if (onlineId)
2601 {
2602 this.applyBag(onlineId, bag);
2603 this.pushInventory(issuerCharacterId, bag);
2604 }
2605 }
2606
2607 #remember (view, workerId)
2608 {
2609 if (!view)
2610 { return; }
2611 this.directory.set(view.entityId, { ...view, workerId });
2612 if (view.characterId)
2613 { this.characterEntities.set(view.characterId, view.entityId); }
2614 }
2615
2616 #applyMoveToDirectory (event)
2617 {
2618 const record = this.directory.get(event.entityId);
2619 if (!record)
2620 { return; }
2621 record.tileX = event.tileX;
2622 record.tileY = event.tileY;
2623 record.gait = event.gait;
2624 if (event.dimensionId != null)
2625 { record.dimensionId = normalizeDimensionId(event.dimensionId); }
2626 if (event.worldX != null)
2627 { record.worldX = event.worldX; }
2628 if (event.worldY != null)
2629 { record.worldY = event.worldY; }
2630 if (event.freeFlight != null)
2631 { record.freeFlight = !!event.freeFlight; }
2632 }
2633
2634 #forget (entityId)
2635 {
2636 const record = this.directory.get(entityId);
2637 if (record?.characterId)
2638 { this.characterEntities.delete(record.characterId); }
2639 this.directory.delete(entityId);
2640 }
2641}