BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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