BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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