BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 44.8 KiB Download Raw
1import {
2 CHUNK_SIZE,
3 DEFAULT_CHUNK_LOADER,
4 GAIT,
5 REGION_RUNTIME_STATE,
6 VISIBLE_CHUNK_RADIUS,
7 WORLD_YEAR_OFFSET
8} from "../../../shared/protocol/constants.js";
9import {
10 chunkKey,
11 chunkToRegion,
12 chunksInRegion,
13 parseChunkKey,
14 parseRegionKey,
15 regionKey,
16 regionTileBounds,
17 tileToChunk,
18 tileToLocal,
19 tileToRegion,
20 visibleChunkCoords
21} from "../world/coordinates.js";
22import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
23import { closedNeighborEdges } from "../world/chunkFlags.js";
24import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
25import { InProcessWorker } from "./inProcessWorker.js";
26import { ThreadWorker } from "./threadWorker.js";
27import { WorkerMessage } from "./protocol.js";
28import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31import { mobComponents } from "./spawners.js";
32import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
33import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
34import { BlockType } from "../../../shared/definitions/tiles.js";
35import { ItemId } from "../../../shared/definitions/items.js";
36import { seasonIdAt } from "../../../shared/world/season.js";
37import { CourierService } from "../courier/service.js";
38import { MarketService } from "../market/service.js";
39import { findReservedChequeIndex } from "../items/bags.js";
40
41export class Simulation
42{
43 constructor (worldDb, stateDb, options = {})
44 {
45 this.worldDb = worldDb;
46 this.stateDb = stateDb;
47 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
48 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
49 this.pinRegion = options.pinRegion ?? null;
50 this.nowFn = options.now ?? (() => Date.now());
51 this.workers = [];
52 this.regionOwner = new Map();
53 this.regionGraceUntil = new Map();
54 this.directory = new Map();
55 this.characterEntities = new Map();
56 this.commandQueue = [];
57 this.replication = [];
58 this.pendingPrivate = [];
59 this.courier = null;
60 this.market = null;
61 this.altarTiles = [];
62 this.authoredCache = new Map();
63 this.simulatingChunkKeys = new Set();
64 this.nextEntityId = 1;
65 this.nextGroundItemId = stateDb.nextGroundItemId();
66 this.tickIndex = 0;
67 this.movementTickCounter = 0;
68 this.lastTickAt = null;
69 this.movementAccumulator = 0;
70 this.activeRevisionId = worldDb.getActiveRevisionId();
71 this.settings = worldDb.getLiveSettings();
72
73 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
74 for (let workerId = 0; workerId < this.workerCount; workerId++)
75 {
76 const worker = new WorkerImpl(workerId);
77 worker.call({
78 type: WorkerMessage.configure,
79 settings: this.settings,
80 activeRevisionId: this.activeRevisionId
81 });
82 this.workers.push(worker);
83 }
84 for (const worker of this.workers)
85 {
86 if (!worker.world)
87 { continue; }
88 worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
89 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
90 }
91 this.courier = new CourierService({
92 stateDb: this.stateDb,
93 worldDb: this.worldDb,
94 simulation: this
95 });
96 this.market = new MarketService({
97 stateDb: this.stateDb,
98 worldDb: this.worldDb,
99 simulation: this
100 });
101 this.#refreshAltarIndex();
102 }
103
104 get now ()
105 {
106 return this.nowFn();
107 }
108
109 applySettings (settings)
110 {
111 this.settings = { ...this.settings, ...settings };
112 this.#configureWorkers();
113 }
114
115 /** Sparse last-sale map for editor base-price readouts. */
116 itemLastSalesSnapshot ()
117 {
118 return this.market?.snapshot?.() ?? {};
119 }
120
121 syncItemLastSales (lastSales)
122 {
123 const sales = {};
124 for (const [itemId, sale] of lastSales?.entries?.() ?? [])
125 { sales[String(itemId)] = sale; }
126 for (const worker of this.workers)
127 {
128 worker.call({
129 type: WorkerMessage.setItemLastSales,
130 sales
131 });
132 }
133 }
134
135 reloadWorld ()
136 {
137 this.activeRevisionId = this.worldDb.getActiveRevisionId();
138 this.settings = this.worldDb.getLiveSettings();
139 this.authoredCache.clear();
140 this.#configureWorkers();
141 for (const [key, workerId] of this.regionOwner)
142 {
143 const { regionX, regionY } = parseRegionKey(key);
144 this.workers[workerId].call({
145 type: WorkerMessage.replaceRegionChunks,
146 chunks: this.#regionChunkBlobs(regionX, regionY)
147 });
148 }
149 this.#syncAllReplicas();
150 this.courier?.refreshBankIndex();
151 this.market?.refreshIndex();
152 this.#refreshAltarIndex();
153 }
154
155 enqueue (sessionId, command)
156 {
157 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
158 }
159
160 step (now = this.now)
161 {
162 this.tickIndex += 1;
163 const events = [];
164 const commands = this.commandQueue.splice(0);
165 for (const item of commands)
166 {
167 try
168 {
169 events.push(...this.#routeCommand(item));
170 }
171 catch (error)
172 {
173 events.push({
174 sessionId: item.sessionId,
175 type: "command-error",
176 message: error.userFacing ? error.message : "Command failed."
177 });
178 }
179 }
180
181 this.#recalculateActivation(now);
182
183 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
184 const expectedDt = 1 / simHz;
185 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
186 ? expectedDt
187 : Math.min(0.25, (now - this.lastTickAt) / 1000);
188 this.lastTickAt = now;
189
190 {
191 const transfers = [];
192 const remoteMelee = [];
193 for (const worker of this.workers)
194 {
195 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
196 for (const event of result?.events ?? [])
197 {
198 if (event.type === "remote-melee-resolve")
199 {
200 remoteMelee.push(event);
201 continue;
202 }
203 if (event.type === "entity-move")
204 { this.#applyMoveToDirectory(event); }
205 if (event.type === "entity-despawn")
206 { this.#forget(event.entityId); }
207 if (event.type === "skills-updated")
208 { this.#applySkillsUpdated(event); }
209 if (event.type === "inventory" && event.characterId)
210 {
211 this.#saveBagFromView(event.characterId, {
212 inventory: event.inventory,
213 equipment: event.equipment,
214 vault: event.vault,
215 vaultReserved: event.vaultReserved
216 });
217 }
218 if (event.type === "player-died")
219 {
220 events.push(...this.#applyPlayerDeath(event));
221 continue;
222 }
223 this.#persistGroundEvent(event);
224 if (event.type !== "skills-updated")
225 { events.push(event); }
226 }
227 for (const request of result?.transferRequests ?? [])
228 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
229 }
230 for (const payload of remoteMelee)
231 { events.push(...this.#applyRemoteMelee(payload)); }
232 if (transfers.length)
233 {
234 events.push(...this.#applyTransfers(transfers));
235 this.#recalculateActivation(now);
236 }
237 }
238
239 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
240 this.movementAccumulator += dt * movementHz;
241 while (this.movementAccumulator >= 1)
242 {
243 this.movementAccumulator -= 1;
244 this.movementTickCounter += 1;
245 const transfers = [];
246 for (const worker of this.workers)
247 {
248 const result = worker.call({ type: WorkerMessage.stepMovement, now });
249 for (const event of result?.events ?? [])
250 {
251 if (event.type === "entity-move")
252 { this.#applyMoveToDirectory(event); }
253 if (event.type === "skills-updated")
254 { this.#applySkillsUpdated(event); }
255 this.#persistGroundEvent(event);
256 if (event.type !== "skills-updated")
257 { events.push(event); }
258 }
259 for (const request of result?.transferRequests ?? [])
260 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
261 }
262 events.push(...this.#applyTransfers(transfers));
263 this.#recalculateActivation(now);
264 }
265
266 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
267 { events.push(...this.#stepSpawners()); }
268
269 if (this.courier)
270 { events.push(...this.courier.step(now, dt)); }
271 if (this.market)
272 { events.push(...this.market.step(now)); }
273
274 this.#syncGhosts();
275 events.push(...this.pendingPrivate.splice(0));
276 return { now, events, replication: this.drainReplication() };
277 }
278
279 drainReplication ()
280 {
281 return this.replication.splice(0);
282 }
283
284 worldTime (now = this.now)
285 {
286 const date = new Date(now);
287 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
288 return {
289 unixMs: now,
290 worldUnixMs: date.getTime(),
291 iso: date.toISOString(),
292 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600,
293 season: seasonIdAt(now)
294 };
295 }
296
297 spawnCharacter (sessionId, character)
298 {
299 this.despawnCharacter(character.character_id);
300 // Despawn may have just written the live tile; never trust a stale row snapshot.
301 const row = this.stateDb.getCharacter(character.character_id) ?? character;
302 let tileX = row.tile_x;
303 let tileY = row.tile_y;
304 const gait = row.gait || character.gait || GAIT.walk;
305 const preferred = this.#findResumeTile(tileX, tileY);
306 if (!preferred)
307 {
308 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
309 error.userFacing = true;
310 throw error;
311 }
312 if (preferred.tileX !== tileX || preferred.tileY !== tileY)
313 {
314 tileX = preferred.tileX;
315 tileY = preferred.tileY;
316 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait);
317 }
318
319 const bag = this.stateDb.getBag(character.character_id) ?? {
320 inventory: emptySlots(),
321 equipment: emptyEquipment(),
322 vault: [],
323 vaultReserved: []
324 };
325 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
326 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
327 if (enforceMinimumSkillLevels(skills))
328 { this.stateDb.saveSkills(character.character_id, skills); }
329 const maxHealth = playerMaxHealth(skills);
330 const maxStamina = playerMaxStamina(skills);
331 const isDead = !!row.is_dead;
332 const entityId = this.nextEntityId++;
333 const components = {
334 position: { tileX, tileY },
335 movement: { gait, walkCarry: 0 },
336 path: { tiles: [] },
337 appearance: {
338 sex: character.sex ?? row.sex,
339 firstName: character.first_name ?? row.first_name,
340 lastName: character.last_name ?? row.last_name
341 },
342 character: {
343 characterId: character.character_id ?? row.character_id,
344 accountId: character.account_id ?? row.account_id
345 },
346 networkIdentity: { sessionId },
347 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
348 inventory: { slots: bag.inventory ?? emptySlots() },
349 equipment: bag.equipment ?? emptyEquipment(),
350 vault: {
351 slots: bag.vault ?? [],
352 reserved: bag.vaultReserved ?? []
353 },
354 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
355 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
356 combat: { targetEntityId: null, nextSwingAt: 0 },
357 skills,
358 };
359 if (isDead)
360 { components.dead = {}; }
361 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
362 const workerId = this.#ownerOfTile(tileX, tileY);
363 const view = this.workers[workerId].call({
364 type: WorkerMessage.spawn,
365 entityId,
366 components
367 });
368 this.#remember(view, workerId);
369 this.#queueReplication(replicationSpawn(view));
370 this.#recalculateActivation(this.now);
371 this.#syncGhosts();
372 return entityId;
373 }
374
375 spawnEntity (components, options = {})
376 {
377 const entityId = options.entityId ?? this.nextEntityId++;
378 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
379 const position = components.position;
380 if (!position)
381 { throw new Error("spawnEntity requires position."); }
382 if (options.requireResident)
383 {
384 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
385 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY))
386 { return null; }
387 const view = this.workers[workerId].call({
388 type: WorkerMessage.spawn,
389 entityId,
390 components
391 });
392 this.#remember(view, workerId);
393 if (components.appearance)
394 { this.#queueReplication(replicationSpawn(view)); }
395 this.#syncGhosts();
396 return entityId;
397 }
398 if (components.chunkLoader)
399 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
400 else
401 {
402 this.#ensureRegion(
403 tileToRegion(position.tileX),
404 tileToRegion(position.tileY),
405 null
406 );
407 }
408 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
409 const view = this.workers[workerId].call({
410 type: WorkerMessage.spawn,
411 entityId,
412 components
413 });
414 this.#remember(view, workerId);
415 if (components.appearance)
416 { this.#queueReplication(replicationSpawn(view)); }
417 this.#recalculateActivation(this.now);
418 this.#syncGhosts();
419 return entityId;
420 }
421
422 despawnEntity (entityId)
423 {
424 const record = this.directory.get(entityId);
425 if (!record)
426 { return; }
427 const dropped = this.workers[record.workerId].call({
428 type: WorkerMessage.despawn,
429 entityId
430 });
431 if (dropped)
432 { this.#queueReplication(replicationDespawn(dropped)); }
433 this.#forget(entityId);
434 }
435
436 chunkIsSimulating (tileX, tileY)
437 {
438 const loaders = this.#allLoaders();
439 const { chunkSim } = accumulateLoaderRefs(loaders);
440 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0;
441 }
442
443 updateCourierFlight (entityId, flightPatch, now = this.now)
444 {
445 const record = this.directory.get(entityId);
446 if (!record)
447 { return { despawned: true, entityId }; }
448 const tileX = Math.floor(flightPatch.x);
449 const tileY = Math.floor(flightPatch.y);
450 const owner = this.#ownerOfTile(tileX, tileY);
451 if (owner == null || owner !== record.workerId)
452 {
453 this.despawnEntity(entityId);
454 return { despawned: true, entityId };
455 }
456 const result = this.workers[owner].call({
457 type: WorkerMessage.updateFlight,
458 entityId,
459 flight: flightPatch,
460 now
461 });
462 if (result?.transferRequest)
463 {
464 const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);
465 this.#recalculateActivation(now);
466 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
467 if (move)
468 {
469 this.#applyMoveToDirectory(move);
470 return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };
471 }
472 this.despawnEntity(entityId);
473 return { despawned: true, entityId };
474 }
475 if (result?.event)
476 {
477 this.#applyMoveToDirectory(result.event);
478 return { event: result.event };
479 }
480 return null;
481 }
482
483 applyBag (entityId, bag)
484 {
485 const record = this.directory.get(entityId);
486 if (!record)
487 { return null; }
488 return this.workers[record.workerId].call({
489 type: WorkerMessage.applyBag,
490 entityId,
491 bag
492 });
493 }
494
495 pushSkills (characterId, skills)
496 {
497 this.pendingPrivate.push({
498 type: "skills",
499 characterId,
500 skills
501 });
502 }
503
504 skillsOf (entityId)
505 {
506 const record = this.directory.get(entityId);
507 if (!record)
508 { return null; }
509 return this.workers[record.workerId].call({
510 type: WorkerMessage.inspectSkills,
511 entityId
512 });
513 }
514
515 staminaOf (entityId)
516 {
517 const record = this.directory.get(entityId);
518 if (!record)
519 { return null; }
520 return this.workers[record.workerId].call({
521 type: WorkerMessage.inspectStamina,
522 entityId
523 });
524 }
525
526 pushInventory (characterId, bag)
527 {
528 this.pendingPrivate.push({
529 type: "inventory",
530 characterId,
531 inventory: bag.inventory,
532 equipment: bag.equipment,
533 vault: bag.vault,
534 vaultReserved: bag.vaultReserved
535 });
536 }
537
538 dispatchPigeon ({ characterId, destination, cargo })
539 {
540 const entityId = this.characterEntities.get(characterId);
541 const position = entityId ? this.positionOf(entityId) : null;
542 if (!position)
543 {
544 const error = new Error("Enter the world before sending a pigeon.");
545 error.userFacing = true;
546 throw error;
547 }
548 return this.courier.dispatchFromPlayer({
549 characterId,
550 originTileX: position.tileX,
551 originTileY: position.tileY,
552 destination,
553 cargo
554 });
555 }
556
557 despawnCharacter (characterId)
558 {
559 const entityId = this.characterEntities.get(characterId);
560 if (!entityId)
561 { return; }
562 const record = this.directory.get(entityId);
563 if (!record)
564 {
565 this.characterEntities.delete(characterId);
566 return;
567 }
568 this.#saveBag(entityId, record.workerId);
569 const dropped = this.workers[record.workerId].call({
570 type: WorkerMessage.despawnCharacter,
571 characterId
572 });
573 if (dropped)
574 {
575 this.stateDb.saveCharacterPosition(
576 characterId,
577 dropped.tileX,
578 dropped.tileY,
579 dropped.gait ?? GAIT.walk
580 );
581 this.#queueReplication(replicationDespawn(dropped));
582 }
583 this.#forget(entityId);
584 this.#recalculateActivation(this.now);
585 this.#syncGhosts();
586 }
587
588 entityForCharacter (characterId)
589 {
590 return this.characterEntities.get(characterId) ?? null;
591 }
592
593 entityRecord (entityId)
594 {
595 const record = this.directory.get(entityId);
596 return record ? { ...record } : null;
597 }
598
599 positionOf (entityId)
600 {
601 const record = this.directory.get(entityId);
602 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
603 }
604
605 bagOf (entityId)
606 {
607 const record = this.directory.get(entityId);
608 if (!record)
609 { return null; }
610 return this.workers[record.workerId].call({
611 type: WorkerMessage.inspectBag,
612 entityId
613 });
614 }
615
616 snapshotFor (entityId)
617 {
618 const record = this.directory.get(entityId);
619 if (!record)
620 { return []; }
621 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
622 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
623 }
624
625 snapshotChunk (chunkX, chunkY)
626 {
627 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
628 if (owner == null)
629 { return this.#syntheticSnapshot(chunkX, chunkY); }
630 return this.workers[owner].call({
631 type: WorkerMessage.snapshotChunk,
632 chunkX,
633 chunkY
634 });
635 }
636
637 findOpenSpawn ()
638 {
639 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
640 for (const coord of coords)
641 {
642 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
643 if (!data.open)
644 { continue; }
645 for (let localY = 0; localY < CHUNK_SIZE; localY++)
646 {
647 for (let localX = 0; localX < CHUNK_SIZE; localX++)
648 {
649 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
650 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
651 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
652 { return { tileX, tileY }; }
653 }
654 }
655 }
656 return null;
657 }
658
659 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
660 #findResumeTile (tileX, tileY, radius = 24)
661 {
662 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
663 }
664
665 #findNearbyEnterable (originX, originY, maxRadius)
666 {
667 for (let radius = 0; radius <= maxRadius; radius++)
668 {
669 for (let dy = -radius; dy <= radius; dy++)
670 {
671 for (let dx = -radius; dx <= radius; dx++)
672 {
673 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
674 { continue; }
675 const tileX = originX + dx;
676 const tileY = originY + dy;
677 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
678 { return { tileX, tileY }; }
679 }
680 }
681 }
682 return null;
683 }
684
685 isEnterable (tileX, tileY)
686 {
687 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
688 if (!data.open)
689 { return false; }
690 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
691 }
692
693 debugWorld ()
694 {
695 const loaders = this.#allLoaders();
696 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
697 const simulatingChunks = [...chunkSim.entries()]
698 .filter(([, count]) => count > 0)
699 .map(([key]) => key)
700 .sort();
701 return {
702 tickIndex: this.tickIndex,
703 workerCount: this.workers.length,
704 workerMode: this.workerMode,
705 simulatingChunks,
706 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
707 ...parseRegionKey(key),
708 workerId,
709 state: REGION_RUNTIME_STATE.resident,
710 refs: regionRes.get(key) ?? 0,
711 graceUntil: this.regionGraceUntil.get(key) ?? null
712 })),
713 entities: [...this.directory.values()].map((entity) => ({
714 entityId: entity.entityId,
715 workerId: entity.workerId,
716 tileX: entity.tileX,
717 tileY: entity.tileY,
718 characterId: entity.characterId
719 }))
720 };
721 }
722
723 async shutdown ()
724 {
725 for (const characterId of [...this.characterEntities.keys()])
726 { this.despawnCharacter(characterId); }
727 this.forceUnloadAll();
728 await Promise.all(this.workers.map((worker) => worker.terminate()));
729 }
730
731 forceUnloadAll ()
732 {
733 for (const key of [...this.regionOwner.keys()])
734 {
735 const { regionX, regionY } = parseRegionKey(key);
736 this.#unloadRegion(regionX, regionY);
737 }
738 }
739
740 #configureWorkers ()
741 {
742 for (const worker of this.workers)
743 {
744 worker.call({
745 type: WorkerMessage.configure,
746 settings: this.settings,
747 activeRevisionId: this.activeRevisionId
748 });
749 }
750 }
751
752 #routeCommand (item)
753 {
754 if (item.command.type === "respawn")
755 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
756 if (
757 item.command.type === "open-market"
758 || item.command.type === "place-market-sell"
759 || item.command.type === "place-market-buy"
760 || item.command.type === "cancel-market-order"
761 || item.command.type === "close-market"
762 )
763 {
764 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
765 return result?.events ?? [];
766 }
767 const entityId = this.characterEntities.get(item.command.characterId);
768 const record = entityId ? this.directory.get(entityId) : null;
769 if (!record)
770 {
771 const error = new Error("Character is not in the world.");
772 error.userFacing = true;
773 throw error;
774 }
775 if (item.command.type === "drop-item" && item.command.groundItemId == null)
776 { item.command.groundItemId = this.nextGroundItemId++; }
777 if (item.command.type === "attack")
778 {
779 const targetRecord = this.directory.get(item.command.targetEntityId);
780 if (!targetRecord)
781 {
782 const error = new Error("Target is not here.");
783 error.userFacing = true;
784 throw error;
785 }
786 const events = this.#finishRoutedCommand(item, record);
787 if (targetRecord.workerId !== record.workerId)
788 {
789 this.workers[targetRecord.workerId].call({
790 type: WorkerMessage.remoteCombatEngage,
791 attackerEntityId: record.entityId,
792 targetEntityId: item.command.targetEntityId,
793 now: item.receivedAt ?? this.now
794 });
795 }
796 return events;
797 }
798 return this.#finishRoutedCommand(item, record);
799 }
800
801 #finishRoutedCommand (item, record)
802 {
803 const result = this.workers[record.workerId].call({
804 type: WorkerMessage.command,
805 sessionId: item.sessionId,
806 command: item.command,
807 now: item.receivedAt ?? this.now
808 });
809 const view = this.workers[record.workerId].call({
810 type: WorkerMessage.inspect,
811 entityId: record.entityId
812 });
813 if (view)
814 { this.#remember(view, record.workerId); }
815 if (result?.private)
816 { this.#saveBagFromView(item.command.characterId, result.private); }
817 if (result?.appearanceChanged && view)
818 { this.#queueReplication(replicationAppearance(view)); }
819 if (result?.remainder)
820 {
821 this.stateDb.saveInheritance(
822 this.stateDb.getCharacter(item.command.characterId).account_id,
823 { slots: result.remainder }
824 );
825 }
826 for (const event of result?.events ?? [])
827 { this.#persistGroundEvent(event); }
828 const events = [...(result?.events ?? [])];
829 if (result?.private)
830 {
831 events.push({
832 type: "inventory",
833 sessionId: item.sessionId,
834 bank: !!result.bank,
835 cauldron: result.cauldron,
836 cauldronState: result.cauldronState ?? null,
837 alchemyResult: result.alchemyResult ?? null,
838 ...result.private
839 });
840 }
841 return events;
842 }
843
844 #applyRemoteMelee (payload)
845 {
846 const targetRecord = this.directory.get(payload.targetId);
847 if (!targetRecord)
848 { return []; }
849 const result = this.workers[targetRecord.workerId].call({
850 ...payload,
851 type: WorkerMessage.applyRemoteMelee
852 });
853 const events = [];
854 for (const event of result?.events ?? [])
855 {
856 if (event.type === "entity-despawn")
857 { this.#forget(event.entityId); }
858 if (event.type === "skills-updated")
859 { this.#applySkillsUpdated(event); }
860 if (event.type === "player-died")
861 {
862 events.push(...this.#applyPlayerDeath(event));
863 continue;
864 }
865 this.#persistGroundEvent(event);
866 if (event.type !== "skills-updated")
867 { events.push(event); }
868 }
869 for (const forward of result?.forwards ?? [])
870 {
871 if (forward.type !== "forward-combat-xp")
872 { continue; }
873 const attackerRecord = this.directory.get(forward.entityId);
874 if (!attackerRecord)
875 { continue; }
876 const xpResult = this.workers[attackerRecord.workerId].call({
877 type: WorkerMessage.applyCombatHitXp,
878 entityId: forward.entityId,
879 profile: forward.profile
880 });
881 for (const xpEvent of xpResult?.events ?? [])
882 {
883 if (xpEvent.type === "skills-updated")
884 { this.#applySkillsUpdated(xpEvent); }
885 if (xpEvent.type !== "skills-updated")
886 { events.push(xpEvent); }
887 }
888 }
889 return events;
890 }
891
892 #applyPlayerDeath (event)
893 {
894 const record = this.directory.get(event.entityId);
895 if (!record)
896 { return [event]; }
897 this.stateDb.setCharacterDead(event.characterId, true);
898 this.stateDb.saveCharacterPosition(
899 event.characterId,
900 event.tileX,
901 event.tileY,
902 record.gait ?? GAIT.walk
903 );
904 for (const worker of this.workers)
905 {
906 worker.call({
907 type: WorkerMessage.clearCombat,
908 entityId: event.entityId,
909 targetEntityId: event.entityId
910 });
911 }
912 const result = this.workers[record.workerId].call({
913 type: WorkerMessage.spawnCorpseDrops,
914 characterId: event.characterId,
915 tileX: event.tileX,
916 tileY: event.tileY,
917 now: this.now,
918 drops: [
919 { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones },
920 { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull }
921 ]
922 });
923 const events = [event];
924 for (const dropEvent of result?.events ?? [])
925 {
926 this.#persistGroundEvent(dropEvent);
927 events.push(dropEvent);
928 }
929 return events;
930 }
931
932 #respawnCharacter (sessionId, characterId)
933 {
934 const row = this.stateDb.getCharacter(characterId);
935 if (!row?.is_dead)
936 {
937 const error = new Error("You are not dead.");
938 error.userFacing = true;
939 throw error;
940 }
941 const entityId = this.characterEntities.get(characterId);
942 const record = entityId ? this.directory.get(entityId) : null;
943 if (!record)
944 {
945 const error = new Error("Character is not in the world.");
946 error.userFacing = true;
947 throw error;
948 }
949 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
950 if (!destination)
951 {
952 const error = new Error("No open tile is available for respawn.");
953 error.userFacing = true;
954 throw error;
955 }
956 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
957 const loader = { ...DEFAULT_CHUNK_LOADER };
958 this.#ensureCoverage(destination.tileX, destination.tileY, loader);
959 const result = this.workers[record.workerId].call({
960 type: WorkerMessage.applyRespawn,
961 entityId,
962 sessionId,
963 tileX: destination.tileX,
964 tileY: destination.tileY,
965 maxHealth: playerMaxHealth(skills),
966 maxStamina: playerMaxStamina(skills)
967 });
968 if (!result?.accepted)
969 {
970 const error = new Error("That respawn tile is no longer available.");
971 error.userFacing = true;
972 throw error;
973 }
974 let moveEvents = [];
975 if (result.transferRequest)
976 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
977 else if (result.event)
978 {
979 this.#applyMoveToDirectory(result.event);
980 moveEvents = [result.event];
981 const view = this.workers[record.workerId].call({
982 type: WorkerMessage.inspect,
983 entityId
984 });
985 if (view)
986 { this.#remember(view, record.workerId); }
987 }
988 if (!moveEvents.length)
989 {
990 const error = new Error("Respawn transfer failed.");
991 error.userFacing = true;
992 throw error;
993 }
994 this.stateDb.setCharacterDead(characterId, false);
995 this.stateDb.saveCharacterPosition(
996 characterId,
997 destination.tileX,
998 destination.tileY,
999 record.gait ?? GAIT.walk
1000 );
1001 this.#recalculateActivation(this.now);
1002 this.#syncGhosts();
1003 return [
1004 ...moveEvents,
1005 {
1006 type: "player-respawned",
1007 entityId,
1008 characterId,
1009 sessionId,
1010 tileX: destination.tileX,
1011 tileY: destination.tileY,
1012 health: playerMaxHealth(skills),
1013 maxHealth: playerMaxHealth(skills),
1014 stamina: playerMaxStamina(skills),
1015 maxStamina: playerMaxStamina(skills)
1016 }
1017 ];
1018 }
1019
1020 #refreshAltarIndex ()
1021 {
1022 const altars = [];
1023 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
1024 {
1025 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
1026 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1027 {
1028 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1029 {
1030 const block = data.blocks[localY * CHUNK_SIZE + localX];
1031 if (block?.typeId !== BlockType.churchAltar)
1032 { continue; }
1033 altars.push({
1034 tileX: coord.chunk_x * CHUNK_SIZE + localX,
1035 tileY: coord.chunk_y * CHUNK_SIZE + localY
1036 });
1037 }
1038 }
1039 }
1040 this.altarTiles = altars;
1041 }
1042
1043 #findRespawnDestination (originX, originY, entityId)
1044 {
1045 const ordered = [...this.altarTiles].sort((left, right) =>
1046 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1047 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1048 );
1049 for (const altar of ordered)
1050 {
1051 const adjacent = [];
1052 for (let dy = -1; dy <= 1; dy++)
1053 {
1054 for (let dx = -1; dx <= 1; dx++)
1055 {
1056 if (dx === 0 && dy === 0)
1057 { continue; }
1058 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy });
1059 }
1060 }
1061 adjacent.sort((left, right) =>
1062 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1063 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1064 );
1065 const tile = adjacent.find((entry) =>
1066 this.isEnterable(entry.tileX, entry.tileY)
1067 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId)
1068 );
1069 if (tile)
1070 { return tile; }
1071 }
1072 for (let radius = 0; radius <= 24; radius++)
1073 {
1074 for (let dy = -radius; dy <= radius; dy++)
1075 {
1076 for (let dx = -radius; dx <= radius; dx++)
1077 {
1078 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1079 { continue; }
1080 const tileX = originX + dx;
1081 const tileY = originY + dy;
1082 if (this.isEnterable(tileX, tileY)
1083 && !this.#occupiedByOther(tileX, tileY, entityId))
1084 { return { tileX, tileY }; }
1085 }
1086 }
1087 }
1088 return this.findOpenSpawn();
1089 }
1090
1091 #occupiedByOther (tileX, tileY, entityId)
1092 {
1093 for (const record of this.directory.values())
1094 {
1095 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY)
1096 { return true; }
1097 }
1098 return false;
1099 }
1100
1101 #recalculateActivation (now)
1102 {
1103 const loaders = this.#allLoaders();
1104 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
1105
1106 for (const [key, count] of regionRes)
1107 {
1108 if (count <= 0)
1109 { continue; }
1110 const { regionX, regionY } = parseRegionKey(key);
1111 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
1112 this.regionGraceUntil.delete(key);
1113 }
1114
1115 for (const [key] of [...this.regionOwner.entries()])
1116 {
1117 if ((regionRes.get(key) ?? 0) > 0)
1118 { continue; }
1119 if (!this.regionGraceUntil.has(key))
1120 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
1121 if (now >= this.regionGraceUntil.get(key))
1122 {
1123 const { regionX, regionY } = parseRegionKey(key);
1124 this.#unloadRegion(regionX, regionY);
1125 }
1126 }
1127
1128 for (const [workerId, worker] of this.workers.entries())
1129 {
1130 const chunkKeys = [];
1131 for (const [key, count] of chunkSim)
1132 {
1133 if (count <= 0)
1134 { continue; }
1135 const { chunkX, chunkY } = parseChunkKey(key);
1136 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
1137 { chunkKeys.push(key); }
1138 }
1139 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
1140 }
1141 this.#syncAllReplicas();
1142
1143 const nextSimulating = new Set();
1144 for (const [key, count] of chunkSim)
1145 {
1146 if (count > 0)
1147 { nextSimulating.add(key); }
1148 }
1149 let preheated = false;
1150 for (const key of nextSimulating)
1151 {
1152 if (!this.simulatingChunkKeys.has(key))
1153 {
1154 preheated = true;
1155 break;
1156 }
1157 }
1158 this.simulatingChunkKeys = nextSimulating;
1159 if (preheated)
1160 { this.#stepSpawners(); }
1161 }
1162
1163 #ensureCoverage (tileX, tileY, loader)
1164 {
1165 const coverage = loaderCoverage(tileX, tileY, loader);
1166 let preferred = this.#ownerOfTile(tileX, tileY);
1167 for (const region of coverage.residentRegions)
1168 {
1169 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
1170 if (preferred == null)
1171 { preferred = owner; }
1172 }
1173 }
1174
1175 #ensureRegion (regionX, regionY, preferredWorkerId)
1176 {
1177 const key = regionKey(regionX, regionY);
1178 if (this.regionOwner.has(key))
1179 { return this.regionOwner.get(key); }
1180 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
1181 this.workers[workerId].call({
1182 type: WorkerMessage.assignRegion,
1183 regionX,
1184 regionY,
1185 chunks: this.#regionChunkBlobs(regionX, regionY)
1186 });
1187 this.regionOwner.set(key, workerId);
1188 this.#restorePersistent(regionX, regionY, workerId);
1189 this.#restoreGroundItems(regionX, regionY, workerId);
1190 return workerId;
1191 }
1192
1193 #unloadRegion (regionX, regionY)
1194 {
1195 const key = regionKey(regionX, regionY);
1196 const workerId = this.regionOwner.get(key);
1197 if (workerId == null)
1198 { return; }
1199 const bounds = regionTileBounds(regionX, regionY);
1200 const { dropped, groundItems } = this.workers[workerId].call({
1201 type: WorkerMessage.dropRegion,
1202 regionX,
1203 regionY
1204 });
1205 const persistent = [];
1206 for (const record of dropped ?? [])
1207 {
1208 if (record.characterId)
1209 {
1210 this.stateDb.saveCharacterPosition(
1211 record.characterId,
1212 record.tileX,
1213 record.tileY,
1214 record.gait ?? GAIT.walk
1215 );
1216 }
1217 if (record.persistent)
1218 { persistent.push(record); }
1219 this.#forget(record.entityId);
1220 }
1221 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
1222 for (const item of groundItems ?? [])
1223 { this.stateDb.upsertGroundItem(item); }
1224 this.regionOwner.delete(key);
1225 this.regionGraceUntil.delete(key);
1226 }
1227
1228 #restorePersistent (regionX, regionY, workerId)
1229 {
1230 const bounds = regionTileBounds(regionX, regionY);
1231 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
1232 for (const row of rows)
1233 {
1234 if (this.directory.has(row.entity_id))
1235 { continue; }
1236 const components = JSON.parse(row.components_blob);
1237 const view = this.workers[workerId].call({
1238 type: WorkerMessage.spawn,
1239 entityId: row.entity_id,
1240 components
1241 });
1242 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
1243 this.#remember(view, workerId);
1244 }
1245 }
1246
1247 #applyTransfers (requests)
1248 {
1249 const events = [];
1250 for (const request of requests)
1251 {
1252 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
1253 if (destWorkerId === request.fromWorkerId)
1254 {
1255 this.workers[request.fromWorkerId].call({
1256 type: WorkerMessage.abortTransfer,
1257 entityId: request.entityId
1258 });
1259 continue;
1260 }
1261 let result;
1262 try
1263 {
1264 result = this.workers[destWorkerId].call({
1265 type: WorkerMessage.applyTransfer,
1266 payload: request.payload,
1267 destTileX: request.destTileX,
1268 destTileY: request.destTileY
1269 });
1270 }
1271 catch
1272 {
1273 result = { accepted: false };
1274 }
1275 if (!result?.accepted)
1276 {
1277 this.workers[request.fromWorkerId].call({
1278 type: WorkerMessage.abortTransfer,
1279 entityId: request.entityId
1280 });
1281 continue;
1282 }
1283 this.workers[request.fromWorkerId].call({
1284 type: WorkerMessage.commitTransfer,
1285 entityId: request.entityId
1286 });
1287 this.#remember(result.entity, destWorkerId);
1288 events.push({
1289 type: "entity-move",
1290 entityId: request.entityId,
1291 fromTileX: request.fromTileX,
1292 fromTileY: request.fromTileY,
1293 tileX: result.entity.tileX,
1294 tileY: result.entity.tileY,
1295 gait: result.entity.gait
1296 });
1297 }
1298 return events;
1299 }
1300
1301 #syncAllReplicas ()
1302 {
1303 for (const [workerId, worker] of this.workers.entries())
1304 {
1305 const ownedKeys = new Set();
1306 for (const [key, owner] of this.regionOwner)
1307 {
1308 if (owner !== workerId)
1309 { continue; }
1310 const { regionX, regionY } = parseRegionKey(key);
1311 for (const chunk of chunksInRegion(regionX, regionY))
1312 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
1313 }
1314 const replicas = [];
1315 for (const key of replicaNeededForOwnedChunks(ownedKeys))
1316 {
1317 if (ownedKeys.has(key))
1318 { continue; }
1319 const { chunkX, chunkY } = parseChunkKey(key);
1320 replicas.push({
1321 chunkX,
1322 chunkY,
1323 data: this.#authoredChunk(chunkX, chunkY)
1324 });
1325 }
1326 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
1327 }
1328 }
1329
1330 #syncGhosts ()
1331 {
1332 const entities = [];
1333 for (const worker of this.workers)
1334 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
1335 for (const [workerId, worker] of this.workers.entries())
1336 {
1337 const ghosts = entities.filter((entity) =>
1338 {
1339 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
1340 { return false; }
1341 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
1342 });
1343 worker.call({ type: WorkerMessage.setGhosts, ghosts });
1344 }
1345 }
1346
1347 #nearWorker (workerId, tileX, tileY)
1348 {
1349 const chunkX = tileToChunk(tileX);
1350 const chunkY = tileToChunk(tileY);
1351 for (const [key, owner] of this.regionOwner)
1352 {
1353 if (owner !== workerId)
1354 { continue; }
1355 const { regionX, regionY } = parseRegionKey(key);
1356 for (const chunk of chunksInRegion(regionX, regionY))
1357 {
1358 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
1359 { return true; }
1360 }
1361 }
1362 return false;
1363 }
1364
1365 #allLoaders ()
1366 {
1367 const loaders = [];
1368 for (const worker of this.workers)
1369 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
1370 return loaders;
1371 }
1372
1373 #preferredWorkerForRegion (loaders, regionX, regionY)
1374 {
1375 const votes = new Map();
1376 for (const loader of loaders)
1377 {
1378 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
1379 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
1380 { continue; }
1381 const record = this.directory.get(loader.entityId);
1382 if (record?.workerId == null)
1383 { continue; }
1384 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
1385 }
1386 let best = null;
1387 let bestVotes = -1;
1388 for (const [workerId, count] of votes)
1389 {
1390 if (count > bestVotes)
1391 {
1392 best = workerId;
1393 bestVotes = count;
1394 }
1395 }
1396 return best;
1397 }
1398
1399 #pickWorker (regionX, regionY, preferredWorkerId)
1400 {
1401 const pinned = this.pinRegion?.(regionX, regionY);
1402 if (pinned != null)
1403 { return pinned; }
1404
1405 const neighborOwners = [];
1406 for (let dy = -1; dy <= 1; dy++)
1407 {
1408 for (let dx = -1; dx <= 1; dx++)
1409 {
1410 if (dx === 0 && dy === 0)
1411 { continue; }
1412 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
1413 if (owner != null)
1414 { neighborOwners.push(owner); }
1415 }
1416 }
1417
1418 const scores = this.workers.map((_, workerId) => ({
1419 workerId,
1420 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
1421 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
1422 }));
1423
1424 if (preferredWorkerId != null && scores[preferredWorkerId])
1425 {
1426 const preferred = scores[preferredWorkerId];
1427 if (preferred.neighbors > 0 || neighborOwners.length === 0)
1428 { return preferredWorkerId; }
1429 }
1430
1431 scores.sort((left, right) =>
1432 right.neighbors - left.neighbors
1433 || left.load - right.load
1434 || left.workerId - right.workerId
1435 );
1436 return scores[0].workerId;
1437 }
1438
1439 #ownerOfTile (tileX, tileY)
1440 {
1441 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
1442 }
1443
1444 #regionKeyForChunk (chunkX, chunkY)
1445 {
1446 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
1447 }
1448
1449 #regionChunkBlobs (regionX, regionY)
1450 {
1451 return chunksInRegion(regionX, regionY).map((coord) => ({
1452 chunkX: coord.chunkX,
1453 chunkY: coord.chunkY,
1454 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
1455 }));
1456 }
1457
1458 #authoredChunk (chunkX, chunkY)
1459 {
1460 const key = chunkKey(chunkX, chunkY);
1461 if (this.authoredCache.has(key))
1462 { return this.authoredCache.get(key); }
1463 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
1464 const data = row
1465 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
1466 : createEmptyChunkData(this.settings.defaultGroundTypeId);
1467 this.authoredCache.set(key, data);
1468 return data;
1469 }
1470
1471 #syntheticSnapshot (chunkX, chunkY)
1472 {
1473 const data = this.#authoredChunk(chunkX, chunkY);
1474 return {
1475 chunkX,
1476 chunkY,
1477 open: data.open,
1478 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
1479 grounds: data.grounds,
1480 blocks: data.blocks,
1481 light: data.light,
1482 entities: [],
1483 groundItems: []
1484 };
1485 }
1486
1487 #occupiedTile (tileX, tileY)
1488 {
1489 for (const record of this.directory.values())
1490 {
1491 if (record.tileX === tileX && record.tileY === tileY)
1492 { return record.entityId; }
1493 }
1494 return null;
1495 }
1496
1497 #queueReplication (event)
1498 {
1499 if (event)
1500 { this.replication.push(event); }
1501 }
1502
1503 #stepSpawners ()
1504 {
1505 const events = [];
1506 for (const worker of this.workers)
1507 {
1508 const result = worker.call({ type: WorkerMessage.stepSpawners });
1509 for (const request of result?.spawnRequests ?? [])
1510 {
1511 try
1512 {
1513 this.spawnEntity(mobComponents(request), { requireResident: true });
1514 }
1515 catch
1516 { continue; }
1517 }
1518 }
1519 return events;
1520 }
1521
1522 #restoreGroundItems (regionX, regionY, workerId)
1523 {
1524 const bounds = regionTileBounds(regionX, regionY);
1525 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
1526 .filter((item) => item.expiresAt > this.now);
1527 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
1528 this.workers[workerId].call({
1529 type: WorkerMessage.setGroundItems,
1530 regionX,
1531 regionY,
1532 items
1533 });
1534 }
1535
1536 #persistGroundEvent (event)
1537 {
1538 if (event.type === "ground-item-appear")
1539 {
1540 this.stateDb.upsertGroundItem({
1541 groundItemId: event.groundItemId,
1542 tileX: event.tileX,
1543 tileY: event.tileY,
1544 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
1545 droppedAt: event.droppedAt ?? this.now,
1546 expiresAt: event.expiresAt,
1547 source: event.source ?? "player-drop",
1548 droppedByCharacterId: event.droppedByCharacterId ?? null
1549 });
1550 }
1551 if (event.type === "ground-item-despawn")
1552 { this.stateDb.deleteGroundItem(event.groundItemId); }
1553 }
1554
1555 #saveBag (entityId, workerId)
1556 {
1557 const record = this.directory.get(entityId);
1558 const bag = this.workers[workerId].call({
1559 type: WorkerMessage.inspectBag,
1560 entityId
1561 });
1562 if (!bag || !record?.characterId)
1563 { return; }
1564 this.#saveBagFromView(record.characterId, bag);
1565 const skills = this.workers[workerId].call({
1566 type: WorkerMessage.inspectSkills,
1567 entityId
1568 });
1569 if (skills)
1570 { this.stateDb.saveSkills(record.characterId, skills); }
1571 }
1572
1573 #applySkillsUpdated (event)
1574 {
1575 if (!event?.characterId || !event.stored)
1576 { return; }
1577 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
1578 this.pushSkills(event.characterId, event.skills ?? []);
1579 }
1580
1581 #saveBagFromView (characterId, bag)
1582 {
1583 this.stateDb.saveBag(characterId, {
1584 inventory: bag.inventory,
1585 equipment: bag.equipment,
1586 vault: bag.vault,
1587 vaultReserved: bag.vaultReserved
1588 });
1589 }
1590
1591 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
1592 {
1593 const onlineId = this.characterEntities.get(issuerCharacterId);
1594 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1595 if (!bag)
1596 { return { ok: false, error: "Issuer vault not found." }; }
1597 const reserved = [...(bag.vaultReserved ?? [])];
1598 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
1599 if (index < 0)
1600 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1601 const [stack] = reserved.splice(index, 1);
1602 bag.vaultReserved = reserved;
1603 this.stateDb.saveBag(issuerCharacterId, bag);
1604 if (onlineId)
1605 {
1606 this.applyBag(onlineId, bag);
1607 this.pushInventory(issuerCharacterId, bag);
1608 }
1609 return { ok: true, stack };
1610 }
1611
1612 restoreChequeReservation (issuerCharacterId, stack)
1613 {
1614 const onlineId = this.characterEntities.get(issuerCharacterId);
1615 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1616 if (!bag)
1617 { return; }
1618 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
1619 this.stateDb.saveBag(issuerCharacterId, bag);
1620 if (onlineId)
1621 {
1622 this.applyBag(onlineId, bag);
1623 this.pushInventory(issuerCharacterId, bag);
1624 }
1625 }
1626
1627 #remember (view, workerId)
1628 {
1629 if (!view)
1630 { return; }
1631 this.directory.set(view.entityId, { ...view, workerId });
1632 if (view.characterId)
1633 { this.characterEntities.set(view.characterId, view.entityId); }
1634 }
1635
1636 #applyMoveToDirectory (event)
1637 {
1638 const record = this.directory.get(event.entityId);
1639 if (!record)
1640 { return; }
1641 record.tileX = event.tileX;
1642 record.tileY = event.tileY;
1643 record.gait = event.gait;
1644 if (event.worldX != null)
1645 { record.worldX = event.worldX; }
1646 if (event.worldY != null)
1647 { record.worldY = event.worldY; }
1648 if (event.freeFlight != null)
1649 { record.freeFlight = !!event.freeFlight; }
1650 }
1651
1652 #forget (entityId)
1653 {
1654 const record = this.directory.get(entityId);
1655 if (record?.characterId)
1656 { this.characterEntities.delete(record.characterId); }
1657 this.directory.delete(entityId);
1658 }
1659}