BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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