BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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