BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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