BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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