BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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