BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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