BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 27.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 { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";
33
34export class Simulation
35{
36 constructor (worldDb, stateDb, options = {})
37 {
38 this.worldDb = worldDb;
39 this.stateDb = stateDb;
40 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
41 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
42 this.pinRegion = options.pinRegion ?? null;
43 this.nowFn = options.now ?? (() => Date.now());
44 this.workers = [];
45 this.regionOwner = new Map();
46 this.regionGraceUntil = new Map();
47 this.directory = new Map();
48 this.characterEntities = new Map();
49 this.commandQueue = [];
50 this.replication = [];
51 this.authoredCache = new Map();
52 this.nextEntityId = 1;
53 this.nextGroundItemId = stateDb.nextGroundItemId();
54 this.tickIndex = 0;
55 this.movementTickCounter = 0;
56 this.lastTickAt = null;
57 this.movementAccumulator = 0;
58 this.activeRevisionId = worldDb.getActiveRevisionId();
59 this.settings = worldDb.getLiveSettings();
60
61 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
62 for (let workerId = 0; workerId < this.workerCount; workerId++)
63 {
64 const worker = new WorkerImpl(workerId);
65 worker.call({
66 type: WorkerMessage.configure,
67 settings: this.settings,
68 activeRevisionId: this.activeRevisionId
69 });
70 this.workers.push(worker);
71 }
72 }
73
74 get now ()
75 {
76 return this.nowFn();
77 }
78
79 applySettings (settings)
80 {
81 this.settings = { ...this.settings, ...settings };
82 this.#configureWorkers();
83 }
84
85 reloadWorld ()
86 {
87 this.activeRevisionId = this.worldDb.getActiveRevisionId();
88 this.settings = this.worldDb.getLiveSettings();
89 this.authoredCache.clear();
90 this.#configureWorkers();
91 for (const [key, workerId] of this.regionOwner)
92 {
93 const { regionX, regionY } = parseRegionKey(key);
94 this.workers[workerId].call({
95 type: WorkerMessage.replaceRegionChunks,
96 chunks: this.#regionChunkBlobs(regionX, regionY)
97 });
98 }
99 this.#syncAllReplicas();
100 }
101
102 enqueue (sessionId, command)
103 {
104 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
105 }
106
107 step (now = this.now)
108 {
109 this.tickIndex += 1;
110 const events = [];
111 const commands = this.commandQueue.splice(0);
112 for (const item of commands)
113 {
114 try
115 {
116 events.push(...this.#routeCommand(item));
117 }
118 catch (error)
119 {
120 events.push({
121 sessionId: item.sessionId,
122 type: "command-error",
123 message: error.userFacing ? error.message : "Command failed."
124 });
125 }
126 }
127
128 this.#recalculateActivation(now);
129
130 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
131 const expectedDt = 1 / simHz;
132 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
133 ? expectedDt
134 : Math.min(0.25, (now - this.lastTickAt) / 1000);
135 this.lastTickAt = now;
136
137 {
138 const transfers = [];
139 for (const worker of this.workers)
140 {
141 const result = worker.call({ type: WorkerMessage.stepSystems, now });
142 for (const event of result?.events ?? [])
143 {
144 if (event.type === "entity-move")
145 { this.#applyMoveToDirectory(event); }
146 if (event.type === "entity-despawn")
147 { this.#forget(event.entityId); }
148 this.#persistGroundEvent(event);
149 events.push(event);
150 }
151 for (const request of result?.transferRequests ?? [])
152 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
153 }
154 if (transfers.length)
155 {
156 events.push(...this.#applyTransfers(transfers));
157 this.#recalculateActivation(now);
158 }
159 }
160
161 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
162 this.movementAccumulator += dt * movementHz;
163 while (this.movementAccumulator >= 1)
164 {
165 this.movementAccumulator -= 1;
166 this.movementTickCounter += 1;
167 const transfers = [];
168 for (const worker of this.workers)
169 {
170 const result = worker.call({ type: WorkerMessage.stepMovement, now });
171 for (const event of result?.events ?? [])
172 {
173 if (event.type === "entity-move")
174 { this.#applyMoveToDirectory(event); }
175 this.#persistGroundEvent(event);
176 events.push(event);
177 }
178 for (const request of result?.transferRequests ?? [])
179 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
180 }
181 events.push(...this.#applyTransfers(transfers));
182 this.#recalculateActivation(now);
183 }
184
185 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
186 { events.push(...this.#stepSpawners()); }
187
188 this.#syncGhosts();
189 return { now, events, replication: this.drainReplication() };
190 }
191
192 drainReplication ()
193 {
194 return this.replication.splice(0);
195 }
196
197 worldTime (now = this.now)
198 {
199 const date = new Date(now);
200 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
201 return {
202 unixMs: now,
203 worldUnixMs: date.getTime(),
204 iso: date.toISOString(),
205 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600
206 };
207 }
208
209 spawnCharacter (sessionId, character)
210 {
211 this.despawnCharacter(character.character_id);
212 // Despawn may have just written the live tile; never trust a stale row snapshot.
213 const row = this.stateDb.getCharacter(character.character_id) ?? character;
214 let tileX = row.tile_x;
215 let tileY = row.tile_y;
216 const gait = row.gait || character.gait || GAIT.walk;
217 const preferred = this.#findResumeTile(tileX, tileY);
218 if (!preferred)
219 {
220 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
221 error.userFacing = true;
222 throw error;
223 }
224 if (preferred.tileX !== tileX || preferred.tileY !== tileY)
225 {
226 tileX = preferred.tileX;
227 tileY = preferred.tileY;
228 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait);
229 }
230
231 const bag = this.stateDb.getBag(character.character_id) ?? {
232 inventory: emptySlots(),
233 equipment: emptyEquipment(),
234 currency: 0,
235 vault: emptySlots(),
236 vaultCurrency: 0
237 };
238 const entityId = this.nextEntityId++;
239 const components = {
240 position: { tileX, tileY },
241 movement: { gait, walkCarry: 0 },
242 path: { tiles: [] },
243 appearance: {
244 sex: character.sex ?? row.sex,
245 firstName: character.first_name ?? row.first_name,
246 lastName: character.last_name ?? row.last_name
247 },
248 character: {
249 characterId: character.character_id ?? row.character_id,
250 accountId: character.account_id ?? row.account_id
251 },
252 networkIdentity: { sessionId },
253 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
254 inventory: { slots: bag.inventory ?? emptySlots() },
255 equipment: bag.equipment ?? emptyEquipment(),
256 currency: { amount: bag.currency ?? 0 },
257 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 },
258 health: { current: 20, max: 20 },
259 combat: { targetEntityId: null, nextSwingAt: 0 },
260 skills: { levels: { ...DEFAULT_PLAYER_SKILL_LEVELS } }
261 };
262 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
263 const workerId = this.#ownerOfTile(tileX, tileY);
264 const view = this.workers[workerId].call({
265 type: WorkerMessage.spawn,
266 entityId,
267 components
268 });
269 this.#remember(view, workerId);
270 this.#queueReplication(replicationSpawn(view));
271 this.#recalculateActivation(this.now);
272 this.#syncGhosts();
273 return entityId;
274 }
275
276 spawnEntity (components, options = {})
277 {
278 const entityId = options.entityId ?? this.nextEntityId++;
279 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
280 const position = components.position;
281 if (!position)
282 { throw new Error("spawnEntity requires position."); }
283 if (components.chunkLoader)
284 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
285 else
286 {
287 this.#ensureRegion(
288 tileToRegion(position.tileX),
289 tileToRegion(position.tileY),
290 null
291 );
292 }
293 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
294 const view = this.workers[workerId].call({
295 type: WorkerMessage.spawn,
296 entityId,
297 components
298 });
299 this.#remember(view, workerId);
300 if (components.appearance)
301 { this.#queueReplication(replicationSpawn(view)); }
302 this.#recalculateActivation(this.now);
303 this.#syncGhosts();
304 return entityId;
305 }
306
307 despawnCharacter (characterId)
308 {
309 const entityId = this.characterEntities.get(characterId);
310 if (!entityId)
311 { return; }
312 const record = this.directory.get(entityId);
313 if (!record)
314 {
315 this.characterEntities.delete(characterId);
316 return;
317 }
318 this.#saveBag(entityId, record.workerId);
319 const dropped = this.workers[record.workerId].call({
320 type: WorkerMessage.despawnCharacter,
321 characterId
322 });
323 if (dropped)
324 {
325 this.stateDb.saveCharacterPosition(
326 characterId,
327 dropped.tileX,
328 dropped.tileY,
329 dropped.gait ?? GAIT.walk
330 );
331 this.#queueReplication(replicationDespawn(dropped));
332 }
333 this.#forget(entityId);
334 this.#recalculateActivation(this.now);
335 this.#syncGhosts();
336 }
337
338 entityForCharacter (characterId)
339 {
340 return this.characterEntities.get(characterId) ?? null;
341 }
342
343 entityRecord (entityId)
344 {
345 const record = this.directory.get(entityId);
346 return record ? { ...record } : null;
347 }
348
349 positionOf (entityId)
350 {
351 const record = this.directory.get(entityId);
352 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
353 }
354
355 bagOf (entityId)
356 {
357 const record = this.directory.get(entityId);
358 if (!record)
359 { return null; }
360 return this.workers[record.workerId].call({
361 type: WorkerMessage.inspectBag,
362 entityId
363 });
364 }
365
366 snapshotFor (entityId)
367 {
368 const record = this.directory.get(entityId);
369 if (!record)
370 { return []; }
371 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
372 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
373 }
374
375 snapshotChunk (chunkX, chunkY)
376 {
377 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
378 if (owner == null)
379 { return this.#syntheticSnapshot(chunkX, chunkY); }
380 return this.workers[owner].call({
381 type: WorkerMessage.snapshotChunk,
382 chunkX,
383 chunkY
384 });
385 }
386
387 findOpenSpawn ()
388 {
389 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
390 for (const coord of coords)
391 {
392 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
393 if (!data.open)
394 { continue; }
395 for (let localY = 0; localY < CHUNK_SIZE; localY++)
396 {
397 for (let localX = 0; localX < CHUNK_SIZE; localX++)
398 {
399 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
400 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
401 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
402 { return { tileX, tileY }; }
403 }
404 }
405 }
406 return null;
407 }
408
409 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
410 #findResumeTile (tileX, tileY, radius = 24)
411 {
412 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
413 }
414
415 #findNearbyEnterable (originX, originY, maxRadius)
416 {
417 for (let radius = 0; radius <= maxRadius; radius++)
418 {
419 for (let dy = -radius; dy <= radius; dy++)
420 {
421 for (let dx = -radius; dx <= radius; dx++)
422 {
423 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
424 { continue; }
425 const tileX = originX + dx;
426 const tileY = originY + dy;
427 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
428 { return { tileX, tileY }; }
429 }
430 }
431 }
432 return null;
433 }
434
435 isEnterable (tileX, tileY)
436 {
437 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
438 if (!data.open)
439 { return false; }
440 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
441 }
442
443 debugWorld ()
444 {
445 const loaders = this.#allLoaders();
446 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
447 const simulatingChunks = [...chunkSim.entries()]
448 .filter(([, count]) => count > 0)
449 .map(([key]) => key)
450 .sort();
451 return {
452 tickIndex: this.tickIndex,
453 workerCount: this.workers.length,
454 workerMode: this.workerMode,
455 simulatingChunks,
456 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
457 ...parseRegionKey(key),
458 workerId,
459 state: REGION_RUNTIME_STATE.resident,
460 refs: regionRes.get(key) ?? 0,
461 graceUntil: this.regionGraceUntil.get(key) ?? null
462 })),
463 entities: [...this.directory.values()].map((entity) => ({
464 entityId: entity.entityId,
465 workerId: entity.workerId,
466 tileX: entity.tileX,
467 tileY: entity.tileY,
468 characterId: entity.characterId
469 }))
470 };
471 }
472
473 async shutdown ()
474 {
475 for (const characterId of [...this.characterEntities.keys()])
476 { this.despawnCharacter(characterId); }
477 this.forceUnloadAll();
478 await Promise.all(this.workers.map((worker) => worker.terminate()));
479 }
480
481 forceUnloadAll ()
482 {
483 for (const key of [...this.regionOwner.keys()])
484 {
485 const { regionX, regionY } = parseRegionKey(key);
486 this.#unloadRegion(regionX, regionY);
487 }
488 }
489
490 #configureWorkers ()
491 {
492 for (const worker of this.workers)
493 {
494 worker.call({
495 type: WorkerMessage.configure,
496 settings: this.settings,
497 activeRevisionId: this.activeRevisionId
498 });
499 }
500 }
501
502 #routeCommand (item)
503 {
504 const entityId = this.characterEntities.get(item.command.characterId);
505 const record = entityId ? this.directory.get(entityId) : null;
506 if (!record)
507 {
508 const error = new Error("Character is not in the world.");
509 error.userFacing = true;
510 throw error;
511 }
512 if (item.command.type === "drop-item" && item.command.groundItemId == null)
513 { item.command.groundItemId = this.nextGroundItemId++; }
514 const result = this.workers[record.workerId].call({
515 type: WorkerMessage.command,
516 sessionId: item.sessionId,
517 command: item.command,
518 now: item.receivedAt ?? this.now
519 });
520 const view = this.workers[record.workerId].call({
521 type: WorkerMessage.inspect,
522 entityId: record.entityId
523 });
524 if (view)
525 { this.#remember(view, record.workerId); }
526 if (result?.private)
527 { this.#saveBagFromView(item.command.characterId, result.private); }
528 if (result?.appearanceChanged && view)
529 { this.#queueReplication(replicationAppearance(view)); }
530 if (result?.remainder)
531 {
532 this.stateDb.saveInheritance(
533 this.stateDb.getCharacter(item.command.characterId).account_id,
534 { slots: result.remainder, currency: 0 }
535 );
536 }
537 for (const event of result?.events ?? [])
538 { this.#persistGroundEvent(event); }
539 const events = [...(result?.events ?? [])];
540 if (result?.private)
541 {
542 events.push({
543 type: "inventory",
544 sessionId: item.sessionId,
545 bank: !!result.bank,
546 ...result.private
547 });
548 }
549 return events;
550 }
551
552 #recalculateActivation (now)
553 {
554 const loaders = this.#allLoaders();
555 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
556
557 for (const [key, count] of regionRes)
558 {
559 if (count <= 0)
560 { continue; }
561 const { regionX, regionY } = parseRegionKey(key);
562 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
563 this.regionGraceUntil.delete(key);
564 }
565
566 for (const [key] of [...this.regionOwner.entries()])
567 {
568 if ((regionRes.get(key) ?? 0) > 0)
569 { continue; }
570 if (!this.regionGraceUntil.has(key))
571 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
572 if (now >= this.regionGraceUntil.get(key))
573 {
574 const { regionX, regionY } = parseRegionKey(key);
575 this.#unloadRegion(regionX, regionY);
576 }
577 }
578
579 for (const [workerId, worker] of this.workers.entries())
580 {
581 const chunkKeys = [];
582 for (const [key, count] of chunkSim)
583 {
584 if (count <= 0)
585 { continue; }
586 const { chunkX, chunkY } = parseChunkKey(key);
587 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
588 { chunkKeys.push(key); }
589 }
590 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
591 }
592 this.#syncAllReplicas();
593 }
594
595 #ensureCoverage (tileX, tileY, loader)
596 {
597 const coverage = loaderCoverage(tileX, tileY, loader);
598 let preferred = this.#ownerOfTile(tileX, tileY);
599 for (const region of coverage.residentRegions)
600 {
601 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
602 if (preferred == null)
603 { preferred = owner; }
604 }
605 }
606
607 #ensureRegion (regionX, regionY, preferredWorkerId)
608 {
609 const key = regionKey(regionX, regionY);
610 if (this.regionOwner.has(key))
611 { return this.regionOwner.get(key); }
612 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
613 this.workers[workerId].call({
614 type: WorkerMessage.assignRegion,
615 regionX,
616 regionY,
617 chunks: this.#regionChunkBlobs(regionX, regionY)
618 });
619 this.regionOwner.set(key, workerId);
620 this.#restorePersistent(regionX, regionY, workerId);
621 this.#restoreGroundItems(regionX, regionY, workerId);
622 return workerId;
623 }
624
625 #unloadRegion (regionX, regionY)
626 {
627 const key = regionKey(regionX, regionY);
628 const workerId = this.regionOwner.get(key);
629 if (workerId == null)
630 { return; }
631 const bounds = regionTileBounds(regionX, regionY);
632 const { dropped, groundItems } = this.workers[workerId].call({
633 type: WorkerMessage.dropRegion,
634 regionX,
635 regionY
636 });
637 const persistent = [];
638 for (const record of dropped ?? [])
639 {
640 if (record.characterId)
641 {
642 this.stateDb.saveCharacterPosition(
643 record.characterId,
644 record.tileX,
645 record.tileY,
646 record.gait ?? GAIT.walk
647 );
648 }
649 if (record.persistent)
650 { persistent.push(record); }
651 this.#forget(record.entityId);
652 }
653 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
654 for (const item of groundItems ?? [])
655 { this.stateDb.upsertGroundItem(item); }
656 this.regionOwner.delete(key);
657 this.regionGraceUntil.delete(key);
658 }
659
660 #restorePersistent (regionX, regionY, workerId)
661 {
662 const bounds = regionTileBounds(regionX, regionY);
663 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
664 for (const row of rows)
665 {
666 if (this.directory.has(row.entity_id))
667 { continue; }
668 const components = JSON.parse(row.components_blob);
669 const view = this.workers[workerId].call({
670 type: WorkerMessage.spawn,
671 entityId: row.entity_id,
672 components
673 });
674 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
675 this.#remember(view, workerId);
676 }
677 }
678
679 #applyTransfers (requests)
680 {
681 const events = [];
682 for (const request of requests)
683 {
684 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
685 if (destWorkerId === request.fromWorkerId)
686 {
687 this.workers[request.fromWorkerId].call({
688 type: WorkerMessage.abortTransfer,
689 entityId: request.entityId
690 });
691 continue;
692 }
693 let result;
694 try
695 {
696 result = this.workers[destWorkerId].call({
697 type: WorkerMessage.applyTransfer,
698 payload: request.payload,
699 destTileX: request.destTileX,
700 destTileY: request.destTileY
701 });
702 }
703 catch
704 {
705 result = { accepted: false };
706 }
707 if (!result?.accepted)
708 {
709 this.workers[request.fromWorkerId].call({
710 type: WorkerMessage.abortTransfer,
711 entityId: request.entityId
712 });
713 continue;
714 }
715 this.workers[request.fromWorkerId].call({
716 type: WorkerMessage.commitTransfer,
717 entityId: request.entityId
718 });
719 this.#remember(result.entity, destWorkerId);
720 events.push({
721 type: "entity-move",
722 entityId: request.entityId,
723 fromTileX: request.fromTileX,
724 fromTileY: request.fromTileY,
725 tileX: result.entity.tileX,
726 tileY: result.entity.tileY,
727 gait: result.entity.gait
728 });
729 }
730 return events;
731 }
732
733 #syncAllReplicas ()
734 {
735 for (const [workerId, worker] of this.workers.entries())
736 {
737 const ownedKeys = new Set();
738 for (const [key, owner] of this.regionOwner)
739 {
740 if (owner !== workerId)
741 { continue; }
742 const { regionX, regionY } = parseRegionKey(key);
743 for (const chunk of chunksInRegion(regionX, regionY))
744 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
745 }
746 const replicas = [];
747 for (const key of replicaNeededForOwnedChunks(ownedKeys))
748 {
749 if (ownedKeys.has(key))
750 { continue; }
751 const { chunkX, chunkY } = parseChunkKey(key);
752 replicas.push({
753 chunkX,
754 chunkY,
755 data: this.#authoredChunk(chunkX, chunkY)
756 });
757 }
758 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
759 }
760 }
761
762 #syncGhosts ()
763 {
764 const entities = [];
765 for (const worker of this.workers)
766 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
767 for (const [workerId, worker] of this.workers.entries())
768 {
769 const ghosts = entities.filter((entity) =>
770 {
771 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
772 { return false; }
773 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
774 });
775 worker.call({ type: WorkerMessage.setGhosts, ghosts });
776 }
777 }
778
779 #nearWorker (workerId, tileX, tileY)
780 {
781 const chunkX = tileToChunk(tileX);
782 const chunkY = tileToChunk(tileY);
783 for (const [key, owner] of this.regionOwner)
784 {
785 if (owner !== workerId)
786 { continue; }
787 const { regionX, regionY } = parseRegionKey(key);
788 for (const chunk of chunksInRegion(regionX, regionY))
789 {
790 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
791 { return true; }
792 }
793 }
794 return false;
795 }
796
797 #allLoaders ()
798 {
799 const loaders = [];
800 for (const worker of this.workers)
801 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
802 return loaders;
803 }
804
805 #preferredWorkerForRegion (loaders, regionX, regionY)
806 {
807 const votes = new Map();
808 for (const loader of loaders)
809 {
810 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
811 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
812 { continue; }
813 const record = this.directory.get(loader.entityId);
814 if (record?.workerId == null)
815 { continue; }
816 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
817 }
818 let best = null;
819 let bestVotes = -1;
820 for (const [workerId, count] of votes)
821 {
822 if (count > bestVotes)
823 {
824 best = workerId;
825 bestVotes = count;
826 }
827 }
828 return best;
829 }
830
831 #pickWorker (regionX, regionY, preferredWorkerId)
832 {
833 const pinned = this.pinRegion?.(regionX, regionY);
834 if (pinned != null)
835 { return pinned; }
836
837 const neighborOwners = [];
838 for (let dy = -1; dy <= 1; dy++)
839 {
840 for (let dx = -1; dx <= 1; dx++)
841 {
842 if (dx === 0 && dy === 0)
843 { continue; }
844 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
845 if (owner != null)
846 { neighborOwners.push(owner); }
847 }
848 }
849
850 const scores = this.workers.map((_, workerId) => ({
851 workerId,
852 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
853 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
854 }));
855
856 if (preferredWorkerId != null && scores[preferredWorkerId])
857 {
858 const preferred = scores[preferredWorkerId];
859 if (preferred.neighbors > 0 || neighborOwners.length === 0)
860 { return preferredWorkerId; }
861 }
862
863 scores.sort((left, right) =>
864 right.neighbors - left.neighbors
865 || left.load - right.load
866 || left.workerId - right.workerId
867 );
868 return scores[0].workerId;
869 }
870
871 #ownerOfTile (tileX, tileY)
872 {
873 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
874 }
875
876 #regionKeyForChunk (chunkX, chunkY)
877 {
878 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
879 }
880
881 #regionChunkBlobs (regionX, regionY)
882 {
883 return chunksInRegion(regionX, regionY).map((coord) => ({
884 chunkX: coord.chunkX,
885 chunkY: coord.chunkY,
886 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
887 }));
888 }
889
890 #authoredChunk (chunkX, chunkY)
891 {
892 const key = chunkKey(chunkX, chunkY);
893 if (this.authoredCache.has(key))
894 { return this.authoredCache.get(key); }
895 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
896 const data = row
897 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
898 : createEmptyChunkData(this.settings.defaultGroundTypeId);
899 this.authoredCache.set(key, data);
900 return data;
901 }
902
903 #syntheticSnapshot (chunkX, chunkY)
904 {
905 const data = this.#authoredChunk(chunkX, chunkY);
906 return {
907 chunkX,
908 chunkY,
909 open: data.open,
910 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
911 grounds: data.grounds,
912 blocks: data.blocks,
913 light: data.light,
914 entities: [],
915 groundItems: []
916 };
917 }
918
919 #occupiedTile (tileX, tileY)
920 {
921 for (const record of this.directory.values())
922 {
923 if (record.tileX === tileX && record.tileY === tileY)
924 { return record.entityId; }
925 }
926 return null;
927 }
928
929 #queueReplication (event)
930 {
931 if (event)
932 { this.replication.push(event); }
933 }
934
935 #stepSpawners ()
936 {
937 const events = [];
938 for (const worker of this.workers)
939 {
940 const result = worker.call({ type: WorkerMessage.stepSpawners });
941 for (const request of result?.spawnRequests ?? [])
942 {
943 try
944 {
945 this.spawnEntity(mobComponents(request));
946 }
947 catch
948 { continue; }
949 }
950 }
951 return events;
952 }
953
954 #restoreGroundItems (regionX, regionY, workerId)
955 {
956 const bounds = regionTileBounds(regionX, regionY);
957 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
958 .filter((item) => item.expiresAt > this.now);
959 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
960 this.workers[workerId].call({
961 type: WorkerMessage.setGroundItems,
962 regionX,
963 regionY,
964 items
965 });
966 }
967
968 #persistGroundEvent (event)
969 {
970 if (event.type === "ground-item-appear")
971 {
972 this.stateDb.upsertGroundItem({
973 groundItemId: event.groundItemId,
974 tileX: event.tileX,
975 tileY: event.tileY,
976 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
977 droppedAt: event.droppedAt ?? this.now,
978 expiresAt: event.expiresAt,
979 source: event.source ?? "player-drop",
980 droppedByCharacterId: event.droppedByCharacterId ?? null
981 });
982 }
983 if (event.type === "ground-item-despawn")
984 { this.stateDb.deleteGroundItem(event.groundItemId); }
985 }
986
987 #saveBag (entityId, workerId)
988 {
989 const record = this.directory.get(entityId);
990 const bag = this.workers[workerId].call({
991 type: WorkerMessage.inspectBag,
992 entityId
993 });
994 if (!bag || !record?.characterId)
995 { return; }
996 this.#saveBagFromView(record.characterId, bag);
997 }
998
999 #saveBagFromView (characterId, bag)
1000 {
1001 this.stateDb.saveBag(characterId, {
1002 inventory: bag.inventory,
1003 equipment: bag.equipment,
1004 currency: bag.currency,
1005 vault: bag.vault,
1006 vaultCurrency: bag.vaultCurrency
1007 });
1008 }
1009
1010 #remember (view, workerId)
1011 {
1012 if (!view)
1013 { return; }
1014 this.directory.set(view.entityId, { ...view, workerId });
1015 if (view.characterId)
1016 { this.characterEntities.set(view.characterId, view.entityId); }
1017 }
1018
1019 #applyMoveToDirectory (event)
1020 {
1021 const record = this.directory.get(event.entityId);
1022 if (!record)
1023 { return; }
1024 record.tileX = event.tileX;
1025 record.tileY = event.tileY;
1026 record.gait = event.gait;
1027 if (event.worldX != null)
1028 { record.worldX = event.worldX; }
1029 if (event.worldY != null)
1030 { record.worldY = event.worldY; }
1031 if (event.freeFlight != null)
1032 { record.freeFlight = !!event.freeFlight; }
1033 }
1034
1035 #forget (entityId)
1036 {
1037 const record = this.directory.get(entityId);
1038 if (record?.characterId)
1039 { this.characterEntities.delete(record.characterId); }
1040 this.directory.delete(entityId);
1041 }
1042}