BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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