BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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