BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 107.0 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 now: this.now,
2302 dropCarriedCoins: true,
2303 coinGroundItemId: this.nextGroundItemId++,
2304 drops: [
2305 {
2306 groundItemId: this.nextGroundItemId++,
2307 stack: attachOrigins({
2308 itemId: ItemId.bones,
2309 quantity: 1,
2310 origins: [{ origin: corpseOrigin, quantity: 1 }]
2311 })
2312 },
2313 {
2314 groundItemId: this.nextGroundItemId++,
2315 stack: attachOrigins({
2316 itemId: ItemId.skull,
2317 quantity: 1,
2318 origins: [{ origin: corpseOrigin, quantity: 1 }]
2319 })
2320 }
2321 ]
2322 });
2323 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
2324 {
2325 const skullEvent = this.refreshCharacterSkull(killerCharacterId, { force: true });
2326 if (skullEvent)
2327 { events.push(skullEvent); }
2328 }
2329 events.push({
2330 type: "entity-despawn",
2331 entityId: event.entityId,
2332 tileX: event.tileX,
2333 tileY: event.tileY,
2334 cause: "death"
2335 });
2336 for (const dropEvent of result?.events ?? [])
2337 {
2338 this.#persistGroundEvent(dropEvent);
2339 events.push(dropEvent);
2340 }
2341 if (result?.private)
2342 {
2343 this.#saveBagFromView(event.characterId, result.private);
2344 if (event.sessionId != null)
2345 {
2346 events.push({
2347 type: "inventory",
2348 sessionId: event.sessionId,
2349 ...result.private
2350 });
2351 }
2352 }
2353 const coinsDropped = coinsDroppedFromDeathEvents(events);
2354 if (this.combatLogouts.has(event.characterId | 0))
2355 { events.push(...this.#finishCombatLogoutDeath(event, coinsDropped)); }
2356 return events;
2357 }
2358
2359 #finishCombatLogoutDeath (event, coinsDropped)
2360 {
2361 const characterId = event.characterId | 0;
2362 const logout = this.combatLogouts.get(characterId);
2363 const events = [];
2364 if (logout?.pendingCowardice)
2365 {
2366 applyCombatLogoutCowardice(this, characterId, {
2367 coinsDropped,
2368 now: this.now
2369 });
2370 }
2371 dispatchChurchOfflineResurrectionLetter(
2372 this,
2373 characterId,
2374 event.tileX | 0,
2375 event.tileY | 0
2376 );
2377 try
2378 { events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); }
2379 catch
2380 {
2381 // Respawn can fail without an altar tile; still despawn the corpse session.
2382 }
2383 this.#restoreCombatLogoutAutoCast(characterId, logout);
2384 this.combatLogouts.delete(characterId);
2385 this.combatTracking.delete(characterId);
2386 this.despawnCharacter(characterId);
2387 return events;
2388 }
2389
2390 #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY)
2391 {
2392 const entityId = this.characterEntities.get(characterId);
2393 const record = entityId ? this.directory.get(entityId) : null;
2394 if (!record)
2395 {
2396 const error = new Error("Character is not in the world.");
2397 error.userFacing = true;
2398 throw error;
2399 }
2400 const tileX = doorwayTileX | 0;
2401 const tileY = doorwayTileY | 0;
2402 if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY))
2403 {
2404 const error = new Error("You are too far from that doorway.");
2405 error.userFacing = true;
2406 throw error;
2407 }
2408 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2409 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId);
2410 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
2411 if (block?.typeId !== BlockType.doorway)
2412 {
2413 const error = new Error("There is no doorway there.");
2414 error.userFacing = true;
2415 throw error;
2416 }
2417 const config = block.config && typeof block.config === "object" ? block.config : null;
2418 const targetRaw = config?.targetDimensionId;
2419 if (targetRaw == null || String(targetRaw).trim() === "")
2420 {
2421 const error = new Error("That doorway leads nowhere.");
2422 error.userFacing = true;
2423 throw error;
2424 }
2425 const targetDimensionId = normalizeDimensionId(targetRaw);
2426 const destTileX = Number(config.tileX);
2427 const destTileY = Number(config.tileY);
2428 if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY))
2429 {
2430 const error = new Error("That doorway leads nowhere.");
2431 error.userFacing = true;
2432 throw error;
2433 }
2434 const destX = destTileX | 0;
2435 const destY = destTileY | 0;
2436 if (!this.#isDimensionUsable(targetDimensionId))
2437 {
2438 const error = new Error("That place is no longer reachable.");
2439 error.userFacing = true;
2440 throw error;
2441 }
2442 if (!this.isEnterable(destX, destY, targetDimensionId))
2443 {
2444 const error = new Error("The other side is blocked.");
2445 error.userFacing = true;
2446 throw error;
2447 }
2448
2449 const events = [];
2450 if (this.quests)
2451 {
2452 const closed = this.quests.closeDialogue(characterId, "doorway");
2453 if (closed?.events?.length)
2454 { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); }
2455 }
2456
2457 const loader = { ...DEFAULT_CHUNK_LOADER };
2458 this.#ensureCoverage(destX, destY, loader, targetDimensionId);
2459 const result = this.workers[record.workerId].call({
2460 type: WorkerMessage.relocateEntity,
2461 entityId,
2462 tileX: destX,
2463 tileY: destY,
2464 dimensionId: targetDimensionId
2465 });
2466 if (!result?.accepted)
2467 {
2468 const error = new Error("Could not enter that doorway.");
2469 error.userFacing = true;
2470 throw error;
2471 }
2472 let moveEvents = [];
2473 if (result.transferRequest)
2474 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
2475 else if (result.event)
2476 {
2477 this.#applyMoveToDirectory(result.event);
2478 moveEvents = [result.event];
2479 const view = this.workers[record.workerId].call({
2480 type: WorkerMessage.inspect,
2481 entityId
2482 });
2483 if (view)
2484 { this.#remember(view, record.workerId); }
2485 }
2486 if (!moveEvents.length)
2487 {
2488 const error = new Error("Could not enter that doorway.");
2489 error.userFacing = true;
2490 throw error;
2491 }
2492 this.stateDb.saveCharacterPosition(
2493 characterId,
2494 destX,
2495 destY,
2496 record.gait ?? GAIT.walk,
2497 targetDimensionId
2498 );
2499 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
2500 this.syncCharacterConditionAccess(characterId);
2501 this.#recalculateActivation(this.now);
2502 this.#syncGhosts();
2503 const dimRecord = this.getDimensionRecord(targetDimensionId);
2504 events.push(...moveEvents, {
2505 type: "dimension-changed",
2506 sessionId,
2507 characterId,
2508 entityId,
2509 dimensionId: targetDimensionId,
2510 tileX: destX,
2511 tileY: destY,
2512 lightingMode: dimRecord?.lightingMode ?? "dayNight",
2513 seasonMode: dimRecord?.seasonMode ?? "auto"
2514 });
2515 return events;
2516 }
2517
2518 #prayAtAltar (sessionId, characterId, altarTileX, altarTileY)
2519 {
2520 const entityId = this.characterEntities.get(characterId);
2521 const record = entityId ? this.directory.get(entityId) : null;
2522 if (!record)
2523 {
2524 const error = new Error("Character is not in the world.");
2525 error.userFacing = true;
2526 throw error;
2527 }
2528 const tileX = altarTileX | 0;
2529 const tileY = altarTileY | 0;
2530 if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY))
2531 {
2532 const error = new Error("You are too far from that altar.");
2533 error.userFacing = true;
2534 throw error;
2535 }
2536 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2537 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2538 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
2539 if (block?.typeId !== BlockType.churchAltar)
2540 {
2541 const error = new Error("There is no altar there.");
2542 error.userFacing = true;
2543 throw error;
2544 }
2545 this.stateDb.setCharacterRespawnAltar(characterId, tileX, tileY, dimensionId);
2546 return [{
2547 type: "toast",
2548 sessionId,
2549 characterId,
2550 message: "Altar set as respawn point."
2551 }];
2552 }
2553
2554 #respawnCharacter (sessionId, characterId)
2555 {
2556 const row = this.stateDb.getCharacter(characterId);
2557 if (!row?.is_dead)
2558 {
2559 const error = new Error("You are not dead.");
2560 error.userFacing = true;
2561 throw error;
2562 }
2563 const entityId = this.characterEntities.get(characterId);
2564 const record = entityId ? this.directory.get(entityId) : null;
2565 if (!record)
2566 {
2567 const error = new Error("Character is not in the world.");
2568 error.userFacing = true;
2569 throw error;
2570 }
2571 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2572 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId, characterId);
2573 if (!destination)
2574 {
2575 const error = new Error("No open tile is available for respawn.");
2576 error.userFacing = true;
2577 throw error;
2578 }
2579 const destDimensionId = normalizeDimensionId(destination.dimensionId ?? fromDimensionId);
2580 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
2581 const loader = { ...DEFAULT_CHUNK_LOADER };
2582 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destDimensionId);
2583 const result = this.workers[record.workerId].call({
2584 type: WorkerMessage.applyRespawn,
2585 entityId,
2586 sessionId,
2587 tileX: destination.tileX,
2588 tileY: destination.tileY,
2589 dimensionId: destDimensionId,
2590 maxHealth: playerMaxHealth(skills),
2591 maxStamina: playerMaxStamina(skills)
2592 });
2593 if (!result?.accepted)
2594 {
2595 const error = new Error("That respawn tile is no longer available.");
2596 error.userFacing = true;
2597 throw error;
2598 }
2599 let moveEvents = [];
2600 if (result.transferRequest)
2601 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
2602 else if (result.event)
2603 {
2604 this.#applyMoveToDirectory(result.event);
2605 moveEvents = [result.event];
2606 const view = this.workers[record.workerId].call({
2607 type: WorkerMessage.inspect,
2608 entityId
2609 });
2610 if (view)
2611 { this.#remember(view, record.workerId); }
2612 }
2613 if (!moveEvents.length)
2614 {
2615 const error = new Error("Respawn transfer failed.");
2616 error.userFacing = true;
2617 throw error;
2618 }
2619 this.stateDb.setCharacterDead(characterId, false);
2620 const respawnHealth = playerMaxHealth(skills);
2621 this.stateDb.saveCharacterHealth(characterId, respawnHealth);
2622 this.stateDb.saveCharacterPosition(
2623 characterId,
2624 destination.tileX,
2625 destination.tileY,
2626 record.gait ?? GAIT.walk,
2627 destDimensionId
2628 );
2629 if (destination.altar)
2630 {
2631 this.stateDb.setCharacterRespawnAltar(
2632 characterId,
2633 destination.altar.tileX,
2634 destination.altar.tileY,
2635 destination.altar.dimensionId
2636 );
2637 }
2638 this.stateDb.markDimensionVisited(characterId, destDimensionId);
2639 this.syncCharacterConditionAccess(characterId);
2640 this.#recalculateActivation(this.now);
2641 this.#syncGhosts();
2642 const skullEvent = this.refreshCharacterSkull(characterId, { force: true });
2643 const skullPoints = this.directory.get(entityId)?.skullValue | 0;
2644 const after = this.directory.get(entityId);
2645 const inspectWorkerId = after?.workerId ?? record.workerId;
2646 const spawnView = this.workers[inspectWorkerId].call({
2647 type: WorkerMessage.inspect,
2648 entityId
2649 });
2650 const spawn = spawnView
2651 ? replicationSpawn({ ...spawnView, skullValue: skullPoints })
2652 : null;
2653 const events = [
2654 ...moveEvents,
2655 ...(spawn ? [spawn] : []),
2656 ...(skullEvent ? [skullEvent] : []),
2657 {
2658 type: "player-respawned",
2659 entityId,
2660 characterId,
2661 sessionId,
2662 tileX: destination.tileX,
2663 tileY: destination.tileY,
2664 dimensionId: destDimensionId,
2665 health: playerMaxHealth(skills),
2666 maxHealth: playerMaxHealth(skills),
2667 stamina: playerMaxStamina(skills),
2668 maxStamina: playerMaxStamina(skills),
2669 skullValue: skullPoints
2670 }
2671 ];
2672 if (destDimensionId !== fromDimensionId)
2673 {
2674 const dimRecord = this.getDimensionRecord(destDimensionId);
2675 events.push({
2676 type: "dimension-changed",
2677 sessionId,
2678 characterId,
2679 entityId,
2680 dimensionId: destDimensionId,
2681 tileX: destination.tileX,
2682 tileY: destination.tileY,
2683 lightingMode: dimRecord?.lightingMode ?? "dayNight",
2684 seasonMode: dimRecord?.seasonMode ?? "auto"
2685 });
2686 }
2687 return events;
2688 }
2689
2690 #refreshAltarIndex ()
2691 {
2692 const altars = [];
2693 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
2694 {
2695 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
2696 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim);
2697 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2698 {
2699 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2700 {
2701 const block = data.blocks[localY * CHUNK_SIZE + localX];
2702 if (block?.typeId !== BlockType.churchAltar)
2703 { continue; }
2704 altars.push({
2705 tileX: coord.chunk_x * CHUNK_SIZE + localX,
2706 tileY: coord.chunk_y * CHUNK_SIZE + localY,
2707 dimensionId: dim
2708 });
2709 }
2710 }
2711 }
2712 this.altarTiles = altars;
2713 }
2714
2715 #chebyshevDistance (originX, originY, tileX, tileY)
2716 {
2717 return Math.max(Math.abs(tileX - originX), Math.abs(tileY - originY));
2718 }
2719
2720 #sortAltarsByDistance (altars, originX, originY)
2721 {
2722 return [...altars].sort((left, right) =>
2723 this.#chebyshevDistance(originX, originY, left.tileX, left.tileY)
2724 - this.#chebyshevDistance(originX, originY, right.tileX, right.tileY)
2725 );
2726 }
2727
2728 #findAdjacentOpenToAltar (altar, originX, originY, entityId)
2729 {
2730 const dimensionId = normalizeDimensionId(altar.dimensionId ?? OVERWORLD_ID);
2731 const adjacent = [];
2732 for (let dy = -1; dy <= 1; dy++)
2733 {
2734 for (let dx = -1; dx <= 1; dx++)
2735 {
2736 if (dx === 0 && dy === 0)
2737 { continue; }
2738 adjacent.push({
2739 tileX: altar.tileX + dx,
2740 tileY: altar.tileY + dy,
2741 dimensionId,
2742 altar: {
2743 tileX: altar.tileX | 0,
2744 tileY: altar.tileY | 0,
2745 dimensionId
2746 }
2747 });
2748 }
2749 }
2750 adjacent.sort((left, right) =>
2751 this.#chebyshevDistance(originX, originY, left.tileX, left.tileY)
2752 - this.#chebyshevDistance(originX, originY, right.tileX, right.tileY)
2753 );
2754 return adjacent.find((entry) =>
2755 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2756 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2757 ) ?? null;
2758 }
2759
2760 #findNearestAltarDestination (originX, originY, entityId, preferredDimensionId = null)
2761 {
2762 const preferred = preferredDimensionId != null
2763 ? normalizeDimensionId(preferredDimensionId)
2764 : null;
2765 const preferredAltars = preferred
2766 ? this.altarTiles.filter((altar) =>
2767 normalizeDimensionId(altar.dimensionId) === preferred)
2768 : [];
2769 const otherAltars = preferred
2770 ? this.altarTiles.filter((altar) =>
2771 normalizeDimensionId(altar.dimensionId) !== preferred)
2772 : this.altarTiles;
2773 for (const altar of this.#sortAltarsByDistance(preferredAltars, originX, originY))
2774 {
2775 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2776 if (tile)
2777 { return tile; }
2778 }
2779 for (const altar of this.#sortAltarsByDistance(otherAltars, originX, originY))
2780 {
2781 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2782 if (tile)
2783 { return tile; }
2784 }
2785 return null;
2786 }
2787
2788 #findSavedAltarDestination (characterId, originX, originY, entityId)
2789 {
2790 const saved = this.stateDb.getCharacterRespawnAltar(characterId);
2791 if (!saved)
2792 { return null; }
2793 const dimensionId = normalizeDimensionId(saved.dimensionId ?? OVERWORLD_ID);
2794 const altar = this.altarTiles.find((entry) =>
2795 (entry.tileX | 0) === (saved.tileX | 0)
2796 && (entry.tileY | 0) === (saved.tileY | 0)
2797 && normalizeDimensionId(entry.dimensionId) === dimensionId
2798 );
2799 if (!altar)
2800 { return null; }
2801 return this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2802 }
2803
2804 #findDeathTileFallback (originX, originY, entityId, dimensionId)
2805 {
2806 const dim = normalizeDimensionId(dimensionId);
2807 for (let radius = 0; radius <= 24; radius++)
2808 {
2809 for (let dy = -radius; dy <= radius; dy++)
2810 {
2811 for (let dx = -radius; dx <= radius; dx++)
2812 {
2813 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2814 { continue; }
2815 const tileX = originX + dx;
2816 const tileY = originY + dy;
2817 if (this.isEnterable(tileX, tileY, dim)
2818 && !this.#occupiedByOther(tileX, tileY, entityId, dim))
2819 { return { tileX, tileY, dimensionId: dim }; }
2820 }
2821 }
2822 }
2823 return null;
2824 }
2825
2826 #findRespawnDestination (originX, originY, entityId, characterId = null)
2827 {
2828 const record = this.directory.get(entityId);
2829 const deathDimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2830 const deathAltars = this.altarTiles.filter((altar) =>
2831 normalizeDimensionId(altar.dimensionId) === deathDimensionId
2832 );
2833 for (const altar of this.#sortAltarsByDistance(deathAltars, originX, originY))
2834 {
2835 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2836 if (tile)
2837 { return tile; }
2838 }
2839 if (characterId != null)
2840 {
2841 const saved = this.#findSavedAltarDestination(characterId, originX, originY, entityId);
2842 if (saved)
2843 { return saved; }
2844 }
2845 const otherAltars = this.altarTiles.filter((altar) =>
2846 normalizeDimensionId(altar.dimensionId) !== deathDimensionId
2847 );
2848 for (const altar of this.#sortAltarsByDistance(otherAltars, originX, originY))
2849 {
2850 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2851 if (tile)
2852 { return tile; }
2853 }
2854 return this.#findDeathTileFallback(originX, originY, entityId, deathDimensionId)
2855 ?? this.findOpenSpawn();
2856 }
2857
2858 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
2859 {
2860 const dim = normalizeDimensionId(dimensionId);
2861 for (const record of this.directory.values())
2862 {
2863 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2864 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2865 { return true; }
2866 }
2867 return false;
2868 }
2869
2870 #recalculateActivation (now)
2871 {
2872 const loaders = this.#allLoaders();
2873 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
2874
2875 for (const [key, count] of regionRes)
2876 {
2877 if (count <= 0)
2878 { continue; }
2879 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2880 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId);
2881 this.regionGraceUntil.delete(key);
2882 }
2883
2884 for (const [key] of [...this.regionOwner.entries()])
2885 {
2886 if ((regionRes.get(key) ?? 0) > 0)
2887 { continue; }
2888 if (!this.regionGraceUntil.has(key))
2889 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
2890 if (now >= this.regionGraceUntil.get(key))
2891 {
2892 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2893 this.#unloadRegion(regionX, regionY, dimensionId);
2894 }
2895 }
2896
2897 for (const [workerId, worker] of this.workers.entries())
2898 {
2899 const chunkKeys = [];
2900 for (const [key, count] of chunkSim)
2901 {
2902 if (count <= 0)
2903 { continue; }
2904 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2905 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId)
2906 { chunkKeys.push(key); }
2907 }
2908 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
2909 }
2910 this.#syncAllReplicas();
2911
2912 const nextSimulating = new Set();
2913 for (const [key, count] of chunkSim)
2914 {
2915 if (count > 0)
2916 { nextSimulating.add(key); }
2917 }
2918 let preheated = false;
2919 for (const key of nextSimulating)
2920 {
2921 if (!this.simulatingChunkKeys.has(key))
2922 {
2923 preheated = true;
2924 break;
2925 }
2926 }
2927 this.simulatingChunkKeys = nextSimulating;
2928 if (preheated)
2929 { this.#stepSpawners(); }
2930 }
2931
2932 #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
2933 {
2934 const dim = normalizeDimensionId(dimensionId);
2935 const coverage = loaderCoverage(tileX, tileY, loader, dim);
2936 let preferred = this.#ownerOfTile(tileX, tileY, dim);
2937 for (const region of coverage.residentRegions)
2938 {
2939 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim);
2940 if (preferred == null)
2941 { preferred = owner; }
2942 }
2943 }
2944
2945 #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2946 {
2947 const dim = normalizeDimensionId(dimensionId);
2948 const key = regionKey(regionX, regionY, dim);
2949 if (this.regionOwner.has(key))
2950 { return this.regionOwner.get(key); }
2951 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim);
2952 this.workers[workerId].call({
2953 type: WorkerMessage.assignRegion,
2954 regionX,
2955 regionY,
2956 dimensionId: dim,
2957 chunks: this.#regionChunkBlobs(regionX, regionY, dim)
2958 });
2959 this.regionOwner.set(key, workerId);
2960 this.#restorePersistent(regionX, regionY, workerId);
2961 this.#restoreGroundItems(regionX, regionY, workerId);
2962 return workerId;
2963 }
2964
2965 #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2966 {
2967 const dim = normalizeDimensionId(dimensionId);
2968 const key = regionKey(regionX, regionY, dim);
2969 const workerId = this.regionOwner.get(key);
2970 if (workerId == null)
2971 { return; }
2972 const bounds = regionTileBounds(regionX, regionY);
2973 const { dropped, groundItems } = this.workers[workerId].call({
2974 type: WorkerMessage.dropRegion,
2975 regionX,
2976 regionY,
2977 dimensionId: dim
2978 });
2979 const persistent = [];
2980 for (const record of dropped ?? [])
2981 {
2982 if (record.characterId)
2983 {
2984 this.stateDb.saveCharacterPosition(
2985 record.characterId,
2986 record.tileX,
2987 record.tileY,
2988 record.gait ?? GAIT.walk,
2989 record.dimensionId ?? OVERWORLD_ID
2990 );
2991 }
2992 if (record.persistent)
2993 { persistent.push(record); }
2994 this.#forget(record.entityId);
2995 }
2996 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
2997 for (const item of groundItems ?? [])
2998 { this.stateDb.upsertGroundItem(item); }
2999 this.regionOwner.delete(key);
3000 this.regionGraceUntil.delete(key);
3001 }
3002
3003 #restorePersistent (regionX, regionY, workerId)
3004 {
3005 const bounds = regionTileBounds(regionX, regionY);
3006 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
3007 for (const row of rows)
3008 {
3009 if (this.directory.has(row.entity_id))
3010 { continue; }
3011 const components = JSON.parse(row.components_blob);
3012 const view = this.workers[workerId].call({
3013 type: WorkerMessage.spawn,
3014 entityId: row.entity_id,
3015 components
3016 });
3017 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
3018 this.#remember(view, workerId);
3019 }
3020 }
3021
3022 #applyTransfers (requests)
3023 {
3024 const events = [];
3025 for (const request of requests)
3026 {
3027 const destWorkerId = this.#ensureRegion(
3028 request.toRegionX,
3029 request.toRegionY,
3030 request.fromWorkerId,
3031 request.dimensionId ?? OVERWORLD_ID
3032 );
3033 if (destWorkerId === request.fromWorkerId)
3034 {
3035 this.workers[request.fromWorkerId].call({
3036 type: WorkerMessage.abortTransfer,
3037 entityId: request.entityId
3038 });
3039 continue;
3040 }
3041 let result;
3042 try
3043 {
3044 result = this.workers[destWorkerId].call({
3045 type: WorkerMessage.applyTransfer,
3046 payload: request.payload,
3047 destTileX: request.destTileX,
3048 destTileY: request.destTileY,
3049 dimensionId: request.dimensionId ?? OVERWORLD_ID
3050 });
3051 }
3052 catch
3053 {
3054 result = { accepted: false };
3055 }
3056 if (!result?.accepted)
3057 {
3058 this.workers[request.fromWorkerId].call({
3059 type: WorkerMessage.abortTransfer,
3060 entityId: request.entityId
3061 });
3062 continue;
3063 }
3064 this.workers[request.fromWorkerId].call({
3065 type: WorkerMessage.commitTransfer,
3066 entityId: request.entityId
3067 });
3068 this.#remember(result.entity, destWorkerId);
3069 events.push({
3070 type: "entity-move",
3071 entityId: request.entityId,
3072 fromTileX: request.fromTileX,
3073 fromTileY: request.fromTileY,
3074 fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId,
3075 tileX: result.entity.tileX,
3076 tileY: result.entity.tileY,
3077 dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID,
3078 gait: result.entity.gait
3079 });
3080 }
3081 return events;
3082 }
3083
3084 #syncAllReplicas ()
3085 {
3086 for (const [workerId, worker] of this.workers.entries())
3087 {
3088 const ownedKeys = new Set();
3089 for (const [key, owner] of this.regionOwner)
3090 {
3091 if (owner !== workerId)
3092 { continue; }
3093 const { regionX, regionY, dimensionId } = parseRegionKey(key);
3094 for (const chunk of chunksInRegion(regionX, regionY))
3095 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); }
3096 }
3097 const replicas = [];
3098 for (const key of replicaNeededForOwnedChunks(ownedKeys))
3099 {
3100 if (ownedKeys.has(key))
3101 { continue; }
3102 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
3103 replicas.push({
3104 chunkX,
3105 chunkY,
3106 dimensionId,
3107 data: this.#authoredChunk(chunkX, chunkY, dimensionId)
3108 });
3109 }
3110 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
3111 }
3112 }
3113
3114 #syncGhosts ()
3115 {
3116 const entities = [];
3117 for (const worker of this.workers)
3118 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
3119 for (const [workerId, worker] of this.workers.entries())
3120 {
3121 const ghosts = entities.filter((entity) =>
3122 {
3123 const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID);
3124 if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId)
3125 { return false; }
3126 return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim);
3127 });
3128 worker.call({ type: WorkerMessage.setGhosts, ghosts });
3129 }
3130 }
3131
3132 #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID)
3133 {
3134 const dim = normalizeDimensionId(dimensionId);
3135 const chunkX = tileToChunk(tileX);
3136 const chunkY = tileToChunk(tileY);
3137 for (const [key, owner] of this.regionOwner)
3138 {
3139 if (owner !== workerId)
3140 { continue; }
3141 const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key);
3142 if (regionDim !== dim)
3143 { continue; }
3144 for (const chunk of chunksInRegion(regionX, regionY))
3145 {
3146 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
3147 { return true; }
3148 }
3149 }
3150 return false;
3151 }
3152
3153 #allLoaders ()
3154 {
3155 const loaders = [];
3156 for (const worker of this.workers)
3157 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
3158 return loaders;
3159 }
3160
3161 #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID)
3162 {
3163 const dim = normalizeDimensionId(dimensionId);
3164 const votes = new Map();
3165 for (const loader of loaders)
3166 {
3167 const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
3168 if (loaderDim !== dim)
3169 { continue; }
3170 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
3171 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
3172 { continue; }
3173 const record = this.directory.get(loader.entityId);
3174 if (record?.workerId == null)
3175 { continue; }
3176 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
3177 }
3178 let best = null;
3179 let bestVotes = -1;
3180 for (const [workerId, count] of votes)
3181 {
3182 if (count > bestVotes)
3183 {
3184 best = workerId;
3185 bestVotes = count;
3186 }
3187 }
3188 return best;
3189 }
3190
3191 #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
3192 {
3193 const dim = normalizeDimensionId(dimensionId);
3194 const pinned = this.pinRegion?.(regionX, regionY, dim);
3195 if (pinned != null)
3196 { return pinned; }
3197
3198 const neighborOwners = [];
3199 for (let dy = -1; dy <= 1; dy++)
3200 {
3201 for (let dx = -1; dx <= 1; dx++)
3202 {
3203 if (dx === 0 && dy === 0)
3204 { continue; }
3205 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim));
3206 if (owner != null)
3207 { neighborOwners.push(owner); }
3208 }
3209 }
3210
3211 const scores = this.workers.map((_, workerId) => ({
3212 workerId,
3213 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
3214 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
3215 }));
3216
3217 if (preferredWorkerId != null && scores[preferredWorkerId])
3218 {
3219 const preferred = scores[preferredWorkerId];
3220 if (preferred.neighbors > 0 || neighborOwners.length === 0)
3221 { return preferredWorkerId; }
3222 }
3223
3224 scores.sort((left, right) =>
3225 right.neighbors - left.neighbors
3226 || left.load - right.load
3227 || left.workerId - right.workerId
3228 );
3229 return scores[0].workerId;
3230 }
3231
3232 #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID)
3233 {
3234 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null;
3235 }
3236
3237 #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
3238 {
3239 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId);
3240 }
3241
3242 #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID)
3243 {
3244 const dim = normalizeDimensionId(dimensionId);
3245 return chunksInRegion(regionX, regionY).map((coord) => ({
3246 chunkX: coord.chunkX,
3247 chunkY: coord.chunkY,
3248 dimensionId: dim,
3249 data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim)
3250 }));
3251 }
3252
3253 #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
3254 {
3255 const dim = normalizeDimensionId(dimensionId);
3256 const key = chunkKey(chunkX, chunkY, dim);
3257 if (this.authoredCache.has(key))
3258 { return this.authoredCache.get(key); }
3259 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim);
3260 const dimRecord = this.getDimensionRecord(dim);
3261 const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId;
3262 const data = row
3263 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
3264 : createEmptyChunkData(defaultGroundTypeId);
3265 this.authoredCache.set(key, data);
3266 return data;
3267 }
3268
3269 #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID)
3270 {
3271 const dim = normalizeDimensionId(dimensionId);
3272 const data = this.#authoredChunk(chunkX, chunkY, dim);
3273 return {
3274 chunkX,
3275 chunkY,
3276 dimensionId: dim,
3277 open: data.open,
3278 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open),
3279 grounds: data.grounds,
3280 blocks: data.blocks,
3281 light: data.light,
3282 entities: [],
3283 groundItems: []
3284 };
3285 }
3286
3287 #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID)
3288 {
3289 const dim = normalizeDimensionId(dimensionId);
3290 for (const record of this.directory.values())
3291 {
3292 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
3293 if (record.tileX === tileX && record.tileY === tileY && recordDim === dim)
3294 { return record.entityId; }
3295 }
3296 return null;
3297 }
3298
3299 #queueReplication (event)
3300 {
3301 if (event)
3302 { this.replication.push(event); }
3303 }
3304
3305 #stepSpawners ()
3306 {
3307 const events = [];
3308 for (const worker of this.workers)
3309 {
3310 const result = worker.call({ type: WorkerMessage.stepSpawners });
3311 for (const request of result?.spawnRequests ?? [])
3312 {
3313 try
3314 {
3315 this.spawnEntity(mobComponents(request), { requireResident: true });
3316 }
3317 catch
3318 { continue; }
3319 }
3320 }
3321 return events;
3322 }
3323
3324 #restoreGroundItems (regionX, regionY, workerId)
3325 {
3326 const bounds = regionTileBounds(regionX, regionY);
3327 const items = [];
3328 for (const item of this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY))
3329 {
3330 if (item.expiresAt > this.now)
3331 {
3332 items.push(item);
3333 continue;
3334 }
3335 // Expired while unloaded: destroy and free any cheque reservation.
3336 this.#destroyExpiredGroundItem(item);
3337 }
3338 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
3339 this.workers[workerId].call({
3340 type: WorkerMessage.setGroundItems,
3341 regionX,
3342 regionY,
3343 items
3344 });
3345 }
3346
3347 /** Cheque paper that no longer exists must free reserved vault goods. */
3348 voidFilledCheque (stack)
3349 {
3350 if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque")
3351 { return { ok: false }; }
3352 const issuerId = stack.instance.issuerCharacterId | 0;
3353 const chequeId = stack.instance.chequeId;
3354 const release = this.releaseChequeReservation(issuerId, chequeId, stack.instance);
3355 if (!release?.ok || !release.stack)
3356 {
3357 // Already redeemed/voided — treat as success so despawn stays idempotent.
3358 return { ok: true, alreadyReleased: true };
3359 }
3360 const onlineId = this.characterEntities.get(issuerId);
3361 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerId);
3362 if (!bag)
3363 { return { ok: false, error: "Issuer vault not found." }; }
3364 const goodsDef = itemDefinition(release.stack.itemId);
3365 if (!goodsDef)
3366 { return { ok: false, error: "Unknown reserved goods." }; }
3367 const goods = attachOrigins({
3368 itemId: release.stack.itemId,
3369 quantity: release.stack.quantity,
3370 instance: release.stack.instance ? structuredClone(release.stack.instance) : null,
3371 origins: release.stack.origins
3372 });
3373 const inserted = insertStackGrowable(bag.vault ?? [], goods, goodsDef);
3374 bag.vault = inserted.slots;
3375 this.stateDb.saveBag(issuerId, bag);
3376 if (onlineId)
3377 {
3378 this.applyBag(onlineId, bag);
3379 this.pushInventory(issuerId, bag);
3380 }
3381 this.pendingPrivate.push({
3382 type: "toast",
3383 characterId: issuerId,
3384 message: "An uncashed cheque expired. Reserved goods returned to your vault."
3385 });
3386 return { ok: true };
3387 }
3388
3389 #destroyExpiredGroundItem (item)
3390 {
3391 if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
3392 { this.voidFilledCheque(item.stack); }
3393 this.stateDb.deleteGroundItem(item.groundItemId);
3394 }
3395
3396 #persistGroundEvent (event)
3397 {
3398 if (event.type === "ground-item-appear")
3399 {
3400 this.stateDb.upsertGroundItem({
3401 groundItemId: event.groundItemId,
3402 tileX: event.tileX,
3403 tileY: event.tileY,
3404 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
3405 droppedAt: event.droppedAt ?? this.now,
3406 expiresAt: event.expiresAt,
3407 source: event.source ?? "player-drop",
3408 droppedByCharacterId: event.droppedByCharacterId ?? null
3409 });
3410 }
3411 if (event.type === "ground-item-despawn")
3412 { this.stateDb.deleteGroundItem(event.groundItemId); }
3413 }
3414
3415 #saveBag (entityId, workerId)
3416 {
3417 const record = this.directory.get(entityId);
3418 const bag = this.workers[workerId].call({
3419 type: WorkerMessage.inspectBag,
3420 entityId
3421 });
3422 if (!bag || !record?.characterId)
3423 { return; }
3424 this.#saveBagFromView(record.characterId, bag);
3425 const skills = this.workers[workerId].call({
3426 type: WorkerMessage.inspectSkills,
3427 entityId
3428 });
3429 if (skills)
3430 { this.stateDb.saveSkills(record.characterId, skills); }
3431 }
3432
3433 #applySkillsUpdated (event)
3434 {
3435 if (!event?.characterId || !event.stored)
3436 { return; }
3437 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
3438 this.pushSkills(event.characterId, event.skills ?? [], event.combatLevel ?? 0);
3439 this.#markQuestReeval(event.characterId);
3440 }
3441
3442 #markQuestReeval (characterId)
3443 {
3444 const id = characterId | 0;
3445 if (!id || !this.quests)
3446 { return; }
3447 this.questReevalCharacterIds.add(id);
3448 }
3449
3450 #flushQuestReevaluations ()
3451 {
3452 if (!this.quests || this.questReevalCharacterIds.size === 0)
3453 { return []; }
3454 const out = [];
3455 // Effects from completions (e.g. giveItem) can mark again; iterate a few times.
3456 for (let pass = 0; pass < 8 && this.questReevalCharacterIds.size > 0; pass++)
3457 {
3458 const batch = [...this.questReevalCharacterIds];
3459 this.questReevalCharacterIds.clear();
3460 for (const characterId of batch)
3461 {
3462 out.push(...this.#mapQuestPrivateEvents(
3463 this.quests.reevaluateQuests(characterId),
3464 null,
3465 characterId
3466 ));
3467 }
3468 }
3469 this.questReevalCharacterIds.clear();
3470 return out;
3471 }
3472
3473 #applySpellsUpdated (event)
3474 {
3475 if (!event?.characterId || !event.stored)
3476 { return; }
3477 this.stateDb.saveSpells(event.characterId, event.stored);
3478 this.pushSpells(event.characterId, {
3479 spells: event.spells ?? [],
3480 favorites: event.favorites ?? [],
3481 autoCast: !!event.autoCast
3482 });
3483 }
3484
3485 #applySummonEntity (event)
3486 {
3487 const isFairy = event.mobTypeId === MobId.fairy || event.mobTypeId === "fairy";
3488 const components = isFairy
3489 ? jadeiteFairyComponents({
3490 tileX: event.tileX | 0,
3491 tileY: event.tileY | 0,
3492 level: event.level | 0 || 1,
3493 ownerEntityId: event.ownerEntityId,
3494 ownerCharacterId: event.ownerCharacterId ?? null,
3495 ownerName: event.ownerName,
3496 dimensionId: event.dimensionId
3497 })
3498 : shadeSummonComponents({
3499 tileX: event.tileX | 0,
3500 tileY: event.tileY | 0,
3501 level: event.level | 0 || 1,
3502 ownerEntityId: event.ownerEntityId,
3503 expiresAt: event.expiresAt,
3504 dimensionId: event.dimensionId
3505 });
3506 try
3507 {
3508 const entityId = this.spawnEntity(components, { requireResident: true });
3509 if (entityId == null)
3510 { return []; }
3511 return [];
3512 }
3513 catch
3514 {
3515 return [];
3516 }
3517 }
3518
3519 #applyJewelryTeleport (event)
3520 {
3521 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
3522 const record = entityId ? this.directory.get(entityId) : null;
3523 if (!record)
3524 { return []; }
3525 const destination = this.#findJewelryTeleportDestination(
3526 event.fromTileX | 0,
3527 event.fromTileY | 0,
3528 entityId,
3529 event.destination
3530 );
3531 if (!destination)
3532 {
3533 return [{
3534 type: "command-error",
3535 sessionId: event.sessionId,
3536 message: event.destination === "bank"
3537 ? "No bank is available."
3538 : "No church altar is available."
3539 }];
3540 }
3541 const loader = { ...DEFAULT_CHUNK_LOADER };
3542 this.#ensureCoverage(
3543 destination.tileX,
3544 destination.tileY,
3545 loader,
3546 destination.dimensionId ?? OVERWORLD_ID
3547 );
3548 const result = this.workers[record.workerId].call({
3549 type: WorkerMessage.relocateEntity,
3550 entityId,
3551 tileX: destination.tileX,
3552 tileY: destination.tileY,
3553 dimensionId: destination.dimensionId ?? OVERWORLD_ID
3554 });
3555 if (!result?.accepted)
3556 {
3557 return [{
3558 type: "command-error",
3559 sessionId: event.sessionId,
3560 message: "The destination is no longer available."
3561 }];
3562 }
3563 const events = [];
3564 if (result.transferRequest)
3565 { events.push(...this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }])); }
3566 else if (result.event)
3567 {
3568 this.#applyMoveToDirectory(result.event);
3569 events.push(result.event);
3570 const view = this.workers[record.workerId].call({
3571 type: WorkerMessage.inspect,
3572 entityId
3573 });
3574 if (view)
3575 { this.#remember(view, record.workerId); }
3576 }
3577 return events;
3578 }
3579
3580 #findJewelryTeleportDestination (originX, originY, entityId, destination)
3581 {
3582 if (destination === "church")
3583 {
3584 const record = this.directory.get(entityId);
3585 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3586 return this.#findNearestAltarDestination(originX, originY, entityId, dimensionId);
3587 }
3588 if (destination !== "bank")
3589 { return null; }
3590 const record = this.directory.get(entityId);
3591 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3592 const bank = this.courier?.nearestBank(originX, originY, dimensionId);
3593 if (!bank)
3594 { return null; }
3595 const adjacent = [];
3596 for (let dy = -1; dy <= 1; dy++)
3597 {
3598 for (let dx = -1; dx <= 1; dx++)
3599 {
3600 if (dx === 0 && dy === 0)
3601 { continue; }
3602 adjacent.push({
3603 tileX: bank.tileX + dx,
3604 tileY: bank.tileY + dy,
3605 dimensionId
3606 });
3607 }
3608 }
3609 adjacent.sort((left, right) =>
3610 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
3611 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
3612 );
3613 const tile = adjacent.find((entry) =>
3614 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
3615 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
3616 );
3617 return tile ?? null;
3618 }
3619
3620 #skillLevelUpEvents (event)
3621 {
3622 const levelUps = event?.levelUps ?? [];
3623 if (!levelUps.length)
3624 { return []; }
3625 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
3626 if (entityId == null)
3627 { return []; }
3628 const record = this.directory.get(entityId);
3629 const tileX = record?.tileX ?? 0;
3630 const tileY = record?.tileY ?? 0;
3631 return levelUps.map((levelUp) => ({
3632 type: "skill-level-up",
3633 entityId,
3634 characterId: event.characterId,
3635 tileX,
3636 tileY,
3637 skillId: levelUp.skillId,
3638 level: levelUp.level,
3639 previousLevel: levelUp.previousLevel,
3640 displayName: levelUp.displayName,
3641 icon: levelUp.icon
3642 }));
3643 }
3644
3645 #saveBagFromView (characterId, bag)
3646 {
3647 this.stateDb.saveBag(characterId, {
3648 inventory: bag.inventory,
3649 equipment: bag.equipment,
3650 vault: bag.vault,
3651 vaultReserved: bag.vaultReserved
3652 });
3653 this.#markQuestReeval(characterId);
3654 }
3655
3656 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
3657 {
3658 const onlineId = this.characterEntities.get(issuerCharacterId);
3659 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
3660 if (!bag)
3661 { return { ok: false, error: "Issuer vault not found." }; }
3662 const reserved = [...(bag.vaultReserved ?? [])];
3663 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
3664 if (index < 0)
3665 { return { ok: false, error: "That cheque cannot be redeemed." }; }
3666 const [stack] = reserved.splice(index, 1);
3667 bag.vaultReserved = reserved;
3668 this.stateDb.saveBag(issuerCharacterId, bag);
3669 if (onlineId)
3670 {
3671 this.applyBag(onlineId, bag);
3672 this.pushInventory(issuerCharacterId, bag);
3673 }
3674 return { ok: true, stack };
3675 }
3676
3677 restoreChequeReservation (issuerCharacterId, stack)
3678 {
3679 const onlineId = this.characterEntities.get(issuerCharacterId);
3680 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
3681 if (!bag)
3682 { return; }
3683 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
3684 this.stateDb.saveBag(issuerCharacterId, bag);
3685 if (onlineId)
3686 {
3687 this.applyBag(onlineId, bag);
3688 this.pushInventory(issuerCharacterId, bag);
3689 }
3690 }
3691
3692 #remember (view, workerId)
3693 {
3694 if (!view)
3695 { return; }
3696 const previous = this.directory.get(view.entityId);
3697 this.directory.set(view.entityId, {
3698 ...view,
3699 workerId,
3700 // Keep simulation-only fields that publicEntityView does not carry.
3701 skullValue: previous?.skullValue ?? view.skullValue ?? 0
3702 });
3703 if (view.characterId)
3704 { this.characterEntities.set(view.characterId, view.entityId); }
3705 }
3706
3707 #applyMoveToDirectory (event)
3708 {
3709 const record = this.directory.get(event.entityId);
3710 if (!record)
3711 { return; }
3712 record.tileX = event.tileX;
3713 record.tileY = event.tileY;
3714 record.gait = event.gait;
3715 if (event.dimensionId != null)
3716 { record.dimensionId = normalizeDimensionId(event.dimensionId); }
3717 if (event.worldX != null)
3718 { record.worldX = event.worldX; }
3719 if (event.worldY != null)
3720 { record.worldY = event.worldY; }
3721 if (event.freeFlight != null)
3722 { record.freeFlight = !!event.freeFlight; }
3723 }
3724
3725 #forget (entityId)
3726 {
3727 const record = this.directory.get(entityId);
3728 if (record?.characterId)
3729 { this.characterEntities.delete(record.characterId); }
3730 this.directory.delete(entityId);
3731 }
3732}