BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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