BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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