BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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