BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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