BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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