BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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