BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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