BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 79.7 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 null; }
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 const routedCharacterId = item.command.characterId | 0;
1163 if (routedCharacterId && this.stateDb.getCharacter(routedCharacterId)?.is_dead)
1164 {
1165 // Queued intents after death (drop/use/send/craft/…) are discarded.
1166 return [];
1167 }
1168 if (item.command.type === "enter-doorway")
1169 {
1170 return this.#relocateCharacterThroughDoorway(
1171 item.sessionId,
1172 item.command.characterId,
1173 item.command.tileX,
1174 item.command.tileY
1175 );
1176 }
1177 if (
1178 item.command.type === "open-market"
1179 || item.command.type === "place-market-sell"
1180 || item.command.type === "place-market-buy"
1181 || item.command.type === "cancel-market-order"
1182 || item.command.type === "close-market"
1183 )
1184 {
1185 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1186 return result?.events ?? [];
1187 }
1188 if (
1189 item.command.type === "open-bounty"
1190 || item.command.type === "raise-bounty"
1191 || item.command.type === "get-character-bounty"
1192 || item.command.type === "close-bounty"
1193 )
1194 {
1195 const result = this.bounty.handleCommand(item.sessionId, item.command);
1196 return result?.events ?? [];
1197 }
1198 if (
1199 item.command.type === "open-barber"
1200 || item.command.type === "set-hair"
1201 || item.command.type === "close-barber"
1202 )
1203 {
1204 const result = this.barber.handleCommand(item.sessionId, item.command);
1205 return result?.events ?? [];
1206 }
1207 if (
1208 item.command.type === "dialogue-choose"
1209 || item.command.type === "dialogue-advance"
1210 || item.command.type === "close-dialogue"
1211 || item.command.type === "request-quests"
1212 )
1213 { return this.#handleQuestCommand(item); }
1214 const entityId = this.characterEntities.get(item.command.characterId);
1215 const record = entityId ? this.directory.get(entityId) : null;
1216 if (!record)
1217 {
1218 const error = new Error("Character is not in the world.");
1219 error.userFacing = true;
1220 throw error;
1221 }
1222 if (item.command.type === "drop-item" && item.command.groundItemId == null)
1223 { item.command.groundItemId = this.nextGroundItemId++; }
1224 if (item.command.type === "attack")
1225 {
1226 const targetRecord = this.directory.get(item.command.targetEntityId);
1227 if (!targetRecord)
1228 {
1229 const error = new Error("Target is not here.");
1230 error.userFacing = true;
1231 throw error;
1232 }
1233 const events = this.#finishRoutedCommand(item, record);
1234 if (targetRecord.workerId !== record.workerId)
1235 {
1236 this.workers[targetRecord.workerId].call({
1237 type: WorkerMessage.remoteCombatEngage,
1238 attackerEntityId: record.entityId,
1239 targetEntityId: item.command.targetEntityId,
1240 now: item.receivedAt ?? this.now
1241 });
1242 }
1243 return events;
1244 }
1245 return this.#finishRoutedCommand(item, record);
1246 }
1247
1248 #finishRoutedCommand (item, record)
1249 {
1250 const result = this.workers[record.workerId].call({
1251 type: WorkerMessage.command,
1252 sessionId: item.sessionId,
1253 command: item.command,
1254 now: item.receivedAt ?? this.now
1255 });
1256 const view = this.workers[record.workerId].call({
1257 type: WorkerMessage.inspect,
1258 entityId: record.entityId
1259 });
1260 if (view)
1261 { this.#remember(view, record.workerId); }
1262 if (result?.private)
1263 { this.#saveBagFromView(item.command.characterId, result.private); }
1264 if (result?.appearanceChanged && view)
1265 { this.#queueReplication(replicationAppearance(view)); }
1266 if (result?.remainder)
1267 {
1268 this.stateDb.saveInheritance(
1269 this.stateDb.getCharacter(item.command.characterId).account_id,
1270 { slots: result.remainder }
1271 );
1272 }
1273 for (const event of result?.events ?? [])
1274 { this.#persistGroundEvent(event); }
1275 const events = [];
1276 for (const event of result?.events ?? [])
1277 {
1278 if (event.type === "skills-updated")
1279 {
1280 this.#applySkillsUpdated(event);
1281 events.push(...this.#skillLevelUpEvents(event));
1282 continue;
1283 }
1284 if (event.type === "spells-updated")
1285 {
1286 this.#applySpellsUpdated(event);
1287 continue;
1288 }
1289 if (event.type === "open-dialogue")
1290 {
1291 events.push(...this.#handleOpenDialogue(event));
1292 continue;
1293 }
1294 events.push(event);
1295 }
1296 if (item.command.type === "attack" && item.command.targetEntityId != null)
1297 {
1298 events.push(...this.#mapQuestPrivateEvents(
1299 this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []
1300 ));
1301 }
1302 if (result?.private)
1303 {
1304 events.push({
1305 type: "inventory",
1306 sessionId: item.sessionId,
1307 bank: !!result.bank,
1308 cauldron: result.cauldron,
1309 cauldronState: result.cauldronState ?? null,
1310 alchemyResult: result.alchemyResult ?? null,
1311 dyeConfirm: result.dyeConfirm ?? null,
1312 ...result.private
1313 });
1314 }
1315 if (result?.statusEffectsChanged && view)
1316 {
1317 events.push({
1318 type: "status-effects",
1319 sessionId: item.sessionId,
1320 characterId: view.characterId ?? item.command.characterId,
1321 effects: view.statusEffects ?? [],
1322 blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind")
1323 });
1324 }
1325 if (result?.healthChanged && view)
1326 {
1327 events.push({
1328 type: "entity-health",
1329 entityId: view.entityId,
1330 characterId: view.characterId ?? item.command.characterId,
1331 health: view.health,
1332 maxHealth: view.maxHealth,
1333 tileX: view.tileX,
1334 tileY: view.tileY
1335 });
1336 }
1337 return events;
1338 }
1339
1340 #applyRemoteMelee (payload)
1341 {
1342 const targetRecord = this.directory.get(payload.targetId);
1343 if (!targetRecord)
1344 { return []; }
1345 const result = this.workers[targetRecord.workerId].call({
1346 ...payload,
1347 type: WorkerMessage.applyRemoteMelee
1348 });
1349 const events = [];
1350 for (const event of result?.events ?? [])
1351 {
1352 if (event.type === "entity-despawn")
1353 { this.#forget(event.entityId); }
1354 if (event.type === "skills-updated")
1355 {
1356 this.#applySkillsUpdated(event);
1357 events.push(...this.#skillLevelUpEvents(event));
1358 continue;
1359 }
1360 if (event.type === "spells-updated")
1361 {
1362 this.#applySpellsUpdated(event);
1363 continue;
1364 }
1365 if (event.type === "player-died")
1366 {
1367 events.push(...this.#applyPlayerDeath(event));
1368 continue;
1369 }
1370 if (event.type === "mob-killed")
1371 {
1372 events.push(...this.#applyMobKilled(event));
1373 continue;
1374 }
1375 this.#persistGroundEvent(event);
1376 if (event.type !== "skills-updated")
1377 { events.push(event); }
1378 }
1379 for (const forward of result?.forwards ?? [])
1380 {
1381 if (forward.type !== "forward-combat-xp")
1382 { continue; }
1383 const attackerRecord = this.directory.get(forward.entityId);
1384 if (!attackerRecord)
1385 { continue; }
1386 const xpResult = this.workers[attackerRecord.workerId].call({
1387 type: WorkerMessage.applyCombatHitXp,
1388 entityId: forward.entityId,
1389 profile: forward.profile,
1390 damage: forward.damage
1391 });
1392 for (const xpEvent of xpResult?.events ?? [])
1393 {
1394 if (xpEvent.type === "skills-updated")
1395 {
1396 this.#applySkillsUpdated(xpEvent);
1397 events.push(...this.#skillLevelUpEvents(xpEvent));
1398 continue;
1399 }
1400 events.push(xpEvent);
1401 }
1402 }
1403 return events;
1404 }
1405
1406 #applyRemoteRanged (payload)
1407 {
1408 const targetRecord = this.directory.get(payload.targetId);
1409 if (!targetRecord)
1410 { return []; }
1411 const result = this.workers[targetRecord.workerId].call({
1412 ...payload,
1413 type: WorkerMessage.applyRemoteRanged
1414 });
1415 const events = [];
1416 for (const event of result?.events ?? [])
1417 {
1418 if (event.type === "entity-despawn")
1419 { this.#forget(event.entityId); }
1420 if (event.type === "skills-updated")
1421 {
1422 this.#applySkillsUpdated(event);
1423 events.push(...this.#skillLevelUpEvents(event));
1424 continue;
1425 }
1426 if (event.type === "spells-updated")
1427 {
1428 this.#applySpellsUpdated(event);
1429 continue;
1430 }
1431 if (event.type === "player-died")
1432 {
1433 events.push(...this.#applyPlayerDeath(event));
1434 continue;
1435 }
1436 if (event.type === "mob-killed")
1437 {
1438 events.push(...this.#applyMobKilled(event));
1439 continue;
1440 }
1441 this.#persistGroundEvent(event);
1442 if (event.type !== "skills-updated")
1443 { events.push(event); }
1444 }
1445 for (const forward of result?.forwards ?? [])
1446 {
1447 if (forward.type !== "forward-combat-xp")
1448 { continue; }
1449 const attackerRecord = this.directory.get(forward.entityId);
1450 if (!attackerRecord)
1451 { continue; }
1452 const xpResult = this.workers[attackerRecord.workerId].call({
1453 type: WorkerMessage.applyCombatHitXp,
1454 entityId: forward.entityId,
1455 profile: forward.profile,
1456 damage: forward.damage
1457 });
1458 for (const xpEvent of xpResult?.events ?? [])
1459 {
1460 if (xpEvent.type === "skills-updated")
1461 {
1462 this.#applySkillsUpdated(xpEvent);
1463 events.push(...this.#skillLevelUpEvents(xpEvent));
1464 continue;
1465 }
1466 events.push(xpEvent);
1467 }
1468 }
1469 return events;
1470 }
1471
1472 #handleQuestCommand (item)
1473 {
1474 const characterId = item.command.characterId | 0;
1475 const sessionId = item.sessionId;
1476 if (!this.quests)
1477 { return []; }
1478 if (item.command.type === "request-quests")
1479 {
1480 const snap = this.quests.questSnapshot(characterId);
1481 return [{ type: "quests-snapshot", sessionId, characterId, ...snap }];
1482 }
1483 if (item.command.type === "close-dialogue")
1484 {
1485 const closed = this.quests.closeDialogue(characterId, "client");
1486 return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId);
1487 }
1488 if (item.command.type === "dialogue-choose")
1489 {
1490 const result = this.quests.chooseDialogue(characterId, item.command.trigger);
1491 if (!result.ok)
1492 {
1493 const error = new Error(result.error || "Choice failed.");
1494 error.userFacing = true;
1495 throw error;
1496 }
1497 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1498 }
1499 if (item.command.type === "dialogue-advance")
1500 {
1501 const result = this.quests.advanceDialogue(characterId);
1502 if (!result.ok)
1503 {
1504 const error = new Error(result.error || "Cannot advance.");
1505 error.userFacing = true;
1506 throw error;
1507 }
1508 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1509 }
1510 return [];
1511 }
1512
1513 #handleOpenDialogue (event)
1514 {
1515 const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId);
1516 if (!result.ok)
1517 {
1518 return [{
1519 type: "toast",
1520 characterId: event.characterId,
1521 sessionId: event.sessionId,
1522 message: result.error || "Nothing to say."
1523 }];
1524 }
1525 this.#pinDialogueNpc(event.entityId, event.characterId);
1526 return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId);
1527 }
1528
1529 #pinDialogueNpc (entityId, characterId)
1530 {
1531 const record = this.directory.get(entityId | 0);
1532 if (!record)
1533 { return; }
1534 this.workers[record.workerId]?.call?.({
1535 type: WorkerMessage.pinDialogue,
1536 entityId: entityId | 0,
1537 characterId: characterId | 0
1538 });
1539 }
1540
1541 #unpinDialogueNpc (entityId, characterId)
1542 {
1543 const record = this.directory.get(entityId | 0);
1544 if (!record)
1545 { return; }
1546 this.workers[record.workerId]?.call?.({
1547 type: WorkerMessage.unpinDialogue,
1548 entityId: entityId | 0,
1549 characterId: characterId | 0
1550 });
1551 }
1552
1553 #mapQuestPrivateEvents (events, sessionId = null, characterId = null)
1554 {
1555 const out = [];
1556 let needSnapshot = false;
1557 for (const event of events ?? [])
1558 {
1559 const cid = event.characterId ?? characterId;
1560 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1561 if (event.type === "dialogueStep")
1562 {
1563 out.push({
1564 type: "dialogue-step",
1565 sessionId: sid,
1566 characterId: cid,
1567 dialogueId: event.dialogueId,
1568 stepId: event.stepId,
1569 label: event.label,
1570 npcEntityId: event.npcEntityId,
1571 lines: event.lines
1572 });
1573 }
1574 else if (event.type === "dialogueChoices")
1575 {
1576 out.push({
1577 type: "dialogue-choices",
1578 sessionId: sid,
1579 characterId: cid,
1580 dialogueId: event.dialogueId,
1581 stepId: event.stepId,
1582 npcEntityId: event.npcEntityId,
1583 triggers: event.triggers
1584 });
1585 }
1586 else if (event.type === "dialogueClose")
1587 {
1588 if (event.npcEntityId != null && cid != null)
1589 { this.#unpinDialogueNpc(event.npcEntityId, cid); }
1590 out.push({
1591 type: "dialogue-close",
1592 sessionId: sid,
1593 characterId: cid,
1594 reason: event.reason
1595 });
1596 }
1597 else if (event.type === "questStepComplete")
1598 {
1599 out.push({
1600 type: "quest-step-complete",
1601 sessionId: sid,
1602 characterId: cid,
1603 questId: event.questId,
1604 title: event.title
1605 });
1606 needSnapshot = true;
1607 }
1608 else if (event.type === "questsDirty")
1609 { needSnapshot = true; }
1610 else if (event.type === "inventoryDirty" && cid != null)
1611 {
1612 const onlineId = this.characterEntities.get(cid | 0);
1613 if (onlineId)
1614 {
1615 const live = this.bagOf(onlineId);
1616 if (live)
1617 { this.pushInventory(cid, live); }
1618 }
1619 }
1620 }
1621 if (needSnapshot && characterId != null)
1622 {
1623 const snap = this.quests.questSnapshot(characterId);
1624 out.push({
1625 type: "quests-snapshot",
1626 sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
1627 characterId,
1628 ...snap
1629 });
1630 }
1631 return out;
1632 }
1633
1634 #sessionIdForCharacter (characterId)
1635 {
1636 const entityId = this.characterEntities.get(characterId | 0);
1637 const record = entityId != null ? this.directory.get(entityId) : null;
1638 return record?.sessionId ?? null;
1639 }
1640
1641 #applyMobKilled (event)
1642 {
1643 const out = [event];
1644 const attackerRecord = this.directory.get(event.attackerId);
1645 const killerCharacterId = attackerRecord?.characterId ?? null;
1646 const killerPos = attackerRecord
1647 ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
1648 : null;
1649 if (killerCharacterId && this.quests)
1650 {
1651 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
1652 mobTypeId: event.mobTypeId,
1653 spawnerId: event.spawnerId
1654 })));
1655 }
1656 out.push(...this.#mapQuestPrivateEvents(
1657 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
1658 ));
1659 let bountyAwarded = 0;
1660 if (killerCharacterId && (event.bounty | 0) > 0)
1661 {
1662 bountyAwarded = event.bounty | 0;
1663 const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1664 this.refreshCharacterSkull(killerCharacterId);
1665 out.push({
1666 type: "toast",
1667 characterId: killerCharacterId,
1668 message: `Bounty +${bountyAwarded} (total ${total})`
1669 });
1670 }
1671
1672 if (killerCharacterId && killerPos)
1673 {
1674 if (bountyAwarded > 0)
1675 { this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); }
1676 if (event.townGuard)
1677 { this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); }
1678 }
1679 return out;
1680 }
1681
1682 /**
1683 * Send up to `count` town guards at the killer. Prefer idle guards.
1684 * When `spawnerId` is set, only that spawner's guards are used.
1685 */
1686 #dispatchTownGuards (targetEntityId, killerPos, spawnerId, count)
1687 {
1688 const want = Math.max(0, count | 0);
1689 if (want <= 0 || targetEntityId == null || !killerPos)
1690 { return; }
1691 const candidates = [];
1692 for (const worker of this.workers)
1693 {
1694 const result = worker.call({
1695 type: WorkerMessage.listTownGuardsNear,
1696 tileX: killerPos.tileX,
1697 tileY: killerPos.tileY,
1698 spawnerId,
1699 limit: 32
1700 });
1701 for (const guard of result?.guards ?? [])
1702 { candidates.push(guard); }
1703 }
1704 candidates.sort((a, b) => Number(a.busy) - Number(b.busy));
1705 let sent = 0;
1706 for (const guard of candidates)
1707 {
1708 if (sent >= want)
1709 { break; }
1710 if (guard.entityId === targetEntityId)
1711 { continue; }
1712 const record = this.directory.get(guard.entityId);
1713 if (!record)
1714 { continue; }
1715 this.workers[record.workerId].call({
1716 type: WorkerMessage.engageTarget,
1717 attackerEntityId: guard.entityId,
1718 targetEntityId,
1719 now: this.now
1720 });
1721 sent += 1;
1722 }
1723 }
1724
1725 #applyPlayerDeath (event)
1726 {
1727 const record = this.directory.get(event.entityId);
1728 if (!record)
1729 { return [event]; }
1730 this.stateDb.setCharacterDead(event.characterId, true);
1731 this.stateDb.saveCharacterPosition(
1732 event.characterId,
1733 event.tileX,
1734 event.tileY,
1735 record.gait ?? GAIT.walk,
1736 record.dimensionId ?? OVERWORLD_ID
1737 );
1738 this.bounty?.settleKill(
1739 event.characterId,
1740 event.attackerId,
1741 event.tileX,
1742 event.tileY
1743 );
1744 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1745 const killerCharacterId = Number(attackerRecord?.characterId) || 0;
1746 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
1747 { this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now); }
1748 const events = [event];
1749 const closedDialogue = this.quests?.closeDialogue(event.characterId, "death");
1750 if (closedDialogue?.events?.length)
1751 {
1752 events.push(...this.#mapQuestPrivateEvents(
1753 closedDialogue.events,
1754 event.sessionId,
1755 event.characterId
1756 ));
1757 }
1758 if (event.sessionId != null)
1759 {
1760 for (const commandType of ["cancel-craft", "cauldron-close"])
1761 {
1762 try
1763 {
1764 this.workers[record.workerId].call({
1765 type: WorkerMessage.command,
1766 sessionId: event.sessionId,
1767 command: { type: commandType, characterId: event.characterId },
1768 now: this.now
1769 });
1770 }
1771 catch
1772 { /* best-effort session cleanup */ }
1773 }
1774 }
1775 // Bounty is cleared instantly on non-friend PvP death; only kill-counter decays over time.
1776 const victimSkull = this.refreshCharacterSkull(event.characterId, { force: true });
1777 if (victimSkull)
1778 { events.push(victimSkull); }
1779 for (const worker of this.workers)
1780 {
1781 worker.call({
1782 type: WorkerMessage.clearCombat,
1783 entityId: event.entityId,
1784 targetEntityId: event.entityId
1785 });
1786 }
1787 const victimName = `${record.firstName ?? "someone"} ${record.lastName ?? ""}`.trim()
1788 || "someone";
1789 const killerName = `${attackerRecord?.firstName ?? ""} ${attackerRecord?.lastName ?? ""}`.trim()
1790 || "someone";
1791 const corpseOrigin = lootOrigin(victimName, killerName);
1792 const result = this.workers[record.workerId].call({
1793 type: WorkerMessage.spawnCorpseDrops,
1794 characterId: event.characterId,
1795 tileX: event.tileX,
1796 tileY: event.tileY,
1797 now: this.now,
1798 dropCarriedCoins: true,
1799 coinGroundItemId: this.nextGroundItemId++,
1800 drops: [
1801 {
1802 groundItemId: this.nextGroundItemId++,
1803 stack: attachOrigins({
1804 itemId: ItemId.bones,
1805 quantity: 1,
1806 origins: [{ origin: corpseOrigin, quantity: 1 }]
1807 })
1808 },
1809 {
1810 groundItemId: this.nextGroundItemId++,
1811 stack: attachOrigins({
1812 itemId: ItemId.skull,
1813 quantity: 1,
1814 origins: [{ origin: corpseOrigin, quantity: 1 }]
1815 })
1816 }
1817 ]
1818 });
1819 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
1820 {
1821 const skullEvent = this.refreshCharacterSkull(killerCharacterId, { force: true });
1822 if (skullEvent)
1823 { events.push(skullEvent); }
1824 }
1825 events.push({
1826 type: "entity-despawn",
1827 entityId: event.entityId,
1828 tileX: event.tileX,
1829 tileY: event.tileY
1830 });
1831 for (const dropEvent of result?.events ?? [])
1832 {
1833 this.#persistGroundEvent(dropEvent);
1834 events.push(dropEvent);
1835 }
1836 if (result?.private)
1837 {
1838 this.#saveBagFromView(event.characterId, result.private);
1839 if (event.sessionId != null)
1840 {
1841 events.push({
1842 type: "inventory",
1843 sessionId: event.sessionId,
1844 ...result.private
1845 });
1846 }
1847 }
1848 return events;
1849 }
1850
1851 #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY)
1852 {
1853 const entityId = this.characterEntities.get(characterId);
1854 const record = entityId ? this.directory.get(entityId) : null;
1855 if (!record)
1856 {
1857 const error = new Error("Character is not in the world.");
1858 error.userFacing = true;
1859 throw error;
1860 }
1861 const tileX = doorwayTileX | 0;
1862 const tileY = doorwayTileY | 0;
1863 if (chebyshev(record.tileX, record.tileY, tileX, tileY) > 1)
1864 {
1865 const error = new Error("You are too far from that doorway.");
1866 error.userFacing = true;
1867 throw error;
1868 }
1869 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1870 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId);
1871 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
1872 if (block?.typeId !== BlockType.doorway)
1873 {
1874 const error = new Error("There is no doorway there.");
1875 error.userFacing = true;
1876 throw error;
1877 }
1878 const config = block.config && typeof block.config === "object" ? block.config : null;
1879 const targetRaw = config?.targetDimensionId;
1880 if (targetRaw == null || String(targetRaw).trim() === "")
1881 {
1882 const error = new Error("That doorway leads nowhere.");
1883 error.userFacing = true;
1884 throw error;
1885 }
1886 const targetDimensionId = normalizeDimensionId(targetRaw);
1887 const destTileX = Number(config.tileX);
1888 const destTileY = Number(config.tileY);
1889 if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY))
1890 {
1891 const error = new Error("That doorway leads nowhere.");
1892 error.userFacing = true;
1893 throw error;
1894 }
1895 const destX = destTileX | 0;
1896 const destY = destTileY | 0;
1897 if (!this.#isDimensionUsable(targetDimensionId))
1898 {
1899 const error = new Error("That place is no longer reachable.");
1900 error.userFacing = true;
1901 throw error;
1902 }
1903 if (!this.isEnterable(destX, destY, targetDimensionId))
1904 {
1905 const error = new Error("The other side is blocked.");
1906 error.userFacing = true;
1907 throw error;
1908 }
1909
1910 const events = [];
1911 if (this.quests)
1912 {
1913 const closed = this.quests.closeDialogue(characterId, "doorway");
1914 if (closed?.events?.length)
1915 { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); }
1916 }
1917
1918 const loader = { ...DEFAULT_CHUNK_LOADER };
1919 this.#ensureCoverage(destX, destY, loader, targetDimensionId);
1920 const result = this.workers[record.workerId].call({
1921 type: WorkerMessage.relocateEntity,
1922 entityId,
1923 tileX: destX,
1924 tileY: destY,
1925 dimensionId: targetDimensionId
1926 });
1927 if (!result?.accepted)
1928 {
1929 const error = new Error("Could not enter that doorway.");
1930 error.userFacing = true;
1931 throw error;
1932 }
1933 let moveEvents = [];
1934 if (result.transferRequest)
1935 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1936 else if (result.event)
1937 {
1938 this.#applyMoveToDirectory(result.event);
1939 moveEvents = [result.event];
1940 const view = this.workers[record.workerId].call({
1941 type: WorkerMessage.inspect,
1942 entityId
1943 });
1944 if (view)
1945 { this.#remember(view, record.workerId); }
1946 }
1947 if (!moveEvents.length)
1948 {
1949 const error = new Error("Could not enter that doorway.");
1950 error.userFacing = true;
1951 throw error;
1952 }
1953 this.stateDb.saveCharacterPosition(
1954 characterId,
1955 destX,
1956 destY,
1957 record.gait ?? GAIT.walk,
1958 targetDimensionId
1959 );
1960 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
1961 this.#recalculateActivation(this.now);
1962 this.#syncGhosts();
1963 const dimRecord = this.getDimensionRecord(targetDimensionId);
1964 events.push(...moveEvents, {
1965 type: "dimension-changed",
1966 sessionId,
1967 characterId,
1968 entityId,
1969 dimensionId: targetDimensionId,
1970 tileX: destX,
1971 tileY: destY,
1972 lightingMode: dimRecord?.lightingMode ?? "dayNight",
1973 seasonMode: dimRecord?.seasonMode ?? "auto"
1974 });
1975 return events;
1976 }
1977
1978 #respawnCharacter (sessionId, characterId)
1979 {
1980 const row = this.stateDb.getCharacter(characterId);
1981 if (!row?.is_dead)
1982 {
1983 const error = new Error("You are not dead.");
1984 error.userFacing = true;
1985 throw error;
1986 }
1987 const entityId = this.characterEntities.get(characterId);
1988 const record = entityId ? this.directory.get(entityId) : null;
1989 if (!record)
1990 {
1991 const error = new Error("Character is not in the world.");
1992 error.userFacing = true;
1993 throw error;
1994 }
1995 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
1996 if (!destination)
1997 {
1998 const error = new Error("No open tile is available for respawn.");
1999 error.userFacing = true;
2000 throw error;
2001 }
2002 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
2003 const loader = { ...DEFAULT_CHUNK_LOADER };
2004 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID);
2005 const result = this.workers[record.workerId].call({
2006 type: WorkerMessage.applyRespawn,
2007 entityId,
2008 sessionId,
2009 tileX: destination.tileX,
2010 tileY: destination.tileY,
2011 maxHealth: playerMaxHealth(skills),
2012 maxStamina: playerMaxStamina(skills)
2013 });
2014 if (!result?.accepted)
2015 {
2016 const error = new Error("That respawn tile is no longer available.");
2017 error.userFacing = true;
2018 throw error;
2019 }
2020 let moveEvents = [];
2021 if (result.transferRequest)
2022 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
2023 else if (result.event)
2024 {
2025 this.#applyMoveToDirectory(result.event);
2026 moveEvents = [result.event];
2027 const view = this.workers[record.workerId].call({
2028 type: WorkerMessage.inspect,
2029 entityId
2030 });
2031 if (view)
2032 { this.#remember(view, record.workerId); }
2033 }
2034 if (!moveEvents.length)
2035 {
2036 const error = new Error("Respawn transfer failed.");
2037 error.userFacing = true;
2038 throw error;
2039 }
2040 this.stateDb.setCharacterDead(characterId, false);
2041 const respawnHealth = playerMaxHealth(skills);
2042 this.stateDb.saveCharacterHealth(characterId, respawnHealth);
2043 this.stateDb.saveCharacterPosition(
2044 characterId,
2045 destination.tileX,
2046 destination.tileY,
2047 record.gait ?? GAIT.walk,
2048 destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
2049 );
2050 this.#recalculateActivation(this.now);
2051 this.#syncGhosts();
2052 const skullEvent = this.refreshCharacterSkull(characterId, { force: true });
2053 const skullPoints = this.directory.get(entityId)?.skullValue | 0;
2054 const spawnView = this.workers[record.workerId].call({
2055 type: WorkerMessage.inspect,
2056 entityId
2057 });
2058 const spawn = spawnView
2059 ? replicationSpawn({ ...spawnView, skullValue: skullPoints })
2060 : null;
2061 return [
2062 ...moveEvents,
2063 ...(spawn ? [spawn] : []),
2064 ...(skullEvent ? [skullEvent] : []),
2065 {
2066 type: "player-respawned",
2067 entityId,
2068 characterId,
2069 sessionId,
2070 tileX: destination.tileX,
2071 tileY: destination.tileY,
2072 health: playerMaxHealth(skills),
2073 maxHealth: playerMaxHealth(skills),
2074 stamina: playerMaxStamina(skills),
2075 maxStamina: playerMaxStamina(skills),
2076 skullValue: skullPoints
2077 }
2078 ];
2079 }
2080
2081 #refreshAltarIndex ()
2082 {
2083 const altars = [];
2084 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
2085 {
2086 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
2087 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim);
2088 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2089 {
2090 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2091 {
2092 const block = data.blocks[localY * CHUNK_SIZE + localX];
2093 if (block?.typeId !== BlockType.churchAltar)
2094 { continue; }
2095 altars.push({
2096 tileX: coord.chunk_x * CHUNK_SIZE + localX,
2097 tileY: coord.chunk_y * CHUNK_SIZE + localY,
2098 dimensionId: dim
2099 });
2100 }
2101 }
2102 }
2103 this.altarTiles = altars;
2104 }
2105
2106 #findRespawnDestination (originX, originY, entityId)
2107 {
2108 const record = this.directory.get(entityId);
2109 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2110 const ordered = [...this.altarTiles].sort((left, right) =>
2111 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2112 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2113 );
2114 for (const altar of ordered)
2115 {
2116 const adjacent = [];
2117 for (let dy = -1; dy <= 1; dy++)
2118 {
2119 for (let dx = -1; dx <= 1; dx++)
2120 {
2121 if (dx === 0 && dy === 0)
2122 { continue; }
2123 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId });
2124 }
2125 }
2126 adjacent.sort((left, right) =>
2127 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2128 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2129 );
2130 const tile = adjacent.find((entry) =>
2131 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2132 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2133 );
2134 if (tile)
2135 { return tile; }
2136 }
2137 for (let radius = 0; radius <= 24; radius++)
2138 {
2139 for (let dy = -radius; dy <= radius; dy++)
2140 {
2141 for (let dx = -radius; dx <= radius; dx++)
2142 {
2143 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2144 { continue; }
2145 const tileX = originX + dx;
2146 const tileY = originY + dy;
2147 if (this.isEnterable(tileX, tileY, dimensionId)
2148 && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId))
2149 { return { tileX, tileY, dimensionId }; }
2150 }
2151 }
2152 }
2153 return this.findOpenSpawn();
2154 }
2155
2156 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
2157 {
2158 const dim = normalizeDimensionId(dimensionId);
2159 for (const record of this.directory.values())
2160 {
2161 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2162 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2163 { return true; }
2164 }
2165 return false;
2166 }
2167
2168 #recalculateActivation (now)
2169 {
2170 const loaders = this.#allLoaders();
2171 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
2172
2173 for (const [key, count] of regionRes)
2174 {
2175 if (count <= 0)
2176 { continue; }
2177 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2178 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId);
2179 this.regionGraceUntil.delete(key);
2180 }
2181
2182 for (const [key] of [...this.regionOwner.entries()])
2183 {
2184 if ((regionRes.get(key) ?? 0) > 0)
2185 { continue; }
2186 if (!this.regionGraceUntil.has(key))
2187 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
2188 if (now >= this.regionGraceUntil.get(key))
2189 {
2190 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2191 this.#unloadRegion(regionX, regionY, dimensionId);
2192 }
2193 }
2194
2195 for (const [workerId, worker] of this.workers.entries())
2196 {
2197 const chunkKeys = [];
2198 for (const [key, count] of chunkSim)
2199 {
2200 if (count <= 0)
2201 { continue; }
2202 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2203 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId)
2204 { chunkKeys.push(key); }
2205 }
2206 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
2207 }
2208 this.#syncAllReplicas();
2209
2210 const nextSimulating = new Set();
2211 for (const [key, count] of chunkSim)
2212 {
2213 if (count > 0)
2214 { nextSimulating.add(key); }
2215 }
2216 let preheated = false;
2217 for (const key of nextSimulating)
2218 {
2219 if (!this.simulatingChunkKeys.has(key))
2220 {
2221 preheated = true;
2222 break;
2223 }
2224 }
2225 this.simulatingChunkKeys = nextSimulating;
2226 if (preheated)
2227 { this.#stepSpawners(); }
2228 }
2229
2230 #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
2231 {
2232 const dim = normalizeDimensionId(dimensionId);
2233 const coverage = loaderCoverage(tileX, tileY, loader, dim);
2234 let preferred = this.#ownerOfTile(tileX, tileY, dim);
2235 for (const region of coverage.residentRegions)
2236 {
2237 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim);
2238 if (preferred == null)
2239 { preferred = owner; }
2240 }
2241 }
2242
2243 #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2244 {
2245 const dim = normalizeDimensionId(dimensionId);
2246 const key = regionKey(regionX, regionY, dim);
2247 if (this.regionOwner.has(key))
2248 { return this.regionOwner.get(key); }
2249 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim);
2250 this.workers[workerId].call({
2251 type: WorkerMessage.assignRegion,
2252 regionX,
2253 regionY,
2254 dimensionId: dim,
2255 chunks: this.#regionChunkBlobs(regionX, regionY, dim)
2256 });
2257 this.regionOwner.set(key, workerId);
2258 this.#restorePersistent(regionX, regionY, workerId);
2259 this.#restoreGroundItems(regionX, regionY, workerId);
2260 return workerId;
2261 }
2262
2263 #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2264 {
2265 const dim = normalizeDimensionId(dimensionId);
2266 const key = regionKey(regionX, regionY, dim);
2267 const workerId = this.regionOwner.get(key);
2268 if (workerId == null)
2269 { return; }
2270 const bounds = regionTileBounds(regionX, regionY);
2271 const { dropped, groundItems } = this.workers[workerId].call({
2272 type: WorkerMessage.dropRegion,
2273 regionX,
2274 regionY,
2275 dimensionId: dim
2276 });
2277 const persistent = [];
2278 for (const record of dropped ?? [])
2279 {
2280 if (record.characterId)
2281 {
2282 this.stateDb.saveCharacterPosition(
2283 record.characterId,
2284 record.tileX,
2285 record.tileY,
2286 record.gait ?? GAIT.walk,
2287 record.dimensionId ?? OVERWORLD_ID
2288 );
2289 }
2290 if (record.persistent)
2291 { persistent.push(record); }
2292 this.#forget(record.entityId);
2293 }
2294 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
2295 for (const item of groundItems ?? [])
2296 { this.stateDb.upsertGroundItem(item); }
2297 this.regionOwner.delete(key);
2298 this.regionGraceUntil.delete(key);
2299 }
2300
2301 #restorePersistent (regionX, regionY, workerId)
2302 {
2303 const bounds = regionTileBounds(regionX, regionY);
2304 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
2305 for (const row of rows)
2306 {
2307 if (this.directory.has(row.entity_id))
2308 { continue; }
2309 const components = JSON.parse(row.components_blob);
2310 const view = this.workers[workerId].call({
2311 type: WorkerMessage.spawn,
2312 entityId: row.entity_id,
2313 components
2314 });
2315 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
2316 this.#remember(view, workerId);
2317 }
2318 }
2319
2320 #applyTransfers (requests)
2321 {
2322 const events = [];
2323 for (const request of requests)
2324 {
2325 const destWorkerId = this.#ensureRegion(
2326 request.toRegionX,
2327 request.toRegionY,
2328 request.fromWorkerId,
2329 request.dimensionId ?? OVERWORLD_ID
2330 );
2331 if (destWorkerId === request.fromWorkerId)
2332 {
2333 this.workers[request.fromWorkerId].call({
2334 type: WorkerMessage.abortTransfer,
2335 entityId: request.entityId
2336 });
2337 continue;
2338 }
2339 let result;
2340 try
2341 {
2342 result = this.workers[destWorkerId].call({
2343 type: WorkerMessage.applyTransfer,
2344 payload: request.payload,
2345 destTileX: request.destTileX,
2346 destTileY: request.destTileY,
2347 dimensionId: request.dimensionId ?? OVERWORLD_ID
2348 });
2349 }
2350 catch
2351 {
2352 result = { accepted: false };
2353 }
2354 if (!result?.accepted)
2355 {
2356 this.workers[request.fromWorkerId].call({
2357 type: WorkerMessage.abortTransfer,
2358 entityId: request.entityId
2359 });
2360 continue;
2361 }
2362 this.workers[request.fromWorkerId].call({
2363 type: WorkerMessage.commitTransfer,
2364 entityId: request.entityId
2365 });
2366 this.#remember(result.entity, destWorkerId);
2367 events.push({
2368 type: "entity-move",
2369 entityId: request.entityId,
2370 fromTileX: request.fromTileX,
2371 fromTileY: request.fromTileY,
2372 fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId,
2373 tileX: result.entity.tileX,
2374 tileY: result.entity.tileY,
2375 dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID,
2376 gait: result.entity.gait
2377 });
2378 }
2379 return events;
2380 }
2381
2382 #syncAllReplicas ()
2383 {
2384 for (const [workerId, worker] of this.workers.entries())
2385 {
2386 const ownedKeys = new Set();
2387 for (const [key, owner] of this.regionOwner)
2388 {
2389 if (owner !== workerId)
2390 { continue; }
2391 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2392 for (const chunk of chunksInRegion(regionX, regionY))
2393 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); }
2394 }
2395 const replicas = [];
2396 for (const key of replicaNeededForOwnedChunks(ownedKeys))
2397 {
2398 if (ownedKeys.has(key))
2399 { continue; }
2400 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2401 replicas.push({
2402 chunkX,
2403 chunkY,
2404 dimensionId,
2405 data: this.#authoredChunk(chunkX, chunkY, dimensionId)
2406 });
2407 }
2408 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
2409 }
2410 }
2411
2412 #syncGhosts ()
2413 {
2414 const entities = [];
2415 for (const worker of this.workers)
2416 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
2417 for (const [workerId, worker] of this.workers.entries())
2418 {
2419 const ghosts = entities.filter((entity) =>
2420 {
2421 const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID);
2422 if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId)
2423 { return false; }
2424 return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim);
2425 });
2426 worker.call({ type: WorkerMessage.setGhosts, ghosts });
2427 }
2428 }
2429
2430 #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID)
2431 {
2432 const dim = normalizeDimensionId(dimensionId);
2433 const chunkX = tileToChunk(tileX);
2434 const chunkY = tileToChunk(tileY);
2435 for (const [key, owner] of this.regionOwner)
2436 {
2437 if (owner !== workerId)
2438 { continue; }
2439 const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key);
2440 if (regionDim !== dim)
2441 { continue; }
2442 for (const chunk of chunksInRegion(regionX, regionY))
2443 {
2444 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
2445 { return true; }
2446 }
2447 }
2448 return false;
2449 }
2450
2451 #allLoaders ()
2452 {
2453 const loaders = [];
2454 for (const worker of this.workers)
2455 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
2456 return loaders;
2457 }
2458
2459 #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID)
2460 {
2461 const dim = normalizeDimensionId(dimensionId);
2462 const votes = new Map();
2463 for (const loader of loaders)
2464 {
2465 const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
2466 if (loaderDim !== dim)
2467 { continue; }
2468 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
2469 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
2470 { continue; }
2471 const record = this.directory.get(loader.entityId);
2472 if (record?.workerId == null)
2473 { continue; }
2474 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
2475 }
2476 let best = null;
2477 let bestVotes = -1;
2478 for (const [workerId, count] of votes)
2479 {
2480 if (count > bestVotes)
2481 {
2482 best = workerId;
2483 bestVotes = count;
2484 }
2485 }
2486 return best;
2487 }
2488
2489 #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2490 {
2491 const dim = normalizeDimensionId(dimensionId);
2492 const pinned = this.pinRegion?.(regionX, regionY, dim);
2493 if (pinned != null)
2494 { return pinned; }
2495
2496 const neighborOwners = [];
2497 for (let dy = -1; dy <= 1; dy++)
2498 {
2499 for (let dx = -1; dx <= 1; dx++)
2500 {
2501 if (dx === 0 && dy === 0)
2502 { continue; }
2503 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim));
2504 if (owner != null)
2505 { neighborOwners.push(owner); }
2506 }
2507 }
2508
2509 const scores = this.workers.map((_, workerId) => ({
2510 workerId,
2511 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
2512 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
2513 }));
2514
2515 if (preferredWorkerId != null && scores[preferredWorkerId])
2516 {
2517 const preferred = scores[preferredWorkerId];
2518 if (preferred.neighbors > 0 || neighborOwners.length === 0)
2519 { return preferredWorkerId; }
2520 }
2521
2522 scores.sort((left, right) =>
2523 right.neighbors - left.neighbors
2524 || left.load - right.load
2525 || left.workerId - right.workerId
2526 );
2527 return scores[0].workerId;
2528 }
2529
2530 #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID)
2531 {
2532 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null;
2533 }
2534
2535 #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2536 {
2537 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId);
2538 }
2539
2540 #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID)
2541 {
2542 const dim = normalizeDimensionId(dimensionId);
2543 return chunksInRegion(regionX, regionY).map((coord) => ({
2544 chunkX: coord.chunkX,
2545 chunkY: coord.chunkY,
2546 dimensionId: dim,
2547 data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim)
2548 }));
2549 }
2550
2551 #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2552 {
2553 const dim = normalizeDimensionId(dimensionId);
2554 const key = chunkKey(chunkX, chunkY, dim);
2555 if (this.authoredCache.has(key))
2556 { return this.authoredCache.get(key); }
2557 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim);
2558 const dimRecord = this.getDimensionRecord(dim);
2559 const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId;
2560 const data = row
2561 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
2562 : createEmptyChunkData(defaultGroundTypeId);
2563 this.authoredCache.set(key, data);
2564 return data;
2565 }
2566
2567 #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2568 {
2569 const dim = normalizeDimensionId(dimensionId);
2570 const data = this.#authoredChunk(chunkX, chunkY, dim);
2571 return {
2572 chunkX,
2573 chunkY,
2574 dimensionId: dim,
2575 open: data.open,
2576 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open),
2577 grounds: data.grounds,
2578 blocks: data.blocks,
2579 light: data.light,
2580 entities: [],
2581 groundItems: []
2582 };
2583 }
2584
2585 #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID)
2586 {
2587 const dim = normalizeDimensionId(dimensionId);
2588 for (const record of this.directory.values())
2589 {
2590 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2591 if (record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2592 { return record.entityId; }
2593 }
2594 return null;
2595 }
2596
2597 #queueReplication (event)
2598 {
2599 if (event)
2600 { this.replication.push(event); }
2601 }
2602
2603 #stepSpawners ()
2604 {
2605 const events = [];
2606 for (const worker of this.workers)
2607 {
2608 const result = worker.call({ type: WorkerMessage.stepSpawners });
2609 for (const request of result?.spawnRequests ?? [])
2610 {
2611 try
2612 {
2613 this.spawnEntity(mobComponents(request), { requireResident: true });
2614 }
2615 catch
2616 { continue; }
2617 }
2618 }
2619 return events;
2620 }
2621
2622 #restoreGroundItems (regionX, regionY, workerId)
2623 {
2624 const bounds = regionTileBounds(regionX, regionY);
2625 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
2626 .filter((item) => item.expiresAt > this.now);
2627 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
2628 this.workers[workerId].call({
2629 type: WorkerMessage.setGroundItems,
2630 regionX,
2631 regionY,
2632 items
2633 });
2634 }
2635
2636 #persistGroundEvent (event)
2637 {
2638 if (event.type === "ground-item-appear")
2639 {
2640 this.stateDb.upsertGroundItem({
2641 groundItemId: event.groundItemId,
2642 tileX: event.tileX,
2643 tileY: event.tileY,
2644 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
2645 droppedAt: event.droppedAt ?? this.now,
2646 expiresAt: event.expiresAt,
2647 source: event.source ?? "player-drop",
2648 droppedByCharacterId: event.droppedByCharacterId ?? null
2649 });
2650 }
2651 if (event.type === "ground-item-despawn")
2652 { this.stateDb.deleteGroundItem(event.groundItemId); }
2653 }
2654
2655 #saveBag (entityId, workerId)
2656 {
2657 const record = this.directory.get(entityId);
2658 const bag = this.workers[workerId].call({
2659 type: WorkerMessage.inspectBag,
2660 entityId
2661 });
2662 if (!bag || !record?.characterId)
2663 { return; }
2664 this.#saveBagFromView(record.characterId, bag);
2665 const skills = this.workers[workerId].call({
2666 type: WorkerMessage.inspectSkills,
2667 entityId
2668 });
2669 if (skills)
2670 { this.stateDb.saveSkills(record.characterId, skills); }
2671 }
2672
2673 #applySkillsUpdated (event)
2674 {
2675 if (!event?.characterId || !event.stored)
2676 { return; }
2677 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
2678 this.pushSkills(event.characterId, event.skills ?? []);
2679 }
2680
2681 #applySpellsUpdated (event)
2682 {
2683 if (!event?.characterId || !event.stored)
2684 { return; }
2685 this.stateDb.saveSpells(event.characterId, event.stored);
2686 this.pushSpells(event.characterId, {
2687 spells: event.spells ?? [],
2688 autoCast: !!event.autoCast
2689 });
2690 }
2691
2692 #applySummonEntity (event)
2693 {
2694 const components = shadeSummonComponents({
2695 tileX: event.tileX | 0,
2696 tileY: event.tileY | 0,
2697 level: event.level | 0 || 1,
2698 ownerEntityId: event.ownerEntityId,
2699 expiresAt: event.expiresAt,
2700 dimensionId: event.dimensionId
2701 });
2702 try
2703 {
2704 const entityId = this.spawnEntity(components, { requireResident: true });
2705 if (entityId == null)
2706 { return []; }
2707 return [];
2708 }
2709 catch
2710 {
2711 return [];
2712 }
2713 }
2714
2715 #skillLevelUpEvents (event)
2716 {
2717 const levelUps = event?.levelUps ?? [];
2718 if (!levelUps.length)
2719 { return []; }
2720 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
2721 if (entityId == null)
2722 { return []; }
2723 const record = this.directory.get(entityId);
2724 const tileX = record?.tileX ?? 0;
2725 const tileY = record?.tileY ?? 0;
2726 return levelUps.map((levelUp) => ({
2727 type: "skill-level-up",
2728 entityId,
2729 characterId: event.characterId,
2730 tileX,
2731 tileY,
2732 skillId: levelUp.skillId,
2733 level: levelUp.level,
2734 previousLevel: levelUp.previousLevel,
2735 displayName: levelUp.displayName,
2736 icon: levelUp.icon
2737 }));
2738 }
2739
2740 #saveBagFromView (characterId, bag)
2741 {
2742 this.stateDb.saveBag(characterId, {
2743 inventory: bag.inventory,
2744 equipment: bag.equipment,
2745 vault: bag.vault,
2746 vaultReserved: bag.vaultReserved
2747 });
2748 }
2749
2750 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
2751 {
2752 const onlineId = this.characterEntities.get(issuerCharacterId);
2753 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
2754 if (!bag)
2755 { return { ok: false, error: "Issuer vault not found." }; }
2756 const reserved = [...(bag.vaultReserved ?? [])];
2757 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
2758 if (index < 0)
2759 { return { ok: false, error: "That cheque cannot be redeemed." }; }
2760 const [stack] = reserved.splice(index, 1);
2761 bag.vaultReserved = reserved;
2762 this.stateDb.saveBag(issuerCharacterId, bag);
2763 if (onlineId)
2764 {
2765 this.applyBag(onlineId, bag);
2766 this.pushInventory(issuerCharacterId, bag);
2767 }
2768 return { ok: true, stack };
2769 }
2770
2771 restoreChequeReservation (issuerCharacterId, stack)
2772 {
2773 const onlineId = this.characterEntities.get(issuerCharacterId);
2774 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
2775 if (!bag)
2776 { return; }
2777 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
2778 this.stateDb.saveBag(issuerCharacterId, bag);
2779 if (onlineId)
2780 {
2781 this.applyBag(onlineId, bag);
2782 this.pushInventory(issuerCharacterId, bag);
2783 }
2784 }
2785
2786 #remember (view, workerId)
2787 {
2788 if (!view)
2789 { return; }
2790 const previous = this.directory.get(view.entityId);
2791 this.directory.set(view.entityId, {
2792 ...view,
2793 workerId,
2794 // Keep simulation-only fields that publicEntityView does not carry.
2795 skullValue: previous?.skullValue ?? view.skullValue ?? 0
2796 });
2797 if (view.characterId)
2798 { this.characterEntities.set(view.characterId, view.entityId); }
2799 }
2800
2801 #applyMoveToDirectory (event)
2802 {
2803 const record = this.directory.get(event.entityId);
2804 if (!record)
2805 { return; }
2806 record.tileX = event.tileX;
2807 record.tileY = event.tileY;
2808 record.gait = event.gait;
2809 if (event.dimensionId != null)
2810 { record.dimensionId = normalizeDimensionId(event.dimensionId); }
2811 if (event.worldX != null)
2812 { record.worldX = event.worldX; }
2813 if (event.worldY != null)
2814 { record.worldY = event.worldY; }
2815 if (event.freeFlight != null)
2816 { record.freeFlight = !!event.freeFlight; }
2817 }
2818
2819 #forget (entityId)
2820 {
2821 const record = this.directory.get(entityId);
2822 if (record?.characterId)
2823 { this.characterEntities.delete(record.characterId); }
2824 this.directory.delete(entityId);
2825 }
2826}