BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 77.4 KiB Download Raw
1import
2 {
3 CHUNK_SIZE,
4 DEFAULT_CHUNK_LOADER,
5 GAIT,
6 REGION_RUNTIME_STATE,
7 VISIBLE_CHUNK_RADIUS,
8 STATIC_CHUNK_RADIUS,
9 WORLD_YEAR_OFFSET
10 } from "../../../shared/protocol/constants.js";
11import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js";
12import
13 {
14 chunkKey,
15 chunkToRegion,
16 chunksInRegion,
17 parseChunkKey,
18 parseRegionKey,
19 regionKey,
20 regionTileBounds,
21 tileToChunk,
22 tileToLocal,
23 tileToRegion,
24 visibleChunkCoords
25 } from "../world/coordinates.js";
26import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
27import { closedNeighborEdges } from "../world/chunkFlags.js";
28import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
29import { InProcessWorker } from "./inProcessWorker.js";
30import { ThreadWorker } from "./threadWorker.js";
31import { WorkerMessage } from "./protocol.js";
32import { replicaNeededForOwnedChunks } from "./workerWorld.js";
33import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
34import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
35import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
37import { mobComponents } from "./spawners.js";
38import { shadeSummonComponents } from "../spells/summons.js";
39import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
40import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
41import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
42import { BlockType } from "../../../shared/definitions/tiles.js";
43import { ItemId } from "../../../shared/definitions/items.js";
44import { seasonIdAt } from "../../../shared/world/season.js";
45import { CourierService } from "../courier/service.js";
46import { MarketService } from "../market/service.js";
47import { BountyService } from "../bounty/service.js";
48import { BarberService } from "../barber/service.js";
49import { findReservedChequeIndex } from "../items/bags.js";
50import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
51import { QuestContentCache } from "../quests/contentCache.js";
52import { QuestRuntime } from "../quests/runtime.js";
53import { chebyshev } from "../combat/service.js";
54
55export class Simulation
56{
57 constructor(worldDb, stateDb, options = {})
58 {
59 this.worldDb = worldDb;
60 this.stateDb = stateDb;
61 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
62 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
63 this.pinRegion = options.pinRegion ?? null;
64 this.nowFn = options.now ?? (() => Date.now());
65 this.workers = [];
66 this.regionOwner = new Map();
67 this.regionGraceUntil = new Map();
68 this.directory = new Map();
69 this.characterEntities = new Map();
70 this.commandQueue = [];
71 this.replication = [];
72 this.pendingPrivate = [];
73 this.courier = null;
74 this.market = null;
75 this.altarTiles = [];
76 this.authoredCache = new Map();
77 this.simulatingChunkKeys = new Set();
78 this.nextEntityId = 1;
79 this.nextGroundItemId = stateDb.nextGroundItemId();
80 this.tickIndex = 0;
81 this.movementTickCounter = 0;
82 this.lastTickAt = null;
83 this.movementAccumulator = 0;
84 this.activeRevisionId = worldDb.getActiveRevisionId();
85 this.settings = worldDb.getLiveSettings();
86 this.questContent = new QuestContentCache(worldDb);
87 this.dimensions = this.#loadDimensionsCache();
88 this.quests = null;
89
90 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
91 for (let workerId = 0; workerId < this.workerCount; workerId++)
92 {
93 const worker = new WorkerImpl(workerId);
94 worker.call({
95 type: WorkerMessage.configure,
96 settings: this.settings,
97 activeRevisionId: this.activeRevisionId
98 });
99 this.workers.push(worker);
100 }
101 for (const worker of this.workers)
102 {
103 if (!worker.world)
104 { continue; }
105 worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
106 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
107 }
108 this.courier = new CourierService({
109 stateDb: this.stateDb,
110 worldDb: this.worldDb,
111 simulation: this
112 });
113 this.market = new MarketService({
114 stateDb: this.stateDb,
115 worldDb: this.worldDb,
116 simulation: this
117 });
118 this.bounty = new BountyService(this.stateDb, this, this.courier);
119 this.barber = new BarberService(this.stateDb, this);
120 this.quests = new QuestRuntime({
121 stateDb: this.stateDb,
122 content: this.questContent,
123 simulation: this
124 });
125 this.#refreshAltarIndex();
126 }
127
128 get now ()
129 {
130 return this.nowFn();
131 }
132
133 applySettings (settings)
134 {
135 this.settings = { ...this.settings, ...settings };
136 this.#configureWorkers();
137 }
138
139 /** Sparse last-sale map for editor base-price readouts. */
140 itemLastSalesSnapshot ()
141 {
142 return this.market?.snapshot?.() ?? {};
143 }
144
145 syncItemLastSales (lastSales)
146 {
147 const sales = {};
148 for (const [itemId, sale] of lastSales?.entries?.() ?? [])
149 { sales[String(itemId)] = sale; }
150 for (const worker of this.workers)
151 {
152 worker.call({
153 type: WorkerMessage.setItemLastSales,
154 sales
155 });
156 }
157 }
158
159 reloadWorld ()
160 {
161 this.activeRevisionId = this.worldDb.getActiveRevisionId();
162 this.settings = this.worldDb.getLiveSettings();
163 this.dimensions = this.#loadDimensionsCache();
164 this.authoredCache.clear();
165 this.#configureWorkers();
166 for (const [key, workerId] of this.regionOwner)
167 {
168 const { regionX, regionY, dimensionId } = parseRegionKey(key);
169 this.workers[workerId].call({
170 type: WorkerMessage.replaceRegionChunks,
171 regionX,
172 regionY,
173 dimensionId,
174 chunks: this.#regionChunkBlobs(regionX, regionY, dimensionId)
175 });
176 }
177 this.#syncAllReplicas();
178 this.courier?.refreshBankIndex();
179 this.courier?.refreshBountyOfficeIndex();
180 this.market?.refreshIndex();
181 this.questContent.reload();
182 this.quests?.closeAllSessions();
183 this.#refreshAltarIndex();
184 }
185
186 enqueue (sessionId, command)
187 {
188 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
189 }
190
191 step (now = this.now)
192 {
193 this.tickIndex += 1;
194 if ((this.tickIndex % 1200) === 0)
195 { this.worldDb.purgeExpiredDimensions(now); }
196 const events = [];
197 const commands = this.commandQueue.splice(0);
198 for (const item of commands)
199 {
200 try
201 {
202 events.push(...this.#routeCommand(item));
203 }
204 catch (error)
205 {
206 events.push({
207 sessionId: item.sessionId,
208 type: "command-error",
209 message: error.userFacing ? error.message : "Command failed."
210 });
211 }
212 }
213
214 this.#recalculateActivation(now);
215
216 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
217 const expectedDt = 1 / simHz;
218 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
219 ? expectedDt
220 : Math.min(0.25, (now - this.lastTickAt) / 1000);
221 this.lastTickAt = now;
222
223 {
224 const transfers = [];
225 const remoteMelee = [];
226 const remoteRanged = [];
227 for (const worker of this.workers)
228 {
229 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
230 for (const event of result?.events ?? [])
231 {
232 if (event.type === "remote-melee-resolve")
233 {
234 remoteMelee.push(event);
235 continue;
236 }
237 if (event.type === "remote-ranged-resolve")
238 {
239 remoteRanged.push(event);
240 continue;
241 }
242 if (event.type === "summon-entity")
243 {
244 events.push(...this.#applySummonEntity(event));
245 continue;
246 }
247 if (event.type === "entity-move")
248 { this.#applyMoveToDirectory(event); }
249 if (event.type === "entity-despawn")
250 { this.#forget(event.entityId); }
251 if (event.type === "skills-updated")
252 {
253 this.#applySkillsUpdated(event);
254 events.push(...this.#skillLevelUpEvents(event));
255 continue;
256 }
257 if (event.type === "spells-updated")
258 {
259 this.#applySpellsUpdated(event);
260 continue;
261 }
262 if (event.type === "inventory" && event.characterId)
263 {
264 this.#saveBagFromView(event.characterId, {
265 inventory: event.inventory,
266 equipment: event.equipment,
267 vault: event.vault,
268 vaultReserved: event.vaultReserved
269 });
270 }
271 if (event.type === "player-died")
272 {
273 events.push(...this.#applyPlayerDeath(event));
274 continue;
275 }
276 if (event.type === "mob-killed")
277 {
278 events.push(...this.#applyMobKilled(event));
279 continue;
280 }
281 if (event.type === "dialogue-walk-away")
282 {
283 const closed = this.quests?.closeDialogue(event.characterId, "walk-away");
284 events.push(...this.#mapQuestPrivateEvents(
285 closed?.events ?? [],
286 event.sessionId,
287 event.characterId
288 ));
289 continue;
290 }
291 this.#persistGroundEvent(event);
292 if (event.type !== "skills-updated")
293 { events.push(event); }
294 }
295 for (const request of result?.transferRequests ?? [])
296 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
297 }
298 for (const payload of remoteMelee)
299 { events.push(...this.#applyRemoteMelee(payload)); }
300 for (const payload of remoteRanged)
301 { events.push(...this.#applyRemoteRanged(payload)); }
302 if (transfers.length)
303 {
304 events.push(...this.#applyTransfers(transfers));
305 this.#recalculateActivation(now);
306 }
307 }
308
309 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
310 this.movementAccumulator += dt * movementHz;
311 while (this.movementAccumulator >= 1)
312 {
313 this.movementAccumulator -= 1;
314 this.movementTickCounter += 1;
315 const transfers = [];
316 for (const worker of this.workers)
317 {
318 const result = worker.call({ type: WorkerMessage.stepMovement, now });
319 for (const event of result?.events ?? [])
320 {
321 if (event.type === "entity-move")
322 { this.#applyMoveToDirectory(event); }
323 if (event.type === "skills-updated")
324 {
325 this.#applySkillsUpdated(event);
326 events.push(...this.#skillLevelUpEvents(event));
327 continue;
328 }
329 if (event.type === "spells-updated")
330 {
331 this.#applySpellsUpdated(event);
332 continue;
333 }
334 this.#persistGroundEvent(event);
335 if (event.type !== "skills-updated")
336 { events.push(event); }
337 }
338 for (const request of result?.transferRequests ?? [])
339 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
340 }
341 events.push(...this.#applyTransfers(transfers));
342 this.#recalculateActivation(now);
343 }
344
345 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
346 { events.push(...this.#stepSpawners()); }
347
348 if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)
349 { this.#stepSkullDecay(); }
350
351 if (this.courier)
352 { events.push(...this.courier.step(now, dt)); }
353 if (this.market)
354 { events.push(...this.market.step(now)); }
355
356 this.#syncGhosts();
357 events.push(...this.pendingPrivate.splice(0));
358 return { now, events, replication: this.drainReplication() };
359 }
360
361 drainReplication ()
362 {
363 return this.replication.splice(0);
364 }
365
366 worldTime (now = this.now)
367 {
368 const date = new Date(now);
369 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
370 return {
371 unixMs: now,
372 worldUnixMs: date.getTime(),
373 iso: date.toISOString(),
374 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600,
375 season: seasonIdAt(now)
376 };
377 }
378
379 spawnCharacter (sessionId, character)
380 {
381 this.despawnCharacter(character.character_id);
382 // Despawn may have just written the live tile; never trust a stale row snapshot.
383 const row = this.stateDb.getCharacter(character.character_id) ?? character;
384 let tileX = row.tile_x;
385 let tileY = row.tile_y;
386 let dimensionId = normalizeDimensionId(row.dimension_id ?? OVERWORLD_ID);
387 const gait = row.gait || character.gait || GAIT.walk;
388
389 // Soft-deleted / purged interiors eject to overworld spawn.
390 if (!this.#isDimensionUsable(dimensionId))
391 {
392 dimensionId = OVERWORLD_ID;
393 const spawn = this.findOpenSpawn();
394 if (!spawn)
395 {
396 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
397 error.userFacing = true;
398 throw error;
399 }
400 tileX = spawn.tileX;
401 tileY = spawn.tileY;
402 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
403 }
404
405 const preferred = this.#findResumeTile(tileX, tileY, 24, dimensionId);
406 if (!preferred)
407 {
408 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
409 error.userFacing = true;
410 throw error;
411 }
412 if (
413 preferred.tileX !== tileX
414 || preferred.tileY !== tileY
415 || normalizeDimensionId(preferred.dimensionId ?? dimensionId) !== dimensionId
416 )
417 {
418 tileX = preferred.tileX;
419 tileY = preferred.tileY;
420 dimensionId = normalizeDimensionId(preferred.dimensionId ?? dimensionId);
421 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
422 }
423
424 const bag = this.stateDb.getBag(character.character_id) ?? {
425 inventory: emptySlots(),
426 equipment: emptyEquipment(),
427 vault: [],
428 vaultReserved: []
429 };
430 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
431 const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells();
432 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
433 if (enforceMinimumSkillLevels(skills))
434 { this.stateDb.saveSkills(character.character_id, skills); }
435 const maxHealth = playerMaxHealth(skills);
436 const maxStamina = playerMaxStamina(skills);
437 const isDead = !!row.is_dead;
438 const savedHealth = row.health_current;
439 const currentHealth = isDead
440 ? 0
441 : savedHealth != null
442 ? Math.max(0, Math.min(maxHealth, savedHealth | 0))
443 : maxHealth;
444 const entityId = this.nextEntityId++;
445 const components = {
446 position: { tileX, tileY, dimensionId },
447 movement: { gait, walkCarry: 0 },
448 path: { tiles: [] },
449 appearance: {
450 sex: character.sex ?? row.sex,
451 firstName: character.first_name ?? row.first_name,
452 lastName: character.last_name ?? row.last_name,
453 ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character))
454 },
455 character: {
456 characterId: character.character_id ?? row.character_id,
457 accountId: character.account_id ?? row.account_id
458 },
459 networkIdentity: { sessionId },
460 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
461 inventory: { slots: bag.inventory ?? emptySlots() },
462 equipment: bag.equipment ?? emptyEquipment(),
463 vault: {
464 slots: bag.vault ?? [],
465 reserved: bag.vaultReserved ?? []
466 },
467 health: { current: currentHealth, max: maxHealth },
468 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
469 combat: { targetEntityId: null, nextSwingAt: 0 },
470 skills,
471 spells,
472 spellcasting: {
473 armedSpellId: null,
474 repeatSpellId: null,
475 repeatTargetEntityId: null,
476 nextCastAt: 0
477 },
478 };
479 if (isDead)
480 { components.dead = {}; }
481 this.#ensureCoverage(tileX, tileY, components.chunkLoader, dimensionId);
482 const workerId = this.#ownerOfTile(tileX, tileY, dimensionId);
483 const view = this.workers[workerId].call({
484 type: WorkerMessage.spawn,
485 entityId,
486 components
487 });
488 this.#remember(view, workerId);
489 this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);
490 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
491 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
492 this.#recalculateActivation(this.now);
493 this.#syncGhosts();
494 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
495 return entityId;
496 }
497
498 characterSkullValue (characterId, now = this.now)
499 {
500 const bounty = this.stateDb.getCharacterBounty(characterId);
501 const killCounter = this.stateDb.peekKillCounter(characterId, now);
502 return skullValue(bounty, killCounter);
503 }
504
505 refreshCharacterSkull (characterId)
506 {
507 const id = characterId | 0;
508 if (!id)
509 { return; }
510 const state = this.stateDb.getKillCounterState(id);
511 const elapsed = Math.max(0, this.now - (state.updatedAt | 0));
512 const decayed = decayKillCounter(state.killCounter, elapsed);
513 if (decayed.killCounter !== state.killCounter)
514 { this.stateDb.setKillCounter(id, decayed.killCounter, this.now); }
515 const value = this.characterSkullValue(id);
516 const entityId = this.characterEntities.get(id);
517 const record = entityId ? this.directory.get(entityId) : null;
518 if (!record)
519 { return; }
520 if ((record.skullValue | 0) === value)
521 { return; }
522 record.skullValue = value;
523 this.#queueReplication({
524 type: "entity-skull",
525 entityId,
526 skullValue: value,
527 tileX: record.tileX,
528 tileY: record.tileY
529 });
530 }
531
532 #attachSkullToRecord (entityId, characterId)
533 {
534 const record = this.directory.get(entityId);
535 if (!record)
536 { return; }
537 record.skullValue = this.characterSkullValue(characterId);
538 }
539
540 #stepSkullDecay ()
541 {
542 for (const characterId of this.characterEntities.keys())
543 {
544 const state = this.stateDb.getKillCounterState(characterId);
545 if (!(state.killCounter > 0))
546 { continue; }
547 this.refreshCharacterSkull(characterId);
548 }
549 }
550
551 isCharacterOnline (characterId)
552 {
553 return this.characterEntities.has(characterId);
554 }
555
556 reattachCharacterSession (characterId, sessionId)
557 {
558 const entityId = this.characterEntities.get(characterId | 0);
559 if (!entityId)
560 { return null; }
561 const record = this.directory.get(entityId);
562 if (!record)
563 { return null; }
564 const result = this.workers[record.workerId].call({
565 type: WorkerMessage.reattachSession,
566 characterId,
567 sessionId
568 });
569 if (!result?.ok)
570 { return null; }
571 this.market?.reattachSession?.(characterId, sessionId);
572 return entityId;
573 }
574
575 spawnEntity (components, options = {})
576 {
577 const entityId = options.entityId ?? this.nextEntityId++;
578 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
579 const position = components.position;
580 if (!position)
581 { throw new Error("spawnEntity requires position."); }
582 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
583 position.dimensionId = dimensionId;
584 if (options.requireResident)
585 {
586 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
587 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId))
588 { return null; }
589 const view = this.workers[workerId].call({
590 type: WorkerMessage.spawn,
591 entityId,
592 components
593 });
594 this.#remember(view, workerId);
595 if (components.appearance)
596 { this.#queueReplication(replicationSpawn(view)); }
597 this.#syncGhosts();
598 return entityId;
599 }
600 if (components.chunkLoader)
601 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); }
602 else
603 {
604 this.#ensureRegion(
605 tileToRegion(position.tileX),
606 tileToRegion(position.tileY),
607 null,
608 dimensionId
609 );
610 }
611 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
612 const view = this.workers[workerId].call({
613 type: WorkerMessage.spawn,
614 entityId,
615 components
616 });
617 this.#remember(view, workerId);
618 if (components.appearance)
619 { this.#queueReplication(replicationSpawn(view)); }
620 this.#recalculateActivation(this.now);
621 this.#syncGhosts();
622 return entityId;
623 }
624
625 despawnEntity (entityId)
626 {
627 const record = this.directory.get(entityId);
628 if (!record)
629 { return; }
630 const dropped = this.workers[record.workerId].call({
631 type: WorkerMessage.despawn,
632 entityId
633 });
634 if (dropped)
635 { this.#queueReplication(replicationDespawn(dropped)); }
636 this.#forget(entityId);
637 }
638
639 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
640 {
641 const loaders = this.#allLoaders();
642 const { chunkSim } = accumulateLoaderRefs(loaders);
643 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0;
644 }
645
646 updateCourierFlight (entityId, flightPatch, now = this.now)
647 {
648 const record = this.directory.get(entityId);
649 if (!record)
650 { return { despawned: true, entityId }; }
651 const tileX = Math.floor(flightPatch.x);
652 const tileY = Math.floor(flightPatch.y);
653 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
654 const owner = this.#ownerOfTile(tileX, tileY, dimensionId);
655 if (owner == null || owner !== record.workerId)
656 {
657 this.despawnEntity(entityId);
658 return { despawned: true, entityId };
659 }
660 const result = this.workers[owner].call({
661 type: WorkerMessage.updateFlight,
662 entityId,
663 flight: flightPatch,
664 now
665 });
666 if (result?.transferRequest)
667 {
668 const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);
669 this.#recalculateActivation(now);
670 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
671 if (move)
672 {
673 this.#applyMoveToDirectory(move);
674 return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };
675 }
676 this.despawnEntity(entityId);
677 return { despawned: true, entityId };
678 }
679 if (result?.event)
680 {
681 this.#applyMoveToDirectory(result.event);
682 return { event: result.event };
683 }
684 return null;
685 }
686
687 applyBag (entityId, bag)
688 {
689 const record = this.directory.get(entityId);
690 if (!record)
691 { return null; }
692 return this.workers[record.workerId].call({
693 type: WorkerMessage.applyBag,
694 entityId,
695 bag
696 });
697 }
698
699 /**
700 * Persist hair + patch live appearance; returns public view.
701 */
702 setCharacterHair (characterId, hair)
703 {
704 const row = this.stateDb.updateCharacterHair(characterId, hair);
705 const entityId = this.characterEntities.get(characterId);
706 if (!entityId)
707 { return { row, view: null }; }
708 const fields = appearanceHairFields({
709 sex: row.sex,
710 style: hair.style,
711 hue: hair.hue,
712 saturation: hair.saturation,
713 darkness: hair.darkness
714 });
715 const record = this.directory.get(entityId);
716 if (!record)
717 { return { row, view: null }; }
718 const view = this.workers[record.workerId].call({
719 type: WorkerMessage.applyAppearance,
720 entityId,
721 appearance: fields
722 });
723 if (view)
724 {
725 this.#remember(view, record.workerId);
726 this.#queueReplication(replicationAppearance(view));
727 }
728 return { row, view };
729 }
730
731 pushSkills (characterId, skills)
732 {
733 this.pendingPrivate.push({
734 type: "skills",
735 characterId,
736 skills
737 });
738 }
739
740 pushSpells (characterId, payload)
741 {
742 this.pendingPrivate.push({
743 type: "spells",
744 characterId,
745 ...payload
746 });
747 }
748
749 skillsOf (entityId)
750 {
751 const record = this.directory.get(entityId);
752 if (!record)
753 { return null; }
754 return this.workers[record.workerId].call({
755 type: WorkerMessage.inspectSkills,
756 entityId
757 });
758 }
759
760 spellsOf (entityId)
761 {
762 const record = this.directory.get(entityId);
763 if (!record)
764 { return null; }
765 return this.workers[record.workerId].call({
766 type: WorkerMessage.inspectSpells,
767 entityId
768 });
769 }
770
771 staminaOf (entityId)
772 {
773 const record = this.directory.get(entityId);
774 if (!record)
775 { return null; }
776 return this.workers[record.workerId].call({
777 type: WorkerMessage.inspectStamina,
778 entityId
779 });
780 }
781
782 pushInventory (characterId, bag)
783 {
784 this.pendingPrivate.push({
785 type: "inventory",
786 characterId,
787 inventory: bag.inventory,
788 equipment: bag.equipment,
789 vault: bag.vault,
790 vaultReserved: bag.vaultReserved
791 });
792 }
793
794 dispatchPigeon ({ characterId, destination, cargo })
795 {
796 const entityId = this.characterEntities.get(characterId);
797 const position = entityId ? this.positionOf(entityId) : null;
798 if (!position)
799 {
800 const error = new Error("Enter the world before sending a pigeon.");
801 error.userFacing = true;
802 throw error;
803 }
804 return this.courier.dispatchFromPlayer({
805 characterId,
806 originTileX: position.tileX,
807 originTileY: position.tileY,
808 destination,
809 cargo
810 });
811 }
812
813 /**
814 * Path an idle CE clerk to a staff-side station tile.
815 */
816 stationExchangeClerk (stationTileX, stationTileY)
817 {
818 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
819 if (owner == null)
820 { return { ok: false, reason: "unowned" }; }
821 return this.workers[owner].call({
822 type: WorkerMessage.stationExchangeClerk,
823 stationTileX,
824 stationTileY
825 });
826 }
827
828 /**
829 * When a player uses a marketplace counter, path idle CE clerks to the
830 * opposite side of each adjacent counter (staff side).
831 */
832 stationExchangeClerks (playerTileX, playerTileY)
833 {
834 const results = [];
835 for (const tile of this.market?.marketTiles ?? [])
836 {
837 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
838 { continue; }
839 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
840 { continue; }
841 const stationTileX = tile.tileX + (tile.tileX - playerTileX);
842 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
843 if (stationTileX === playerTileX && stationTileY === playerTileY)
844 { continue; }
845 results.push(this.stationExchangeClerk(stationTileX, stationTileY));
846 }
847 return results;
848 }
849
850 /** Release a CE clerk stationed at the given staff-side tile. */
851 releaseExchangeClerk (stationTileX, stationTileY)
852 {
853 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
854 if (owner == null)
855 { return { ok: false, reason: "unowned" }; }
856 return this.workers[owner].call({
857 type: WorkerMessage.releaseExchangeClerk,
858 stationTileX,
859 stationTileY
860 });
861 }
862
863 despawnCharacter (characterId)
864 {
865 this.market?.leaveExchangeStations?.(characterId);
866 const entityId = this.characterEntities.get(characterId);
867 if (!entityId)
868 { return; }
869 const record = this.directory.get(entityId);
870 if (!record)
871 {
872 this.characterEntities.delete(characterId);
873 return;
874 }
875 this.#saveBag(entityId, record.workerId);
876 const dropped = this.workers[record.workerId].call({
877 type: WorkerMessage.despawnCharacter,
878 characterId
879 });
880 if (dropped)
881 {
882 this.stateDb.saveCharacterPosition(
883 characterId,
884 dropped.tileX,
885 dropped.tileY,
886 dropped.gait ?? GAIT.walk,
887 dropped.dimensionId ?? OVERWORLD_ID
888 );
889 if (dropped.health != null)
890 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
891 this.#queueReplication(replicationDespawn(dropped));
892 }
893 this.#forget(entityId);
894 this.#recalculateActivation(this.now);
895 this.#syncGhosts();
896 }
897
898 entityForCharacter (characterId)
899 {
900 return this.characterEntities.get(characterId) ?? null;
901 }
902
903 entityRecord (entityId)
904 {
905 const record = this.directory.get(entityId);
906 return record ? { ...record } : null;
907 }
908
909 positionOf (entityId)
910 {
911 const record = this.directory.get(entityId);
912 return record
913 ? {
914 tileX: record.tileX,
915 tileY: record.tileY,
916 dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID)
917 }
918 : null;
919 }
920
921 bagOf (entityId)
922 {
923 const record = this.directory.get(entityId);
924 if (!record)
925 { return null; }
926 return this.workers[record.workerId].call({
927 type: WorkerMessage.inspectBag,
928 entityId
929 });
930 }
931
932 snapshotFor (entityId)
933 {
934 const record = this.directory.get(entityId);
935 if (!record)
936 { return []; }
937 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
938 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
939 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId));
940 }
941
942 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
943 snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS)
944 {
945 const record = this.directory.get(entityId);
946 if (!record)
947 { return []; }
948 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
949 const centerChunkX = tileToChunk(record.tileX);
950 const centerChunkY = tileToChunk(record.tileY);
951 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
952 const entityKeys = new Set(
953 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
954 .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId))
955 );
956 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
957 .map((coord) =>
958 {
959 const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId);
960 const staticOnly = !entityKeys.has(key);
961 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId);
962 return { ...snapshot, staticOnly };
963 });
964 }
965
966 snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
967 {
968 const dim = normalizeDimensionId(dimensionId);
969 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim));
970 if (owner == null)
971 { return this.#syntheticSnapshot(chunkX, chunkY, dim); }
972 return this.workers[owner].call({
973 type: WorkerMessage.snapshotChunk,
974 chunkX,
975 chunkY,
976 dimensionId: dim,
977 staticOnly: !!staticOnly
978 });
979 }
980
981 findOpenSpawn ()
982 {
983 const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID);
984 for (const coord of coords)
985 {
986 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID);
987 if (!data.open)
988 { continue; }
989 for (let localY = 0; localY < CHUNK_SIZE; localY++)
990 {
991 for (let localX = 0; localX < CHUNK_SIZE; localX++)
992 {
993 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
994 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
995 if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID))
996 { return { tileX, tileY, dimensionId: OVERWORLD_ID }; }
997 }
998 }
999 }
1000 return null;
1001 }
1002
1003 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
1004 #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID)
1005 {
1006 const dim = normalizeDimensionId(dimensionId);
1007 return this.#findNearbyEnterable(tileX, tileY, radius, dim)
1008 ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn());
1009 }
1010
1011 #isDimensionUsable (dimensionId)
1012 {
1013 const dim = normalizeDimensionId(dimensionId);
1014 if (dim === OVERWORLD_ID)
1015 { return true; }
1016 const record = this.getDimensionRecord(dim);
1017 if (!record)
1018 { return false; }
1019 if (record.deletedAt != null)
1020 { return false; }
1021 if (record.purgeAfter != null && record.purgeAfter <= this.now)
1022 { return false; }
1023 return true;
1024 }
1025
1026 #loadDimensionsCache ()
1027 {
1028 const map = new Map();
1029 for (const dim of this.worldDb.listDimensions(this.activeRevisionId))
1030 { map.set(dim.dimensionId, dim); }
1031 if (!map.has(OVERWORLD_ID))
1032 {
1033 map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, {
1034 defaultGroundTypeId: this.settings.defaultGroundTypeId
1035 }));
1036 }
1037 return map;
1038 }
1039
1040 getDimensionRecord (dimensionId)
1041 {
1042 const dim = normalizeDimensionId(dimensionId);
1043 return this.dimensions?.get(dim)
1044 ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim)
1045 ?? (dim === OVERWORLD_ID
1046 ? defaultDimensionRecord(OVERWORLD_ID, {
1047 defaultGroundTypeId: this.settings.defaultGroundTypeId
1048 })
1049 : null);
1050 }
1051
1052 listDimensionRecords ()
1053 {
1054 return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))];
1055 }
1056
1057 #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID)
1058 {
1059 const dim = normalizeDimensionId(dimensionId);
1060 for (let radius = 0; radius <= maxRadius; radius++)
1061 {
1062 for (let dy = -radius; dy <= radius; dy++)
1063 {
1064 for (let dx = -radius; dx <= radius; dx++)
1065 {
1066 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1067 { continue; }
1068 const tileX = originX + dx;
1069 const tileY = originY + dy;
1070 if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim))
1071 { return { tileX, tileY, dimensionId: dim }; }
1072 }
1073 }
1074 }
1075 return null;
1076 }
1077
1078 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
1079 {
1080 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1081 if (!data.open)
1082 { return false; }
1083 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1084 }
1085
1086 debugWorld ()
1087 {
1088 const loaders = this.#allLoaders();
1089 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
1090 const simulatingChunks = [...chunkSim.entries()]
1091 .filter(([, count]) => count > 0)
1092 .map(([key]) => key)
1093 .sort();
1094 return {
1095 tickIndex: this.tickIndex,
1096 workerCount: this.workers.length,
1097 workerMode: this.workerMode,
1098 simulatingChunks,
1099 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
1100 ...parseRegionKey(key),
1101 workerId,
1102 state: REGION_RUNTIME_STATE.resident,
1103 refs: regionRes.get(key) ?? 0,
1104 graceUntil: this.regionGraceUntil.get(key) ?? null
1105 })),
1106 entities: [...this.directory.values()].map((entity) => ({
1107 entityId: entity.entityId,
1108 workerId: entity.workerId,
1109 tileX: entity.tileX,
1110 tileY: entity.tileY,
1111 characterId: entity.characterId
1112 }))
1113 };
1114 }
1115
1116 async shutdown ()
1117 {
1118 for (const characterId of [...this.characterEntities.keys()])
1119 { this.despawnCharacter(characterId); }
1120 this.forceUnloadAll();
1121 await Promise.all(this.workers.map((worker) => worker.terminate()));
1122 }
1123
1124 forceUnloadAll ()
1125 {
1126 for (const key of [...this.regionOwner.keys()])
1127 {
1128 const { regionX, regionY } = parseRegionKey(key);
1129 this.#unloadRegion(regionX, regionY);
1130 }
1131 }
1132
1133 #configureWorkers ()
1134 {
1135 for (const worker of this.workers)
1136 {
1137 worker.call({
1138 type: WorkerMessage.configure,
1139 settings: this.settings,
1140 activeRevisionId: this.activeRevisionId
1141 });
1142 }
1143 }
1144
1145 #routeCommand (item)
1146 {
1147 if (item.command.type === "respawn")
1148 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
1149 if (item.command.type === "enter-doorway")
1150 {
1151 return this.#relocateCharacterThroughDoorway(
1152 item.sessionId,
1153 item.command.characterId,
1154 item.command.tileX,
1155 item.command.tileY
1156 );
1157 }
1158 if (
1159 item.command.type === "open-market"
1160 || item.command.type === "place-market-sell"
1161 || item.command.type === "place-market-buy"
1162 || item.command.type === "cancel-market-order"
1163 || item.command.type === "close-market"
1164 )
1165 {
1166 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1167 return result?.events ?? [];
1168 }
1169 if (
1170 item.command.type === "open-bounty"
1171 || item.command.type === "raise-bounty"
1172 || item.command.type === "get-character-bounty"
1173 || item.command.type === "close-bounty"
1174 )
1175 {
1176 const result = this.bounty.handleCommand(item.sessionId, item.command);
1177 return result?.events ?? [];
1178 }
1179 if (
1180 item.command.type === "open-barber"
1181 || item.command.type === "set-hair"
1182 || item.command.type === "close-barber"
1183 )
1184 {
1185 const result = this.barber.handleCommand(item.sessionId, item.command);
1186 return result?.events ?? [];
1187 }
1188 if (
1189 item.command.type === "dialogue-choose"
1190 || item.command.type === "dialogue-advance"
1191 || item.command.type === "close-dialogue"
1192 || item.command.type === "request-quests"
1193 )
1194 { return this.#handleQuestCommand(item); }
1195 const entityId = this.characterEntities.get(item.command.characterId);
1196 const record = entityId ? this.directory.get(entityId) : null;
1197 if (!record)
1198 {
1199 const error = new Error("Character is not in the world.");
1200 error.userFacing = true;
1201 throw error;
1202 }
1203 if (item.command.type === "drop-item" && item.command.groundItemId == null)
1204 { item.command.groundItemId = this.nextGroundItemId++; }
1205 if (item.command.type === "attack")
1206 {
1207 const targetRecord = this.directory.get(item.command.targetEntityId);
1208 if (!targetRecord)
1209 {
1210 const error = new Error("Target is not here.");
1211 error.userFacing = true;
1212 throw error;
1213 }
1214 const events = this.#finishRoutedCommand(item, record);
1215 if (targetRecord.workerId !== record.workerId)
1216 {
1217 this.workers[targetRecord.workerId].call({
1218 type: WorkerMessage.remoteCombatEngage,
1219 attackerEntityId: record.entityId,
1220 targetEntityId: item.command.targetEntityId,
1221 now: item.receivedAt ?? this.now
1222 });
1223 }
1224 return events;
1225 }
1226 return this.#finishRoutedCommand(item, record);
1227 }
1228
1229 #finishRoutedCommand (item, record)
1230 {
1231 const result = this.workers[record.workerId].call({
1232 type: WorkerMessage.command,
1233 sessionId: item.sessionId,
1234 command: item.command,
1235 now: item.receivedAt ?? this.now
1236 });
1237 const view = this.workers[record.workerId].call({
1238 type: WorkerMessage.inspect,
1239 entityId: record.entityId
1240 });
1241 if (view)
1242 { this.#remember(view, record.workerId); }
1243 if (result?.private)
1244 { this.#saveBagFromView(item.command.characterId, result.private); }
1245 if (result?.appearanceChanged && view)
1246 { this.#queueReplication(replicationAppearance(view)); }
1247 if (result?.remainder)
1248 {
1249 this.stateDb.saveInheritance(
1250 this.stateDb.getCharacter(item.command.characterId).account_id,
1251 { slots: result.remainder }
1252 );
1253 }
1254 for (const event of result?.events ?? [])
1255 { this.#persistGroundEvent(event); }
1256 const events = [];
1257 for (const event of result?.events ?? [])
1258 {
1259 if (event.type === "skills-updated")
1260 {
1261 this.#applySkillsUpdated(event);
1262 events.push(...this.#skillLevelUpEvents(event));
1263 continue;
1264 }
1265 if (event.type === "spells-updated")
1266 {
1267 this.#applySpellsUpdated(event);
1268 continue;
1269 }
1270 if (event.type === "open-dialogue")
1271 {
1272 events.push(...this.#handleOpenDialogue(event));
1273 continue;
1274 }
1275 events.push(event);
1276 }
1277 if (item.command.type === "attack" && item.command.targetEntityId != null)
1278 {
1279 events.push(...this.#mapQuestPrivateEvents(
1280 this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []
1281 ));
1282 }
1283 if (result?.private)
1284 {
1285 events.push({
1286 type: "inventory",
1287 sessionId: item.sessionId,
1288 bank: !!result.bank,
1289 cauldron: result.cauldron,
1290 cauldronState: result.cauldronState ?? null,
1291 alchemyResult: result.alchemyResult ?? null,
1292 dyeConfirm: result.dyeConfirm ?? null,
1293 ...result.private
1294 });
1295 }
1296 if (result?.statusEffectsChanged && view)
1297 {
1298 events.push({
1299 type: "status-effects",
1300 sessionId: item.sessionId,
1301 characterId: view.characterId ?? item.command.characterId,
1302 effects: view.statusEffects ?? [],
1303 blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind")
1304 });
1305 }
1306 if (result?.healthChanged && view)
1307 {
1308 events.push({
1309 type: "entity-health",
1310 entityId: view.entityId,
1311 characterId: view.characterId ?? item.command.characterId,
1312 health: view.health,
1313 maxHealth: view.maxHealth,
1314 tileX: view.tileX,
1315 tileY: view.tileY
1316 });
1317 }
1318 return events;
1319 }
1320
1321 #applyRemoteMelee (payload)
1322 {
1323 const targetRecord = this.directory.get(payload.targetId);
1324 if (!targetRecord)
1325 { return []; }
1326 const result = this.workers[targetRecord.workerId].call({
1327 ...payload,
1328 type: WorkerMessage.applyRemoteMelee
1329 });
1330 const events = [];
1331 for (const event of result?.events ?? [])
1332 {
1333 if (event.type === "entity-despawn")
1334 { this.#forget(event.entityId); }
1335 if (event.type === "skills-updated")
1336 {
1337 this.#applySkillsUpdated(event);
1338 events.push(...this.#skillLevelUpEvents(event));
1339 continue;
1340 }
1341 if (event.type === "spells-updated")
1342 {
1343 this.#applySpellsUpdated(event);
1344 continue;
1345 }
1346 if (event.type === "player-died")
1347 {
1348 events.push(...this.#applyPlayerDeath(event));
1349 continue;
1350 }
1351 if (event.type === "mob-killed")
1352 {
1353 events.push(...this.#applyMobKilled(event));
1354 continue;
1355 }
1356 this.#persistGroundEvent(event);
1357 if (event.type !== "skills-updated")
1358 { events.push(event); }
1359 }
1360 for (const forward of result?.forwards ?? [])
1361 {
1362 if (forward.type !== "forward-combat-xp")
1363 { continue; }
1364 const attackerRecord = this.directory.get(forward.entityId);
1365 if (!attackerRecord)
1366 { continue; }
1367 const xpResult = this.workers[attackerRecord.workerId].call({
1368 type: WorkerMessage.applyCombatHitXp,
1369 entityId: forward.entityId,
1370 profile: forward.profile,
1371 damage: forward.damage
1372 });
1373 for (const xpEvent of xpResult?.events ?? [])
1374 {
1375 if (xpEvent.type === "skills-updated")
1376 {
1377 this.#applySkillsUpdated(xpEvent);
1378 events.push(...this.#skillLevelUpEvents(xpEvent));
1379 continue;
1380 }
1381 events.push(xpEvent);
1382 }
1383 }
1384 return events;
1385 }
1386
1387 #applyRemoteRanged (payload)
1388 {
1389 const targetRecord = this.directory.get(payload.targetId);
1390 if (!targetRecord)
1391 { return []; }
1392 const result = this.workers[targetRecord.workerId].call({
1393 ...payload,
1394 type: WorkerMessage.applyRemoteRanged
1395 });
1396 const events = [];
1397 for (const event of result?.events ?? [])
1398 {
1399 if (event.type === "entity-despawn")
1400 { this.#forget(event.entityId); }
1401 if (event.type === "skills-updated")
1402 {
1403 this.#applySkillsUpdated(event);
1404 events.push(...this.#skillLevelUpEvents(event));
1405 continue;
1406 }
1407 if (event.type === "spells-updated")
1408 {
1409 this.#applySpellsUpdated(event);
1410 continue;
1411 }
1412 if (event.type === "player-died")
1413 {
1414 events.push(...this.#applyPlayerDeath(event));
1415 continue;
1416 }
1417 if (event.type === "mob-killed")
1418 {
1419 events.push(...this.#applyMobKilled(event));
1420 continue;
1421 }
1422 this.#persistGroundEvent(event);
1423 if (event.type !== "skills-updated")
1424 { events.push(event); }
1425 }
1426 for (const forward of result?.forwards ?? [])
1427 {
1428 if (forward.type !== "forward-combat-xp")
1429 { continue; }
1430 const attackerRecord = this.directory.get(forward.entityId);
1431 if (!attackerRecord)
1432 { continue; }
1433 const xpResult = this.workers[attackerRecord.workerId].call({
1434 type: WorkerMessage.applyCombatHitXp,
1435 entityId: forward.entityId,
1436 profile: forward.profile,
1437 damage: forward.damage
1438 });
1439 for (const xpEvent of xpResult?.events ?? [])
1440 {
1441 if (xpEvent.type === "skills-updated")
1442 {
1443 this.#applySkillsUpdated(xpEvent);
1444 events.push(...this.#skillLevelUpEvents(xpEvent));
1445 continue;
1446 }
1447 events.push(xpEvent);
1448 }
1449 }
1450 return events;
1451 }
1452
1453 #handleQuestCommand (item)
1454 {
1455 const characterId = item.command.characterId | 0;
1456 const sessionId = item.sessionId;
1457 if (!this.quests)
1458 { return []; }
1459 if (item.command.type === "request-quests")
1460 {
1461 const snap = this.quests.questSnapshot(characterId);
1462 return [{ type: "quests-snapshot", sessionId, characterId, ...snap }];
1463 }
1464 if (item.command.type === "close-dialogue")
1465 {
1466 const closed = this.quests.closeDialogue(characterId, "client");
1467 return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId);
1468 }
1469 if (item.command.type === "dialogue-choose")
1470 {
1471 const result = this.quests.chooseDialogue(characterId, item.command.trigger);
1472 if (!result.ok)
1473 {
1474 const error = new Error(result.error || "Choice failed.");
1475 error.userFacing = true;
1476 throw error;
1477 }
1478 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1479 }
1480 if (item.command.type === "dialogue-advance")
1481 {
1482 const result = this.quests.advanceDialogue(characterId);
1483 if (!result.ok)
1484 {
1485 const error = new Error(result.error || "Cannot advance.");
1486 error.userFacing = true;
1487 throw error;
1488 }
1489 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1490 }
1491 return [];
1492 }
1493
1494 #handleOpenDialogue (event)
1495 {
1496 const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId);
1497 if (!result.ok)
1498 {
1499 return [{
1500 type: "toast",
1501 characterId: event.characterId,
1502 sessionId: event.sessionId,
1503 message: result.error || "Nothing to say."
1504 }];
1505 }
1506 this.#pinDialogueNpc(event.entityId, event.characterId);
1507 return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId);
1508 }
1509
1510 #pinDialogueNpc (entityId, characterId)
1511 {
1512 const record = this.directory.get(entityId | 0);
1513 if (!record)
1514 { return; }
1515 this.workers[record.workerId]?.call?.({
1516 type: WorkerMessage.pinDialogue,
1517 entityId: entityId | 0,
1518 characterId: characterId | 0
1519 });
1520 }
1521
1522 #unpinDialogueNpc (entityId, characterId)
1523 {
1524 const record = this.directory.get(entityId | 0);
1525 if (!record)
1526 { return; }
1527 this.workers[record.workerId]?.call?.({
1528 type: WorkerMessage.unpinDialogue,
1529 entityId: entityId | 0,
1530 characterId: characterId | 0
1531 });
1532 }
1533
1534 #mapQuestPrivateEvents (events, sessionId = null, characterId = null)
1535 {
1536 const out = [];
1537 let needSnapshot = false;
1538 for (const event of events ?? [])
1539 {
1540 const cid = event.characterId ?? characterId;
1541 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1542 if (event.type === "dialogueStep")
1543 {
1544 out.push({
1545 type: "dialogue-step",
1546 sessionId: sid,
1547 characterId: cid,
1548 dialogueId: event.dialogueId,
1549 stepId: event.stepId,
1550 label: event.label,
1551 npcEntityId: event.npcEntityId,
1552 lines: event.lines
1553 });
1554 }
1555 else if (event.type === "dialogueChoices")
1556 {
1557 out.push({
1558 type: "dialogue-choices",
1559 sessionId: sid,
1560 characterId: cid,
1561 dialogueId: event.dialogueId,
1562 stepId: event.stepId,
1563 npcEntityId: event.npcEntityId,
1564 triggers: event.triggers
1565 });
1566 }
1567 else if (event.type === "dialogueClose")
1568 {
1569 if (event.npcEntityId != null && cid != null)
1570 { this.#unpinDialogueNpc(event.npcEntityId, cid); }
1571 out.push({
1572 type: "dialogue-close",
1573 sessionId: sid,
1574 characterId: cid,
1575 reason: event.reason
1576 });
1577 }
1578 else if (event.type === "questStepComplete")
1579 {
1580 out.push({
1581 type: "quest-step-complete",
1582 sessionId: sid,
1583 characterId: cid,
1584 questId: event.questId,
1585 title: event.title
1586 });
1587 needSnapshot = true;
1588 }
1589 else if (event.type === "questsDirty")
1590 { needSnapshot = true; }
1591 else if (event.type === "inventoryDirty" && cid != null)
1592 {
1593 const onlineId = this.characterEntities.get(cid | 0);
1594 if (onlineId)
1595 {
1596 const live = this.bagOf(onlineId);
1597 if (live)
1598 { this.pushInventory(cid, live); }
1599 }
1600 }
1601 }
1602 if (needSnapshot && characterId != null)
1603 {
1604 const snap = this.quests.questSnapshot(characterId);
1605 out.push({
1606 type: "quests-snapshot",
1607 sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
1608 characterId,
1609 ...snap
1610 });
1611 }
1612 return out;
1613 }
1614
1615 #sessionIdForCharacter (characterId)
1616 {
1617 const entityId = this.characterEntities.get(characterId | 0);
1618 const record = entityId != null ? this.directory.get(entityId) : null;
1619 return record?.sessionId ?? null;
1620 }
1621
1622 #applyMobKilled (event)
1623 {
1624 const out = [event];
1625 const attackerRecord = this.directory.get(event.attackerId);
1626 const killerCharacterId = attackerRecord?.characterId ?? null;
1627 const killerPos = attackerRecord
1628 ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
1629 : null;
1630 if (killerCharacterId && this.quests)
1631 {
1632 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
1633 mobTypeId: event.mobTypeId,
1634 spawnerId: event.spawnerId
1635 })));
1636 }
1637 out.push(...this.#mapQuestPrivateEvents(
1638 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
1639 ));
1640 let bountyAwarded = 0;
1641 if (killerCharacterId && (event.bounty | 0) > 0)
1642 {
1643 bountyAwarded = event.bounty | 0;
1644 const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1645 this.refreshCharacterSkull(killerCharacterId);
1646 out.push({
1647 type: "toast",
1648 characterId: killerCharacterId,
1649 message: `Bounty +${bountyAwarded} (total ${total})`
1650 });
1651 }
1652
1653 if (killerCharacterId && killerPos)
1654 {
1655 if (bountyAwarded > 0)
1656 { this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); }
1657 if (event.townGuard)
1658 { this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); }
1659 }
1660 return out;
1661 }
1662
1663 /**
1664 * Send up to `count` town guards at the killer. Prefer idle guards.
1665 * When `spawnerId` is set, only that spawner's guards are used.
1666 */
1667 #dispatchTownGuards (targetEntityId, killerPos, spawnerId, count)
1668 {
1669 const want = Math.max(0, count | 0);
1670 if (want <= 0 || targetEntityId == null || !killerPos)
1671 { return; }
1672 const candidates = [];
1673 for (const worker of this.workers)
1674 {
1675 const result = worker.call({
1676 type: WorkerMessage.listTownGuardsNear,
1677 tileX: killerPos.tileX,
1678 tileY: killerPos.tileY,
1679 spawnerId,
1680 limit: 32
1681 });
1682 for (const guard of result?.guards ?? [])
1683 { candidates.push(guard); }
1684 }
1685 candidates.sort((a, b) => Number(a.busy) - Number(b.busy));
1686 let sent = 0;
1687 for (const guard of candidates)
1688 {
1689 if (sent >= want)
1690 { break; }
1691 if (guard.entityId === targetEntityId)
1692 { continue; }
1693 const record = this.directory.get(guard.entityId);
1694 if (!record)
1695 { continue; }
1696 this.workers[record.workerId].call({
1697 type: WorkerMessage.engageTarget,
1698 attackerEntityId: guard.entityId,
1699 targetEntityId,
1700 now: this.now
1701 });
1702 sent += 1;
1703 }
1704 }
1705
1706 #applyPlayerDeath (event)
1707 {
1708 const record = this.directory.get(event.entityId);
1709 if (!record)
1710 { return [event]; }
1711 this.stateDb.setCharacterDead(event.characterId, true);
1712 this.stateDb.saveCharacterPosition(
1713 event.characterId,
1714 event.tileX,
1715 event.tileY,
1716 record.gait ?? GAIT.walk,
1717 record.dimensionId ?? OVERWORLD_ID
1718 );
1719 this.bounty?.settleKill(
1720 event.characterId,
1721 event.attackerId,
1722 event.tileX,
1723 event.tileY
1724 );
1725 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1726 const killerCharacterId = attackerRecord?.characterId | 0;
1727 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
1728 {
1729 this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now);
1730 this.refreshCharacterSkull(killerCharacterId);
1731 }
1732 this.refreshCharacterSkull(event.characterId);
1733 for (const worker of this.workers)
1734 {
1735 worker.call({
1736 type: WorkerMessage.clearCombat,
1737 entityId: event.entityId,
1738 targetEntityId: event.entityId
1739 });
1740 }
1741 const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()
1742 || "someone";
1743 const killerName = attackerRecord?.appearance
1744 ? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()
1745 || attackerRecord.appearance.displayName
1746 || "someone")
1747 : "someone";
1748 const corpseOrigin = lootOrigin(victimName, killerName);
1749 const result = this.workers[record.workerId].call({
1750 type: WorkerMessage.spawnCorpseDrops,
1751 characterId: event.characterId,
1752 tileX: event.tileX,
1753 tileY: event.tileY,
1754 now: this.now,
1755 dropCarriedCoins: true,
1756 coinGroundItemId: this.nextGroundItemId++,
1757 drops: [
1758 {
1759 groundItemId: this.nextGroundItemId++,
1760 stack: attachOrigins({
1761 itemId: ItemId.bones,
1762 quantity: 1,
1763 origins: [{ origin: corpseOrigin, quantity: 1 }]
1764 })
1765 },
1766 {
1767 groundItemId: this.nextGroundItemId++,
1768 stack: attachOrigins({
1769 itemId: ItemId.skull,
1770 quantity: 1,
1771 origins: [{ origin: corpseOrigin, quantity: 1 }]
1772 })
1773 }
1774 ]
1775 });
1776 const events = [event];
1777 for (const dropEvent of result?.events ?? [])
1778 {
1779 this.#persistGroundEvent(dropEvent);
1780 events.push(dropEvent);
1781 }
1782 if (result?.private)
1783 {
1784 this.#saveBagFromView(event.characterId, result.private);
1785 if (event.sessionId != null)
1786 {
1787 events.push({
1788 type: "inventory",
1789 sessionId: event.sessionId,
1790 ...result.private
1791 });
1792 }
1793 }
1794 return events;
1795 }
1796
1797 #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY)
1798 {
1799 const entityId = this.characterEntities.get(characterId);
1800 const record = entityId ? this.directory.get(entityId) : null;
1801 if (!record)
1802 {
1803 const error = new Error("Character is not in the world.");
1804 error.userFacing = true;
1805 throw error;
1806 }
1807 const tileX = doorwayTileX | 0;
1808 const tileY = doorwayTileY | 0;
1809 if (chebyshev(record.tileX, record.tileY, tileX, tileY) > 1)
1810 {
1811 const error = new Error("You are too far from that doorway.");
1812 error.userFacing = true;
1813 throw error;
1814 }
1815 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1816 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId);
1817 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
1818 if (block?.typeId !== BlockType.doorway)
1819 {
1820 const error = new Error("There is no doorway there.");
1821 error.userFacing = true;
1822 throw error;
1823 }
1824 const config = block.config && typeof block.config === "object" ? block.config : null;
1825 const targetRaw = config?.targetDimensionId;
1826 if (targetRaw == null || String(targetRaw).trim() === "")
1827 {
1828 const error = new Error("That doorway leads nowhere.");
1829 error.userFacing = true;
1830 throw error;
1831 }
1832 const targetDimensionId = normalizeDimensionId(targetRaw);
1833 const destTileX = Number(config.tileX);
1834 const destTileY = Number(config.tileY);
1835 if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY))
1836 {
1837 const error = new Error("That doorway leads nowhere.");
1838 error.userFacing = true;
1839 throw error;
1840 }
1841 const destX = destTileX | 0;
1842 const destY = destTileY | 0;
1843 if (!this.#isDimensionUsable(targetDimensionId))
1844 {
1845 const error = new Error("That place is no longer reachable.");
1846 error.userFacing = true;
1847 throw error;
1848 }
1849 if (!this.isEnterable(destX, destY, targetDimensionId))
1850 {
1851 const error = new Error("The other side is blocked.");
1852 error.userFacing = true;
1853 throw error;
1854 }
1855
1856 const events = [];
1857 if (this.quests)
1858 {
1859 const closed = this.quests.closeDialogue(characterId, "doorway");
1860 if (closed?.events?.length)
1861 { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); }
1862 }
1863
1864 const loader = { ...DEFAULT_CHUNK_LOADER };
1865 this.#ensureCoverage(destX, destY, loader, targetDimensionId);
1866 const result = this.workers[record.workerId].call({
1867 type: WorkerMessage.relocateEntity,
1868 entityId,
1869 tileX: destX,
1870 tileY: destY,
1871 dimensionId: targetDimensionId
1872 });
1873 if (!result?.accepted)
1874 {
1875 const error = new Error("Could not enter that doorway.");
1876 error.userFacing = true;
1877 throw error;
1878 }
1879 let moveEvents = [];
1880 if (result.transferRequest)
1881 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1882 else if (result.event)
1883 {
1884 this.#applyMoveToDirectory(result.event);
1885 moveEvents = [result.event];
1886 const view = this.workers[record.workerId].call({
1887 type: WorkerMessage.inspect,
1888 entityId
1889 });
1890 if (view)
1891 { this.#remember(view, record.workerId); }
1892 }
1893 if (!moveEvents.length)
1894 {
1895 const error = new Error("Could not enter that doorway.");
1896 error.userFacing = true;
1897 throw error;
1898 }
1899 this.stateDb.saveCharacterPosition(
1900 characterId,
1901 destX,
1902 destY,
1903 record.gait ?? GAIT.walk,
1904 targetDimensionId
1905 );
1906 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
1907 this.#recalculateActivation(this.now);
1908 this.#syncGhosts();
1909 const dimRecord = this.getDimensionRecord(targetDimensionId);
1910 events.push(...moveEvents, {
1911 type: "dimension-changed",
1912 sessionId,
1913 characterId,
1914 entityId,
1915 dimensionId: targetDimensionId,
1916 tileX: destX,
1917 tileY: destY,
1918 lightingMode: dimRecord?.lightingMode ?? "dayNight",
1919 seasonMode: dimRecord?.seasonMode ?? "auto"
1920 });
1921 return events;
1922 }
1923
1924 #respawnCharacter (sessionId, characterId)
1925 {
1926 const row = this.stateDb.getCharacter(characterId);
1927 if (!row?.is_dead)
1928 {
1929 const error = new Error("You are not dead.");
1930 error.userFacing = true;
1931 throw error;
1932 }
1933 const entityId = this.characterEntities.get(characterId);
1934 const record = entityId ? this.directory.get(entityId) : null;
1935 if (!record)
1936 {
1937 const error = new Error("Character is not in the world.");
1938 error.userFacing = true;
1939 throw error;
1940 }
1941 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
1942 if (!destination)
1943 {
1944 const error = new Error("No open tile is available for respawn.");
1945 error.userFacing = true;
1946 throw error;
1947 }
1948 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
1949 const loader = { ...DEFAULT_CHUNK_LOADER };
1950 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID);
1951 const result = this.workers[record.workerId].call({
1952 type: WorkerMessage.applyRespawn,
1953 entityId,
1954 sessionId,
1955 tileX: destination.tileX,
1956 tileY: destination.tileY,
1957 maxHealth: playerMaxHealth(skills),
1958 maxStamina: playerMaxStamina(skills)
1959 });
1960 if (!result?.accepted)
1961 {
1962 const error = new Error("That respawn tile is no longer available.");
1963 error.userFacing = true;
1964 throw error;
1965 }
1966 let moveEvents = [];
1967 if (result.transferRequest)
1968 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1969 else if (result.event)
1970 {
1971 this.#applyMoveToDirectory(result.event);
1972 moveEvents = [result.event];
1973 const view = this.workers[record.workerId].call({
1974 type: WorkerMessage.inspect,
1975 entityId
1976 });
1977 if (view)
1978 { this.#remember(view, record.workerId); }
1979 }
1980 if (!moveEvents.length)
1981 {
1982 const error = new Error("Respawn transfer failed.");
1983 error.userFacing = true;
1984 throw error;
1985 }
1986 this.stateDb.setCharacterDead(characterId, false);
1987 const respawnHealth = playerMaxHealth(skills);
1988 this.stateDb.saveCharacterHealth(characterId, respawnHealth);
1989 this.stateDb.saveCharacterPosition(
1990 characterId,
1991 destination.tileX,
1992 destination.tileY,
1993 record.gait ?? GAIT.walk,
1994 destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
1995 );
1996 this.#recalculateActivation(this.now);
1997 this.#syncGhosts();
1998 return [
1999 ...moveEvents,
2000 {
2001 type: "player-respawned",
2002 entityId,
2003 characterId,
2004 sessionId,
2005 tileX: destination.tileX,
2006 tileY: destination.tileY,
2007 health: playerMaxHealth(skills),
2008 maxHealth: playerMaxHealth(skills),
2009 stamina: playerMaxStamina(skills),
2010 maxStamina: playerMaxStamina(skills)
2011 }
2012 ];
2013 }
2014
2015 #refreshAltarIndex ()
2016 {
2017 const altars = [];
2018 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
2019 {
2020 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
2021 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim);
2022 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2023 {
2024 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2025 {
2026 const block = data.blocks[localY * CHUNK_SIZE + localX];
2027 if (block?.typeId !== BlockType.churchAltar)
2028 { continue; }
2029 altars.push({
2030 tileX: coord.chunk_x * CHUNK_SIZE + localX,
2031 tileY: coord.chunk_y * CHUNK_SIZE + localY,
2032 dimensionId: dim
2033 });
2034 }
2035 }
2036 }
2037 this.altarTiles = altars;
2038 }
2039
2040 #findRespawnDestination (originX, originY, entityId)
2041 {
2042 const record = this.directory.get(entityId);
2043 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2044 const ordered = [...this.altarTiles].sort((left, right) =>
2045 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2046 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2047 );
2048 for (const altar of ordered)
2049 {
2050 const adjacent = [];
2051 for (let dy = -1; dy <= 1; dy++)
2052 {
2053 for (let dx = -1; dx <= 1; dx++)
2054 {
2055 if (dx === 0 && dy === 0)
2056 { continue; }
2057 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId });
2058 }
2059 }
2060 adjacent.sort((left, right) =>
2061 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2062 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2063 );
2064 const tile = adjacent.find((entry) =>
2065 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2066 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2067 );
2068 if (tile)
2069 { return tile; }
2070 }
2071 for (let radius = 0; radius <= 24; radius++)
2072 {
2073 for (let dy = -radius; dy <= radius; dy++)
2074 {
2075 for (let dx = -radius; dx <= radius; dx++)
2076 {
2077 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2078 { continue; }
2079 const tileX = originX + dx;
2080 const tileY = originY + dy;
2081 if (this.isEnterable(tileX, tileY, dimensionId)
2082 && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId))
2083 { return { tileX, tileY, dimensionId }; }
2084 }
2085 }
2086 }
2087 return this.findOpenSpawn();
2088 }
2089
2090 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
2091 {
2092 const dim = normalizeDimensionId(dimensionId);
2093 for (const record of this.directory.values())
2094 {
2095 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2096 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2097 { return true; }
2098 }
2099 return false;
2100 }
2101
2102 #recalculateActivation (now)
2103 {
2104 const loaders = this.#allLoaders();
2105 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
2106
2107 for (const [key, count] of regionRes)
2108 {
2109 if (count <= 0)
2110 { continue; }
2111 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2112 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId);
2113 this.regionGraceUntil.delete(key);
2114 }
2115
2116 for (const [key] of [...this.regionOwner.entries()])
2117 {
2118 if ((regionRes.get(key) ?? 0) > 0)
2119 { continue; }
2120 if (!this.regionGraceUntil.has(key))
2121 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
2122 if (now >= this.regionGraceUntil.get(key))
2123 {
2124 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2125 this.#unloadRegion(regionX, regionY, dimensionId);
2126 }
2127 }
2128
2129 for (const [workerId, worker] of this.workers.entries())
2130 {
2131 const chunkKeys = [];
2132 for (const [key, count] of chunkSim)
2133 {
2134 if (count <= 0)
2135 { continue; }
2136 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2137 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId)
2138 { chunkKeys.push(key); }
2139 }
2140 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
2141 }
2142 this.#syncAllReplicas();
2143
2144 const nextSimulating = new Set();
2145 for (const [key, count] of chunkSim)
2146 {
2147 if (count > 0)
2148 { nextSimulating.add(key); }
2149 }
2150 let preheated = false;
2151 for (const key of nextSimulating)
2152 {
2153 if (!this.simulatingChunkKeys.has(key))
2154 {
2155 preheated = true;
2156 break;
2157 }
2158 }
2159 this.simulatingChunkKeys = nextSimulating;
2160 if (preheated)
2161 { this.#stepSpawners(); }
2162 }
2163
2164 #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
2165 {
2166 const dim = normalizeDimensionId(dimensionId);
2167 const coverage = loaderCoverage(tileX, tileY, loader, dim);
2168 let preferred = this.#ownerOfTile(tileX, tileY, dim);
2169 for (const region of coverage.residentRegions)
2170 {
2171 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim);
2172 if (preferred == null)
2173 { preferred = owner; }
2174 }
2175 }
2176
2177 #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2178 {
2179 const dim = normalizeDimensionId(dimensionId);
2180 const key = regionKey(regionX, regionY, dim);
2181 if (this.regionOwner.has(key))
2182 { return this.regionOwner.get(key); }
2183 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim);
2184 this.workers[workerId].call({
2185 type: WorkerMessage.assignRegion,
2186 regionX,
2187 regionY,
2188 dimensionId: dim,
2189 chunks: this.#regionChunkBlobs(regionX, regionY, dim)
2190 });
2191 this.regionOwner.set(key, workerId);
2192 this.#restorePersistent(regionX, regionY, workerId);
2193 this.#restoreGroundItems(regionX, regionY, workerId);
2194 return workerId;
2195 }
2196
2197 #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2198 {
2199 const dim = normalizeDimensionId(dimensionId);
2200 const key = regionKey(regionX, regionY, dim);
2201 const workerId = this.regionOwner.get(key);
2202 if (workerId == null)
2203 { return; }
2204 const bounds = regionTileBounds(regionX, regionY);
2205 const { dropped, groundItems } = this.workers[workerId].call({
2206 type: WorkerMessage.dropRegion,
2207 regionX,
2208 regionY,
2209 dimensionId: dim
2210 });
2211 const persistent = [];
2212 for (const record of dropped ?? [])
2213 {
2214 if (record.characterId)
2215 {
2216 this.stateDb.saveCharacterPosition(
2217 record.characterId,
2218 record.tileX,
2219 record.tileY,
2220 record.gait ?? GAIT.walk,
2221 record.dimensionId ?? OVERWORLD_ID
2222 );
2223 }
2224 if (record.persistent)
2225 { persistent.push(record); }
2226 this.#forget(record.entityId);
2227 }
2228 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
2229 for (const item of groundItems ?? [])
2230 { this.stateDb.upsertGroundItem(item); }
2231 this.regionOwner.delete(key);
2232 this.regionGraceUntil.delete(key);
2233 }
2234
2235 #restorePersistent (regionX, regionY, workerId)
2236 {
2237 const bounds = regionTileBounds(regionX, regionY);
2238 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
2239 for (const row of rows)
2240 {
2241 if (this.directory.has(row.entity_id))
2242 { continue; }
2243 const components = JSON.parse(row.components_blob);
2244 const view = this.workers[workerId].call({
2245 type: WorkerMessage.spawn,
2246 entityId: row.entity_id,
2247 components
2248 });
2249 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
2250 this.#remember(view, workerId);
2251 }
2252 }
2253
2254 #applyTransfers (requests)
2255 {
2256 const events = [];
2257 for (const request of requests)
2258 {
2259 const destWorkerId = this.#ensureRegion(
2260 request.toRegionX,
2261 request.toRegionY,
2262 request.fromWorkerId,
2263 request.dimensionId ?? OVERWORLD_ID
2264 );
2265 if (destWorkerId === request.fromWorkerId)
2266 {
2267 this.workers[request.fromWorkerId].call({
2268 type: WorkerMessage.abortTransfer,
2269 entityId: request.entityId
2270 });
2271 continue;
2272 }
2273 let result;
2274 try
2275 {
2276 result = this.workers[destWorkerId].call({
2277 type: WorkerMessage.applyTransfer,
2278 payload: request.payload,
2279 destTileX: request.destTileX,
2280 destTileY: request.destTileY,
2281 dimensionId: request.dimensionId ?? OVERWORLD_ID
2282 });
2283 }
2284 catch
2285 {
2286 result = { accepted: false };
2287 }
2288 if (!result?.accepted)
2289 {
2290 this.workers[request.fromWorkerId].call({
2291 type: WorkerMessage.abortTransfer,
2292 entityId: request.entityId
2293 });
2294 continue;
2295 }
2296 this.workers[request.fromWorkerId].call({
2297 type: WorkerMessage.commitTransfer,
2298 entityId: request.entityId
2299 });
2300 this.#remember(result.entity, destWorkerId);
2301 events.push({
2302 type: "entity-move",
2303 entityId: request.entityId,
2304 fromTileX: request.fromTileX,
2305 fromTileY: request.fromTileY,
2306 fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId,
2307 tileX: result.entity.tileX,
2308 tileY: result.entity.tileY,
2309 dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID,
2310 gait: result.entity.gait
2311 });
2312 }
2313 return events;
2314 }
2315
2316 #syncAllReplicas ()
2317 {
2318 for (const [workerId, worker] of this.workers.entries())
2319 {
2320 const ownedKeys = new Set();
2321 for (const [key, owner] of this.regionOwner)
2322 {
2323 if (owner !== workerId)
2324 { continue; }
2325 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2326 for (const chunk of chunksInRegion(regionX, regionY))
2327 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); }
2328 }
2329 const replicas = [];
2330 for (const key of replicaNeededForOwnedChunks(ownedKeys))
2331 {
2332 if (ownedKeys.has(key))
2333 { continue; }
2334 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2335 replicas.push({
2336 chunkX,
2337 chunkY,
2338 dimensionId,
2339 data: this.#authoredChunk(chunkX, chunkY, dimensionId)
2340 });
2341 }
2342 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
2343 }
2344 }
2345
2346 #syncGhosts ()
2347 {
2348 const entities = [];
2349 for (const worker of this.workers)
2350 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
2351 for (const [workerId, worker] of this.workers.entries())
2352 {
2353 const ghosts = entities.filter((entity) =>
2354 {
2355 const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID);
2356 if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId)
2357 { return false; }
2358 return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim);
2359 });
2360 worker.call({ type: WorkerMessage.setGhosts, ghosts });
2361 }
2362 }
2363
2364 #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID)
2365 {
2366 const dim = normalizeDimensionId(dimensionId);
2367 const chunkX = tileToChunk(tileX);
2368 const chunkY = tileToChunk(tileY);
2369 for (const [key, owner] of this.regionOwner)
2370 {
2371 if (owner !== workerId)
2372 { continue; }
2373 const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key);
2374 if (regionDim !== dim)
2375 { continue; }
2376 for (const chunk of chunksInRegion(regionX, regionY))
2377 {
2378 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
2379 { return true; }
2380 }
2381 }
2382 return false;
2383 }
2384
2385 #allLoaders ()
2386 {
2387 const loaders = [];
2388 for (const worker of this.workers)
2389 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
2390 return loaders;
2391 }
2392
2393 #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID)
2394 {
2395 const dim = normalizeDimensionId(dimensionId);
2396 const votes = new Map();
2397 for (const loader of loaders)
2398 {
2399 const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
2400 if (loaderDim !== dim)
2401 { continue; }
2402 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
2403 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
2404 { continue; }
2405 const record = this.directory.get(loader.entityId);
2406 if (record?.workerId == null)
2407 { continue; }
2408 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
2409 }
2410 let best = null;
2411 let bestVotes = -1;
2412 for (const [workerId, count] of votes)
2413 {
2414 if (count > bestVotes)
2415 {
2416 best = workerId;
2417 bestVotes = count;
2418 }
2419 }
2420 return best;
2421 }
2422
2423 #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2424 {
2425 const dim = normalizeDimensionId(dimensionId);
2426 const pinned = this.pinRegion?.(regionX, regionY, dim);
2427 if (pinned != null)
2428 { return pinned; }
2429
2430 const neighborOwners = [];
2431 for (let dy = -1; dy <= 1; dy++)
2432 {
2433 for (let dx = -1; dx <= 1; dx++)
2434 {
2435 if (dx === 0 && dy === 0)
2436 { continue; }
2437 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim));
2438 if (owner != null)
2439 { neighborOwners.push(owner); }
2440 }
2441 }
2442
2443 const scores = this.workers.map((_, workerId) => ({
2444 workerId,
2445 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
2446 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
2447 }));
2448
2449 if (preferredWorkerId != null && scores[preferredWorkerId])
2450 {
2451 const preferred = scores[preferredWorkerId];
2452 if (preferred.neighbors > 0 || neighborOwners.length === 0)
2453 { return preferredWorkerId; }
2454 }
2455
2456 scores.sort((left, right) =>
2457 right.neighbors - left.neighbors
2458 || left.load - right.load
2459 || left.workerId - right.workerId
2460 );
2461 return scores[0].workerId;
2462 }
2463
2464 #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID)
2465 {
2466 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null;
2467 }
2468
2469 #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2470 {
2471 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId);
2472 }
2473
2474 #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID)
2475 {
2476 const dim = normalizeDimensionId(dimensionId);
2477 return chunksInRegion(regionX, regionY).map((coord) => ({
2478 chunkX: coord.chunkX,
2479 chunkY: coord.chunkY,
2480 dimensionId: dim,
2481 data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim)
2482 }));
2483 }
2484
2485 #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2486 {
2487 const dim = normalizeDimensionId(dimensionId);
2488 const key = chunkKey(chunkX, chunkY, dim);
2489 if (this.authoredCache.has(key))
2490 { return this.authoredCache.get(key); }
2491 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim);
2492 const dimRecord = this.getDimensionRecord(dim);
2493 const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId;
2494 const data = row
2495 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
2496 : createEmptyChunkData(defaultGroundTypeId);
2497 this.authoredCache.set(key, data);
2498 return data;
2499 }
2500
2501 #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2502 {
2503 const dim = normalizeDimensionId(dimensionId);
2504 const data = this.#authoredChunk(chunkX, chunkY, dim);
2505 return {
2506 chunkX,
2507 chunkY,
2508 dimensionId: dim,
2509 open: data.open,
2510 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open),
2511 grounds: data.grounds,
2512 blocks: data.blocks,
2513 light: data.light,
2514 entities: [],
2515 groundItems: []
2516 };
2517 }
2518
2519 #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID)
2520 {
2521 const dim = normalizeDimensionId(dimensionId);
2522 for (const record of this.directory.values())
2523 {
2524 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2525 if (record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2526 { return record.entityId; }
2527 }
2528 return null;
2529 }
2530
2531 #queueReplication (event)
2532 {
2533 if (event)
2534 { this.replication.push(event); }
2535 }
2536
2537 #stepSpawners ()
2538 {
2539 const events = [];
2540 for (const worker of this.workers)
2541 {
2542 const result = worker.call({ type: WorkerMessage.stepSpawners });
2543 for (const request of result?.spawnRequests ?? [])
2544 {
2545 try
2546 {
2547 this.spawnEntity(mobComponents(request), { requireResident: true });
2548 }
2549 catch
2550 { continue; }
2551 }
2552 }
2553 return events;
2554 }
2555
2556 #restoreGroundItems (regionX, regionY, workerId)
2557 {
2558 const bounds = regionTileBounds(regionX, regionY);
2559 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
2560 .filter((item) => item.expiresAt > this.now);
2561 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
2562 this.workers[workerId].call({
2563 type: WorkerMessage.setGroundItems,
2564 regionX,
2565 regionY,
2566 items
2567 });
2568 }
2569
2570 #persistGroundEvent (event)
2571 {
2572 if (event.type === "ground-item-appear")
2573 {
2574 this.stateDb.upsertGroundItem({
2575 groundItemId: event.groundItemId,
2576 tileX: event.tileX,
2577 tileY: event.tileY,
2578 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
2579 droppedAt: event.droppedAt ?? this.now,
2580 expiresAt: event.expiresAt,
2581 source: event.source ?? "player-drop",
2582 droppedByCharacterId: event.droppedByCharacterId ?? null
2583 });
2584 }
2585 if (event.type === "ground-item-despawn")
2586 { this.stateDb.deleteGroundItem(event.groundItemId); }
2587 }
2588
2589 #saveBag (entityId, workerId)
2590 {
2591 const record = this.directory.get(entityId);
2592 const bag = this.workers[workerId].call({
2593 type: WorkerMessage.inspectBag,
2594 entityId
2595 });
2596 if (!bag || !record?.characterId)
2597 { return; }
2598 this.#saveBagFromView(record.characterId, bag);
2599 const skills = this.workers[workerId].call({
2600 type: WorkerMessage.inspectSkills,
2601 entityId
2602 });
2603 if (skills)
2604 { this.stateDb.saveSkills(record.characterId, skills); }
2605 }
2606
2607 #applySkillsUpdated (event)
2608 {
2609 if (!event?.characterId || !event.stored)
2610 { return; }
2611 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
2612 this.pushSkills(event.characterId, event.skills ?? []);
2613 }
2614
2615 #applySpellsUpdated (event)
2616 {
2617 if (!event?.characterId || !event.stored)
2618 { return; }
2619 this.stateDb.saveSpells(event.characterId, event.stored);
2620 this.pushSpells(event.characterId, {
2621 spells: event.spells ?? [],
2622 autoCast: !!event.autoCast
2623 });
2624 }
2625
2626 #applySummonEntity (event)
2627 {
2628 const components = shadeSummonComponents({
2629 tileX: event.tileX | 0,
2630 tileY: event.tileY | 0,
2631 level: event.level | 0 || 1,
2632 ownerEntityId: event.ownerEntityId,
2633 expiresAt: event.expiresAt,
2634 dimensionId: event.dimensionId
2635 });
2636 try
2637 {
2638 const entityId = this.spawnEntity(components, { requireResident: true });
2639 if (entityId == null)
2640 { return []; }
2641 return [];
2642 }
2643 catch
2644 {
2645 return [];
2646 }
2647 }
2648
2649 #skillLevelUpEvents (event)
2650 {
2651 const levelUps = event?.levelUps ?? [];
2652 if (!levelUps.length)
2653 { return []; }
2654 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
2655 if (entityId == null)
2656 { return []; }
2657 const record = this.directory.get(entityId);
2658 const tileX = record?.tileX ?? 0;
2659 const tileY = record?.tileY ?? 0;
2660 return levelUps.map((levelUp) => ({
2661 type: "skill-level-up",
2662 entityId,
2663 characterId: event.characterId,
2664 tileX,
2665 tileY,
2666 skillId: levelUp.skillId,
2667 level: levelUp.level,
2668 previousLevel: levelUp.previousLevel,
2669 displayName: levelUp.displayName,
2670 icon: levelUp.icon
2671 }));
2672 }
2673
2674 #saveBagFromView (characterId, bag)
2675 {
2676 this.stateDb.saveBag(characterId, {
2677 inventory: bag.inventory,
2678 equipment: bag.equipment,
2679 vault: bag.vault,
2680 vaultReserved: bag.vaultReserved
2681 });
2682 }
2683
2684 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
2685 {
2686 const onlineId = this.characterEntities.get(issuerCharacterId);
2687 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
2688 if (!bag)
2689 { return { ok: false, error: "Issuer vault not found." }; }
2690 const reserved = [...(bag.vaultReserved ?? [])];
2691 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
2692 if (index < 0)
2693 { return { ok: false, error: "That cheque cannot be redeemed." }; }
2694 const [stack] = reserved.splice(index, 1);
2695 bag.vaultReserved = reserved;
2696 this.stateDb.saveBag(issuerCharacterId, bag);
2697 if (onlineId)
2698 {
2699 this.applyBag(onlineId, bag);
2700 this.pushInventory(issuerCharacterId, bag);
2701 }
2702 return { ok: true, stack };
2703 }
2704
2705 restoreChequeReservation (issuerCharacterId, stack)
2706 {
2707 const onlineId = this.characterEntities.get(issuerCharacterId);
2708 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
2709 if (!bag)
2710 { return; }
2711 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
2712 this.stateDb.saveBag(issuerCharacterId, bag);
2713 if (onlineId)
2714 {
2715 this.applyBag(onlineId, bag);
2716 this.pushInventory(issuerCharacterId, bag);
2717 }
2718 }
2719
2720 #remember (view, workerId)
2721 {
2722 if (!view)
2723 { return; }
2724 this.directory.set(view.entityId, { ...view, workerId });
2725 if (view.characterId)
2726 { this.characterEntities.set(view.characterId, view.entityId); }
2727 }
2728
2729 #applyMoveToDirectory (event)
2730 {
2731 const record = this.directory.get(event.entityId);
2732 if (!record)
2733 { return; }
2734 record.tileX = event.tileX;
2735 record.tileY = event.tileY;
2736 record.gait = event.gait;
2737 if (event.dimensionId != null)
2738 { record.dimensionId = normalizeDimensionId(event.dimensionId); }
2739 if (event.worldX != null)
2740 { record.worldX = event.worldX; }
2741 if (event.worldY != null)
2742 { record.worldY = event.worldY; }
2743 if (event.freeFlight != null)
2744 { record.freeFlight = !!event.freeFlight; }
2745 }
2746
2747 #forget (entityId)
2748 {
2749 const record = this.directory.get(entityId);
2750 if (record?.characterId)
2751 { this.characterEntities.delete(record.characterId); }
2752 this.directory.delete(entityId);
2753 }
2754}