BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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