import { CHUNK_SIZE, DEFAULT_CHUNK_LOADER, GAIT, REGION_RUNTIME_STATE, VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js"; import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js"; import { chunkKey, chunkToRegion, chunksInRegion, parseChunkKey, parseRegionKey, regionKey, regionTileBounds, tileToChunk, tileToLocal, tileToRegion, visibleChunkCoords } from "../world/coordinates.js"; import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js"; import { closedNeighborEdges } from "../world/chunkFlags.js"; import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js"; import { InProcessWorker } from "./inProcessWorker.js"; import { ThreadWorker } from "./threadWorker.js"; import { WorkerMessage } from "./protocol.js"; import { replicaNeededForOwnedChunks } from "./workerWorld.js"; import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js"; import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js"; import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js"; import { mobComponents } from "./spawners.js"; import { shadeSummonComponents } from "../spells/summons.js"; import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js"; import { MobId } from "../../../shared/definitions/mobs.js"; import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js"; import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js"; import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { ItemId } from "../../../shared/definitions/items.js"; import { seasonIdAt } from "../../../shared/world/season.js"; import { CourierService } from "../courier/service.js"; import { MarketService } from "../market/service.js"; import { BountyService } from "../bounty/service.js"; import { BarberService } from "../barber/service.js"; import { findReservedChequeIndex } from "../items/bags.js"; import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js"; import { QuestContentCache } from "../quests/contentCache.js"; import { QuestRuntime } from "../quests/runtime.js"; import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; export class Simulation { constructor(worldDb, stateDb, options = {}) { this.worldDb = worldDb; this.stateDb = stateDb; this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2))); this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess"; this.pinRegion = options.pinRegion ?? null; this.nowFn = options.now ?? (() => Date.now()); this.workers = []; this.regionOwner = new Map(); this.regionGraceUntil = new Map(); this.directory = new Map(); this.characterEntities = new Map(); this.commandQueue = []; this.replication = []; this.pendingPrivate = []; this.courier = null; this.market = null; this.altarTiles = []; this.authoredCache = new Map(); this.simulatingChunkKeys = new Set(); this.nextEntityId = 1; this.nextGroundItemId = stateDb.nextGroundItemId(); this.tickIndex = 0; this.movementTickCounter = 0; this.lastTickAt = null; this.movementAccumulator = 0; this.activeRevisionId = worldDb.getActiveRevisionId(); this.settings = worldDb.getLiveSettings(); this.questContent = new QuestContentCache(worldDb); this.dimensions = this.#loadDimensionsCache(); this.quests = null; const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker; for (let workerId = 0; workerId < this.workerCount; workerId++) { const worker = new WorkerImpl(workerId); worker.call({ type: WorkerMessage.configure, settings: this.settings, activeRevisionId: this.activeRevisionId }); this.workers.push(worker); } for (const worker of this.workers) { if (!worker.world) { continue; } worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId); worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack); } this.courier = new CourierService({ stateDb: this.stateDb, worldDb: this.worldDb, simulation: this }); this.market = new MarketService({ stateDb: this.stateDb, worldDb: this.worldDb, simulation: this }); this.bounty = new BountyService(this.stateDb, this, this.courier); this.barber = new BarberService(this.stateDb, this); this.quests = new QuestRuntime({ stateDb: this.stateDb, content: this.questContent, simulation: this }); this.#refreshAltarIndex(); } get now () { return this.nowFn(); } applySettings (settings) { this.settings = { ...this.settings, ...settings }; this.#configureWorkers(); } /** Sparse last-sale map for editor base-price readouts. */ itemLastSalesSnapshot () { return this.market?.snapshot?.() ?? {}; } syncItemLastSales (lastSales) { const sales = {}; for (const [itemId, sale] of lastSales?.entries?.() ?? []) { sales[String(itemId)] = sale; } for (const worker of this.workers) { worker.call({ type: WorkerMessage.setItemLastSales, sales }); } } reloadWorld () { this.activeRevisionId = this.worldDb.getActiveRevisionId(); this.settings = this.worldDb.getLiveSettings(); this.dimensions = this.#loadDimensionsCache(); this.authoredCache.clear(); this.#configureWorkers(); for (const [key, workerId] of this.regionOwner) { const { regionX, regionY, dimensionId } = parseRegionKey(key); this.workers[workerId].call({ type: WorkerMessage.replaceRegionChunks, regionX, regionY, dimensionId, chunks: this.#regionChunkBlobs(regionX, regionY, dimensionId) }); } this.#syncAllReplicas(); this.courier?.refreshBankIndex(); this.courier?.refreshBountyOfficeIndex(); this.market?.refreshIndex(); this.questContent.reload(); this.quests?.closeAllSessions(); this.#refreshAltarIndex(); } enqueue (sessionId, command) { this.commandQueue.push({ sessionId, command, receivedAt: this.now }); } step (now = this.now) { this.tickIndex += 1; if ((this.tickIndex % 1200) === 0) { this.worldDb.purgeExpiredDimensions(now); } const events = []; const commands = this.commandQueue.splice(0); for (const item of commands) { try { events.push(...this.#routeCommand(item)); } catch (error) { events.push({ sessionId: item.sessionId, type: "command-error", message: error.userFacing ? error.message : "Command failed." }); } } this.#recalculateActivation(now); const simHz = Math.max(1, this.settings.simulationTickHz || 20); const expectedDt = 1 / simHz; const dt = (this.lastTickAt == null || now <= this.lastTickAt) ? expectedDt : Math.min(0.25, (now - this.lastTickAt) / 1000); this.lastTickAt = now; { const transfers = []; const remoteMelee = []; const remoteRanged = []; for (const worker of this.workers) { const result = worker.call({ type: WorkerMessage.stepSystems, now, dt }); for (const event of result?.events ?? []) { if (event.type === "remote-melee-resolve") { remoteMelee.push(event); continue; } if (event.type === "remote-ranged-resolve") { remoteRanged.push(event); continue; } if (event.type === "summon-entity") { events.push(...this.#applySummonEntity(event)); continue; } if (event.type === "jewelry-teleport-finish") { events.push(...this.#applyJewelryTeleport(event)); continue; } if (event.type === "entity-move") { this.#applyMoveToDirectory(event); } if (event.type === "entity-despawn") { this.#forget(event.entityId); } if (event.type === "skills-updated") { this.#applySkillsUpdated(event); events.push(...this.#skillLevelUpEvents(event)); continue; } if (event.type === "spells-updated") { this.#applySpellsUpdated(event); continue; } if (event.type === "inventory" && event.characterId) { this.#saveBagFromView(event.characterId, { inventory: event.inventory, equipment: event.equipment, vault: event.vault, vaultReserved: event.vaultReserved }); } if (event.type === "player-died") { events.push(...this.#applyPlayerDeath(event)); continue; } if (event.type === "mob-killed") { events.push(...this.#applyMobKilled(event)); continue; } if (event.type === "dialogue-walk-away") { const closed = this.quests?.closeDialogue(event.characterId, "walk-away"); events.push(...this.#mapQuestPrivateEvents( closed?.events ?? [], event.sessionId, event.characterId )); continue; } this.#persistGroundEvent(event); if (event.type !== "skills-updated") { events.push(event); } } for (const request of result?.transferRequests ?? []) { transfers.push({ ...request, fromWorkerId: worker.workerId }); } } for (const payload of remoteMelee) { events.push(...this.#applyRemoteMelee(payload)); } for (const payload of remoteRanged) { events.push(...this.#applyRemoteRanged(payload)); } if (transfers.length) { events.push(...this.#applyTransfers(transfers)); this.#recalculateActivation(now); } } const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2); this.movementAccumulator += dt * movementHz; while (this.movementAccumulator >= 1) { this.movementAccumulator -= 1; this.movementTickCounter += 1; const transfers = []; for (const worker of this.workers) { const result = worker.call({ type: WorkerMessage.stepMovement, now }); for (const event of result?.events ?? []) { if (event.type === "entity-move") { this.#applyMoveToDirectory(event); } if (event.type === "skills-updated") { this.#applySkillsUpdated(event); events.push(...this.#skillLevelUpEvents(event)); continue; } if (event.type === "spells-updated") { this.#applySpellsUpdated(event); continue; } this.#persistGroundEvent(event); if (event.type !== "skills-updated") { events.push(event); } } for (const request of result?.transferRequests ?? []) { transfers.push({ ...request, fromWorkerId: worker.workerId }); } } events.push(...this.#applyTransfers(transfers)); this.#recalculateActivation(now); } if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0) { events.push(...this.#stepSpawners()); } if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0) { this.#stepSkullDecay(); } if (this.courier) { events.push(...this.courier.step(now, dt)); } if (this.market) { events.push(...this.market.step(now)); } this.#syncGhosts(); events.push(...this.pendingPrivate.splice(0)); return { now, events, replication: this.drainReplication() }; } drainReplication () { return this.replication.splice(0); } worldTime (now = this.now) { const date = new Date(now); date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET); return { unixMs: now, worldUnixMs: date.getTime(), iso: date.toISOString(), hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600, season: seasonIdAt(now) }; } spawnCharacter (sessionId, character) { this.despawnCharacter(character.character_id); // Despawn may have just written the live tile; never trust a stale row snapshot. const row = this.stateDb.getCharacter(character.character_id) ?? character; let tileX = row.tile_x; let tileY = row.tile_y; let dimensionId = normalizeDimensionId(row.dimension_id ?? OVERWORLD_ID); const gait = row.gait || character.gait || GAIT.walk; // Soft-deleted / purged interiors eject to overworld spawn. if (!this.#isDimensionUsable(dimensionId)) { dimensionId = OVERWORLD_ID; const spawn = this.findOpenSpawn(); if (!spawn) { const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); error.userFacing = true; throw error; } tileX = spawn.tileX; tileY = spawn.tileY; this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId); } const preferred = this.#findResumeTile(tileX, tileY, 24, dimensionId); if (!preferred) { const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); error.userFacing = true; throw error; } if ( preferred.tileX !== tileX || preferred.tileY !== tileY || normalizeDimensionId(preferred.dimensionId ?? dimensionId) !== dimensionId ) { tileX = preferred.tileX; tileY = preferred.tileY; dimensionId = normalizeDimensionId(preferred.dimensionId ?? dimensionId); this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId); } const bag = this.stateDb.getBag(character.character_id) ?? { inventory: emptySlots(), equipment: emptyEquipment(), vault: [], vaultReserved: [] }; const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills(); const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells(); // Login floor: Health ≥ 5, every other skill ≥ 1 (persist if raised). if (enforceMinimumSkillLevels(skills)) { this.stateDb.saveSkills(character.character_id, skills); } const maxHealth = playerMaxHealth(skills); const maxStamina = playerMaxStamina(skills); const isDead = !!row.is_dead; const savedHealth = row.health_current; const currentHealth = isDead ? 0 : savedHealth != null ? Math.max(0, Math.min(maxHealth, savedHealth | 0)) : maxHealth; const entityId = this.nextEntityId++; const components = { position: { tileX, tileY, dimensionId }, movement: { gait, walkCarry: 0 }, path: { tiles: [] }, appearance: { sex: character.sex ?? row.sex, firstName: character.first_name ?? row.first_name, lastName: character.last_name ?? row.last_name, ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character)) }, character: { characterId: character.character_id ?? row.character_id, accountId: character.account_id ?? row.account_id }, networkIdentity: { sessionId }, chunkLoader: { ...DEFAULT_CHUNK_LOADER }, inventory: { slots: bag.inventory ?? emptySlots() }, equipment: bag.equipment ?? emptyEquipment(), vault: { slots: bag.vault ?? [], reserved: bag.vaultReserved ?? [] }, health: { current: currentHealth, max: maxHealth }, stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 }, combat: { targetEntityId: null, nextSwingAt: 0 }, skills, spells, spellcasting: { armedSpellId: null, repeatSpellId: null, repeatTargetEntityId: null, repeatTileX: null, repeatTileY: null, nextCastAt: 0, pendingCast: null }, chunkPresence: { chunkX: tileToChunk(tileX), chunkY: tileToChunk(tileY), dimensionId, sinceMs: this.now }, }; if (isDead) { components.dead = {}; } this.#ensureCoverage(tileX, tileY, components.chunkLoader, dimensionId); const workerId = this.#ownerOfTile(tileX, tileY, dimensionId); const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId, components }); this.#remember(view, workerId); this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id); this.stateDb.markDimensionVisited(character.character_id, dimensionId); this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view)); this.#recalculateActivation(this.now); this.#syncGhosts(); this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY); return entityId; } characterSkullValue (characterId, now = this.now) { const bounty = this.stateDb.getCharacterBounty(characterId); const killCounter = this.stateDb.peekKillCounter(characterId, now); return skullValue(bounty, killCounter); } refreshCharacterSkull (characterId, { force = false } = {}) { const id = characterId | 0; if (!id) { return null; } const state = this.stateDb.getKillCounterState(id); const elapsed = Math.max(0, this.now - (state.updatedAt | 0)); const decayed = decayKillCounter(state.killCounter, elapsed); if (decayed.killCounter !== state.killCounter) { this.stateDb.setKillCounter(id, decayed.killCounter, this.now); } const value = this.characterSkullValue(id); const entityId = this.characterEntities.get(id); const record = entityId ? this.directory.get(entityId) : null; if (!record) { return null; } if (!force && (record.skullValue | 0) === value) { return null; } record.skullValue = value; const event = { type: "entity-skull", entityId, skullValue: value, tileX: record.tileX, tileY: record.tileY, dimensionId: record.dimensionId ?? OVERWORLD_ID }; this.#queueReplication(event); return event; } #attachSkullToRecord (entityId, characterId) { const record = this.directory.get(entityId); if (!record) { return; } record.skullValue = this.characterSkullValue(characterId); } #stepSkullDecay () { for (const characterId of this.characterEntities.keys()) { const state = this.stateDb.getKillCounterState(characterId); if (!(state.killCounter > 0)) { continue; } this.refreshCharacterSkull(characterId); } } isCharacterOnline (characterId) { return this.characterEntities.has(characterId); } reattachCharacterSession (characterId, sessionId) { const entityId = this.characterEntities.get(characterId | 0); if (!entityId) { return null; } const record = this.directory.get(entityId); if (!record) { return null; } const result = this.workers[record.workerId].call({ type: WorkerMessage.reattachSession, characterId, sessionId }); if (!result?.ok) { return null; } this.market?.reattachSession?.(characterId, sessionId); return entityId; } spawnEntity (components, options = {}) { const entityId = options.entityId ?? this.nextEntityId++; this.nextEntityId = Math.max(this.nextEntityId, entityId + 1); const position = components.position; if (!position) { throw new Error("spawnEntity requires position."); } const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); position.dimensionId = dimensionId; if (options.requireResident) { const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId); if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId)) { return null; } const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId, components }); this.#remember(view, workerId); if (components.appearance) { this.#queueReplication(replicationSpawn(view)); } this.#syncGhosts(); return entityId; } if (components.chunkLoader) { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); } else { this.#ensureRegion( tileToRegion(position.tileX), tileToRegion(position.tileY), null, dimensionId ); } const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId); const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId, components }); this.#remember(view, workerId); if (components.appearance) { this.#queueReplication(replicationSpawn(view)); } this.#recalculateActivation(this.now); this.#syncGhosts(); return entityId; } despawnEntity (entityId) { const record = this.directory.get(entityId); if (!record) { return; } const dropped = this.workers[record.workerId].call({ type: WorkerMessage.despawn, entityId }); if (dropped) { this.#queueReplication(replicationDespawn(dropped)); } this.#forget(entityId); } chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) { const loaders = this.#allLoaders(); const { chunkSim } = accumulateLoaderRefs(loaders); return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0; } updateCourierFlight (entityId, flightPatch, now = this.now) { const record = this.directory.get(entityId); if (!record) { return { despawned: true, entityId }; } const tileX = Math.floor(flightPatch.x); const tileY = Math.floor(flightPatch.y); const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); const owner = this.#ownerOfTile(tileX, tileY, dimensionId); if (owner == null || owner !== record.workerId) { this.despawnEntity(entityId); return { despawned: true, entityId }; } const result = this.workers[owner].call({ type: WorkerMessage.updateFlight, entityId, flight: flightPatch, now }); if (result?.transferRequest) { const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]); this.#recalculateActivation(now); const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId); if (move) { this.#applyMoveToDirectory(move); return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } }; } this.despawnEntity(entityId); return { despawned: true, entityId }; } if (result?.event) { this.#applyMoveToDirectory(result.event); return { event: result.event }; } return null; } applyBag (entityId, bag) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.applyBag, entityId, bag }); } /** * Persist hair + patch live appearance; returns public view. */ setCharacterHair (characterId, hair) { const row = this.stateDb.updateCharacterHair(characterId, hair); const entityId = this.characterEntities.get(characterId); if (!entityId) { return { row, view: null }; } const fields = appearanceHairFields({ sex: row.sex, style: hair.style, hue: hair.hue, saturation: hair.saturation, darkness: hair.darkness }); const record = this.directory.get(entityId); if (!record) { return { row, view: null }; } const view = this.workers[record.workerId].call({ type: WorkerMessage.applyAppearance, entityId, appearance: fields }); if (view) { this.#remember(view, record.workerId); this.#queueReplication(replicationAppearance(view)); } return { row, view }; } pushSkills (characterId, skills, combatLevel) { this.pendingPrivate.push({ type: "skills", characterId, skills, combatLevel }); } pushSpells (characterId, payload) { this.pendingPrivate.push({ type: "spells", characterId, ...payload }); } skillsOf (entityId) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.inspectSkills, entityId }); } spellsOf (entityId) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.inspectSpells, entityId }); } staminaOf (entityId) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.inspectStamina, entityId }); } pushInventory (characterId, bag) { this.pendingPrivate.push({ type: "inventory", characterId, inventory: bag.inventory, equipment: bag.equipment, vault: bag.vault, vaultReserved: bag.vaultReserved }); } dispatchPigeon ({ characterId, destination, cargo }) { const entityId = this.characterEntities.get(characterId); const position = entityId ? this.positionOf(entityId) : null; if (!position) { const error = new Error("Enter the world before sending a pigeon."); error.userFacing = true; throw error; } return this.courier.dispatchFromPlayer({ characterId, originTileX: position.tileX, originTileY: position.tileY, destination, cargo }); } /** * Path an idle CE clerk to a staff-side station tile. */ stationExchangeClerk (stationTileX, stationTileY) { const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID); if (owner == null) { return { ok: false, reason: "unowned" }; } return this.workers[owner].call({ type: WorkerMessage.stationExchangeClerk, stationTileX, stationTileY }); } /** * When a player uses a marketplace counter, path idle CE clerks to the * opposite side of each adjacent counter (staff side). */ stationExchangeClerks (playerTileX, playerTileY) { const results = []; for (const tile of this.market?.marketTiles ?? []) { if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1) { continue; } if (tile.tileX === playerTileX && tile.tileY === playerTileY) { continue; } const stationTileX = tile.tileX + (tile.tileX - playerTileX); const stationTileY = tile.tileY + (tile.tileY - playerTileY); if (stationTileX === playerTileX && stationTileY === playerTileY) { continue; } results.push(this.stationExchangeClerk(stationTileX, stationTileY)); } return results; } /** Release a CE clerk stationed at the given staff-side tile. */ releaseExchangeClerk (stationTileX, stationTileY) { const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID); if (owner == null) { return { ok: false, reason: "unowned" }; } return this.workers[owner].call({ type: WorkerMessage.releaseExchangeClerk, stationTileX, stationTileY }); } despawnCharacter (characterId) { this.market?.leaveExchangeStations?.(characterId); const entityId = this.characterEntities.get(characterId); if (!entityId) { return; } const record = this.directory.get(entityId); if (!record) { this.characterEntities.delete(characterId); return; } this.#saveBag(entityId, record.workerId); const dropped = this.workers[record.workerId].call({ type: WorkerMessage.despawnCharacter, characterId }); if (dropped) { this.stateDb.saveCharacterPosition( characterId, dropped.tileX, dropped.tileY, dropped.gait ?? GAIT.walk, dropped.dimensionId ?? OVERWORLD_ID ); if (dropped.health != null) { this.stateDb.saveCharacterHealth(characterId, dropped.health); } this.#queueReplication(replicationDespawn(dropped)); } this.#forget(entityId); this.#recalculateActivation(this.now); this.#syncGhosts(); } entityForCharacter (characterId) { return this.characterEntities.get(characterId) ?? null; } entityRecord (entityId) { const record = this.directory.get(entityId); return record ? { ...record } : null; } positionOf (entityId) { const record = this.directory.get(entityId); return record ? { tileX: record.tileX, tileY: record.tileY, dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID) } : null; } bagOf (entityId) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.inspectBag, entityId }); } snapshotFor (entityId) { const record = this.directory.get(entityId); if (!record) { return []; } const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS); return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId)); } /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */ snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS) { const record = this.directory.get(entityId); if (!record) { return []; } const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); const centerChunkX = tileToChunk(record.tileX); const centerChunkY = tileToChunk(record.tileY); const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0); const entityKeys = new Set( visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS) .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId)) ); return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius) .map((coord) => { const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId); const staticOnly = !entityKeys.has(key); const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId); const entities = (snapshot.entities ?? []).map((entity) => { const known = this.directory.get(entity.entityId); if (!known || entity.characterId == null) { return entity; } return { ...entity, skullValue: known.skullValue | 0 }; }); return { ...snapshot, entities, staticOnly }; }); } snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim)); if (owner == null) { return this.#syntheticSnapshot(chunkX, chunkY, dim); } return this.workers[owner].call({ type: WorkerMessage.snapshotChunk, chunkX, chunkY, dimensionId: dim, staticOnly: !!staticOnly }); } findOpenSpawn () { const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID); for (const coord of coords) { const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID); if (!data.open) { continue; } for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const tileX = coord.chunk_x * CHUNK_SIZE + localX; const tileY = coord.chunk_y * CHUNK_SIZE + localY; if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID)) { return { tileX, tileY, dimensionId: OVERWORLD_ID }; } } } } return null; } /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */ #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); return this.#findNearbyEnterable(tileX, tileY, radius, dim) ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn()); } #isDimensionUsable (dimensionId) { const dim = normalizeDimensionId(dimensionId); if (dim === OVERWORLD_ID) { return true; } const record = this.getDimensionRecord(dim); if (!record) { return false; } if (record.deletedAt != null) { return false; } if (record.purgeAfter != null && record.purgeAfter <= this.now) { return false; } return true; } #loadDimensionsCache () { const map = new Map(); for (const dim of this.worldDb.listDimensions(this.activeRevisionId)) { map.set(dim.dimensionId, dim); } if (!map.has(OVERWORLD_ID)) { map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, { defaultGroundTypeId: this.settings.defaultGroundTypeId })); } return map; } getDimensionRecord (dimensionId) { const dim = normalizeDimensionId(dimensionId); return this.dimensions?.get(dim) ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim) ?? (dim === OVERWORLD_ID ? defaultDimensionRecord(OVERWORLD_ID, { defaultGroundTypeId: this.settings.defaultGroundTypeId }) : null); } listDimensionRecords () { return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))]; } #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); for (let radius = 0; radius <= maxRadius; radius++) { for (let dy = -radius; dy <= radius; dy++) { for (let dx = -radius; dx <= radius; dx++) { if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) { continue; } const tileX = originX + dx; const tileY = originY + dy; if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim)) { return { tileX, tileY, dimensionId: dim }; } } } } return null; } isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID) { const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId); if (!data.open) { return false; } return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); } debugWorld () { const loaders = this.#allLoaders(); const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); const simulatingChunks = [...chunkSim.entries()] .filter(([, count]) => count > 0) .map(([key]) => key) .sort(); return { tickIndex: this.tickIndex, workerCount: this.workers.length, workerMode: this.workerMode, simulatingChunks, regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({ ...parseRegionKey(key), workerId, state: REGION_RUNTIME_STATE.resident, refs: regionRes.get(key) ?? 0, graceUntil: this.regionGraceUntil.get(key) ?? null })), entities: [...this.directory.values()].map((entity) => ({ entityId: entity.entityId, workerId: entity.workerId, tileX: entity.tileX, tileY: entity.tileY, characterId: entity.characterId })) }; } async shutdown () { for (const characterId of [...this.characterEntities.keys()]) { this.despawnCharacter(characterId); } this.forceUnloadAll(); await Promise.all(this.workers.map((worker) => worker.terminate())); } forceUnloadAll () { for (const key of [...this.regionOwner.keys()]) { const { regionX, regionY } = parseRegionKey(key); this.#unloadRegion(regionX, regionY); } } #configureWorkers () { for (const worker of this.workers) { worker.call({ type: WorkerMessage.configure, settings: this.settings, activeRevisionId: this.activeRevisionId }); } } #routeCommand (item) { if (item.command.type === "respawn") { return this.#respawnCharacter(item.sessionId, item.command.characterId); } const routedCharacterId = item.command.characterId | 0; if (routedCharacterId && this.stateDb.getCharacter(routedCharacterId)?.is_dead) { // Queued intents after death (drop/use/send/craft/…) are discarded. return []; } if (item.command.type === "enter-doorway") { return this.#relocateCharacterThroughDoorway( item.sessionId, item.command.characterId, item.command.tileX, item.command.tileY ); } if ( item.command.type === "open-market" || item.command.type === "place-market-sell" || item.command.type === "place-market-buy" || item.command.type === "cancel-market-order" || item.command.type === "close-market" ) { const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now); return result?.events ?? []; } if ( item.command.type === "open-bounty" || item.command.type === "raise-bounty" || item.command.type === "get-character-bounty" || item.command.type === "close-bounty" ) { const result = this.bounty.handleCommand(item.sessionId, item.command); return result?.events ?? []; } if ( item.command.type === "open-barber" || item.command.type === "set-hair" || item.command.type === "close-barber" ) { const result = this.barber.handleCommand(item.sessionId, item.command); return result?.events ?? []; } if ( item.command.type === "dialogue-choose" || item.command.type === "dialogue-advance" || item.command.type === "close-dialogue" || item.command.type === "request-quests" ) { return this.#handleQuestCommand(item); } const entityId = this.characterEntities.get(item.command.characterId); const record = entityId ? this.directory.get(entityId) : null; if (!record) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } if (item.command.type === "drop-item" && item.command.groundItemId == null) { item.command.groundItemId = this.nextGroundItemId++; } if (item.command.type === "attack") { const targetRecord = this.directory.get(item.command.targetEntityId); if (!targetRecord) { const error = new Error("Target is not here."); error.userFacing = true; throw error; } const events = this.#finishRoutedCommand(item, record); if (targetRecord.workerId !== record.workerId) { this.workers[targetRecord.workerId].call({ type: WorkerMessage.remoteCombatEngage, attackerEntityId: record.entityId, targetEntityId: item.command.targetEntityId, now: item.receivedAt ?? this.now }); } return events; } return this.#finishRoutedCommand(item, record); } #finishRoutedCommand (item, record) { const result = this.workers[record.workerId].call({ type: WorkerMessage.command, sessionId: item.sessionId, command: item.command, now: item.receivedAt ?? this.now }); const view = this.workers[record.workerId].call({ type: WorkerMessage.inspect, entityId: record.entityId }); if (view) { this.#remember(view, record.workerId); } if (result?.private) { this.#saveBagFromView(item.command.characterId, result.private); } if (result?.appearanceChanged && view) { this.#queueReplication(replicationAppearance(view)); } if (result?.remainder) { this.stateDb.saveInheritance( this.stateDb.getCharacter(item.command.characterId).account_id, { slots: result.remainder } ); } for (const event of result?.events ?? []) { this.#persistGroundEvent(event); } const events = []; for (const event of result?.events ?? []) { if (event.type === "skills-updated") { this.#applySkillsUpdated(event); events.push(...this.#skillLevelUpEvents(event)); continue; } if (event.type === "spells-updated") { this.#applySpellsUpdated(event); continue; } if (event.type === "open-dialogue") { events.push(...this.#handleOpenDialogue(event)); continue; } events.push(event); } if (item.command.type === "attack" && item.command.targetEntityId != null) { events.push(...this.#mapQuestPrivateEvents( this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? [] )); } if (result?.private) { events.push({ type: "inventory", sessionId: item.sessionId, bank: !!result.bank, cauldron: result.cauldron, cauldronState: result.cauldronState ?? null, alchemyResult: result.alchemyResult ?? null, dyeConfirm: result.dyeConfirm ?? null, ...result.private }); } if (result?.statusEffectsChanged && view) { events.push({ type: "status-effects", sessionId: item.sessionId, characterId: view.characterId ?? item.command.characterId, effects: view.statusEffects ?? [], blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind") }); } if (result?.healthChanged && view) { events.push({ type: "entity-health", entityId: view.entityId, characterId: view.characterId ?? item.command.characterId, health: view.health, maxHealth: view.maxHealth, tileX: view.tileX, tileY: view.tileY }); } return events; } #applyRemoteMelee (payload) { const targetRecord = this.directory.get(payload.targetId); if (!targetRecord) { return []; } const result = this.workers[targetRecord.workerId].call({ ...payload, type: WorkerMessage.applyRemoteMelee }); const events = []; for (const event of result?.events ?? []) { if (event.type === "entity-despawn") { this.#forget(event.entityId); } if (event.type === "skills-updated") { this.#applySkillsUpdated(event); events.push(...this.#skillLevelUpEvents(event)); continue; } if (event.type === "spells-updated") { this.#applySpellsUpdated(event); continue; } if (event.type === "player-died") { events.push(...this.#applyPlayerDeath(event)); continue; } if (event.type === "mob-killed") { events.push(...this.#applyMobKilled(event)); continue; } this.#persistGroundEvent(event); if (event.type !== "skills-updated") { events.push(event); } } for (const forward of result?.forwards ?? []) { if (forward.type !== "forward-combat-xp") { continue; } const attackerRecord = this.directory.get(forward.entityId); if (!attackerRecord) { continue; } const xpResult = this.workers[attackerRecord.workerId].call({ type: WorkerMessage.applyCombatHitXp, entityId: forward.entityId, profile: forward.profile, damage: forward.damage }); for (const xpEvent of xpResult?.events ?? []) { if (xpEvent.type === "skills-updated") { this.#applySkillsUpdated(xpEvent); events.push(...this.#skillLevelUpEvents(xpEvent)); continue; } events.push(xpEvent); } } return events; } #applyRemoteRanged (payload) { const targetRecord = this.directory.get(payload.targetId); if (!targetRecord) { return []; } const result = this.workers[targetRecord.workerId].call({ ...payload, type: WorkerMessage.applyRemoteRanged }); const events = []; for (const event of result?.events ?? []) { if (event.type === "entity-despawn") { this.#forget(event.entityId); } if (event.type === "skills-updated") { this.#applySkillsUpdated(event); events.push(...this.#skillLevelUpEvents(event)); continue; } if (event.type === "spells-updated") { this.#applySpellsUpdated(event); continue; } if (event.type === "player-died") { events.push(...this.#applyPlayerDeath(event)); continue; } if (event.type === "mob-killed") { events.push(...this.#applyMobKilled(event)); continue; } this.#persistGroundEvent(event); if (event.type !== "skills-updated") { events.push(event); } } for (const forward of result?.forwards ?? []) { if (forward.type !== "forward-combat-xp") { continue; } const attackerRecord = this.directory.get(forward.entityId); if (!attackerRecord) { continue; } const xpResult = this.workers[attackerRecord.workerId].call({ type: WorkerMessage.applyCombatHitXp, entityId: forward.entityId, profile: forward.profile, damage: forward.damage }); for (const xpEvent of xpResult?.events ?? []) { if (xpEvent.type === "skills-updated") { this.#applySkillsUpdated(xpEvent); events.push(...this.#skillLevelUpEvents(xpEvent)); continue; } events.push(xpEvent); } } return events; } #handleQuestCommand (item) { const characterId = item.command.characterId | 0; const sessionId = item.sessionId; if (!this.quests) { return []; } if (item.command.type === "request-quests") { const snap = this.quests.questSnapshot(characterId); return [{ type: "quests-snapshot", sessionId, characterId, ...snap }]; } if (item.command.type === "close-dialogue") { const closed = this.quests.closeDialogue(characterId, "client"); return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId); } if (item.command.type === "dialogue-choose") { const result = this.quests.chooseDialogue(characterId, item.command.trigger); if (!result.ok) { const error = new Error(result.error || "Choice failed."); error.userFacing = true; throw error; } return this.#mapQuestPrivateEvents(result.events, sessionId, characterId); } if (item.command.type === "dialogue-advance") { const result = this.quests.advanceDialogue(characterId); if (!result.ok) { const error = new Error(result.error || "Cannot advance."); error.userFacing = true; throw error; } return this.#mapQuestPrivateEvents(result.events, sessionId, characterId); } return []; } #handleOpenDialogue (event) { const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId); if (!result.ok) { return [{ type: "toast", characterId: event.characterId, sessionId: event.sessionId, message: result.error || "Nothing to say." }]; } this.#pinDialogueNpc(event.entityId, event.characterId); return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId); } #pinDialogueNpc (entityId, characterId) { const record = this.directory.get(entityId | 0); if (!record) { return; } this.workers[record.workerId]?.call?.({ type: WorkerMessage.pinDialogue, entityId: entityId | 0, characterId: characterId | 0 }); } #unpinDialogueNpc (entityId, characterId) { const record = this.directory.get(entityId | 0); if (!record) { return; } this.workers[record.workerId]?.call?.({ type: WorkerMessage.unpinDialogue, entityId: entityId | 0, characterId: characterId | 0 }); } #mapQuestPrivateEvents (events, sessionId = null, characterId = null) { const out = []; let needSnapshot = false; for (const event of events ?? []) { const cid = event.characterId ?? characterId; const sid = sessionId ?? this.#sessionIdForCharacter(cid); if (event.type === "dialogueStep") { out.push({ type: "dialogue-step", sessionId: sid, characterId: cid, dialogueId: event.dialogueId, stepId: event.stepId, label: event.label, npcEntityId: event.npcEntityId, lines: event.lines }); } else if (event.type === "dialogueChoices") { out.push({ type: "dialogue-choices", sessionId: sid, characterId: cid, dialogueId: event.dialogueId, stepId: event.stepId, npcEntityId: event.npcEntityId, triggers: event.triggers }); } else if (event.type === "dialogueItemRewards") { out.push({ type: "dialogue-item-rewards", sessionId: sid, characterId: cid, dialogueId: event.dialogueId, stepId: event.stepId, npcEntityId: event.npcEntityId, messages: event.messages ?? [] }); } else if (event.type === "dialogueClose") { if (event.npcEntityId != null && cid != null) { this.#unpinDialogueNpc(event.npcEntityId, cid); } out.push({ type: "dialogue-close", sessionId: sid, characterId: cid, reason: event.reason }); } else if (event.type === "questStepComplete") { out.push({ type: "quest-step-complete", sessionId: sid, characterId: cid, questId: event.questId, title: event.title }); needSnapshot = true; } else if (event.type === "questsDirty") { needSnapshot = true; } else if (event.type === "inventoryDirty" && cid != null) { const onlineId = this.characterEntities.get(cid | 0); if (onlineId) { const live = this.bagOf(onlineId); if (live) { this.pushInventory(cid, live); } } } } if (needSnapshot && characterId != null) { const snap = this.quests.questSnapshot(characterId); out.push({ type: "quests-snapshot", sessionId: sessionId ?? this.#sessionIdForCharacter(characterId), characterId, ...snap }); } return out; } #sessionIdForCharacter (characterId) { const entityId = this.characterEntities.get(characterId | 0); const record = entityId != null ? this.directory.get(entityId) : null; return record?.sessionId ?? null; } #applyMobKilled (event) { const out = [event]; const attackerRecord = this.directory.get(event.attackerId); const killerCharacterId = attackerRecord?.characterId ?? null; const killerPos = attackerRecord ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY } : null; if (killerCharacterId && this.quests) { out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, { mobTypeId: event.mobTypeId, spawnerId: event.spawnerId }))); } out.push(...this.#mapQuestPrivateEvents( this.quests?.interruptDialogueForEntity(event.entityId) ?? [] )); let bountyAwarded = 0; if (killerCharacterId && (event.bounty | 0) > 0) { bountyAwarded = event.bounty | 0; const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded); this.refreshCharacterSkull(killerCharacterId); out.push({ type: "toast", characterId: killerCharacterId, message: `Bounty +${bountyAwarded} (total ${total})` }); } if (killerCharacterId && killerPos) { if (bountyAwarded > 0) { this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); } if (event.townGuard) { this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); } } return out; } /** * Send up to `count` town guards at the killer. Prefer idle guards. * When `spawnerId` is set, only that spawner's guards are used. */ #dispatchTownGuards (targetEntityId, killerPos, spawnerId, count) { const want = Math.max(0, count | 0); if (want <= 0 || targetEntityId == null || !killerPos) { return; } const candidates = []; for (const worker of this.workers) { const result = worker.call({ type: WorkerMessage.listTownGuardsNear, tileX: killerPos.tileX, tileY: killerPos.tileY, spawnerId, limit: 32 }); for (const guard of result?.guards ?? []) { candidates.push(guard); } } candidates.sort((a, b) => Number(a.busy) - Number(b.busy)); let sent = 0; for (const guard of candidates) { if (sent >= want) { break; } if (guard.entityId === targetEntityId) { continue; } const record = this.directory.get(guard.entityId); if (!record) { continue; } this.workers[record.workerId].call({ type: WorkerMessage.engageTarget, attackerEntityId: guard.entityId, targetEntityId, now: this.now }); sent += 1; } } #applyPlayerDeath (event) { const record = this.directory.get(event.entityId); if (!record) { return [event]; } this.stateDb.setCharacterDead(event.characterId, true); this.stateDb.saveCharacterPosition( event.characterId, event.tileX, event.tileY, record.gait ?? GAIT.walk, record.dimensionId ?? OVERWORLD_ID ); this.bounty?.settleKill( event.characterId, event.attackerId, event.tileX, event.tileY ); const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null; const killerCharacterId = Number(attackerRecord?.characterId) || 0; if (killerCharacterId && killerCharacterId !== (event.characterId | 0)) { this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now); } const events = [event]; const closedDialogue = this.quests?.closeDialogue(event.characterId, "death"); if (closedDialogue?.events?.length) { events.push(...this.#mapQuestPrivateEvents( closedDialogue.events, event.sessionId, event.characterId )); } if (event.sessionId != null) { for (const commandType of ["cancel-craft", "cauldron-close"]) { try { this.workers[record.workerId].call({ type: WorkerMessage.command, sessionId: event.sessionId, command: { type: commandType, characterId: event.characterId }, now: this.now }); } catch { /* best-effort session cleanup */ } } } // Bounty is cleared instantly on non-friend PvP death; only kill-counter decays over time. const victimSkull = this.refreshCharacterSkull(event.characterId, { force: true }); if (victimSkull) { events.push(victimSkull); } for (const worker of this.workers) { worker.call({ type: WorkerMessage.clearCombat, entityId: event.entityId, targetEntityId: event.entityId }); } const victimName = `${record.firstName ?? "someone"} ${record.lastName ?? ""}`.trim() || "someone"; const killerName = `${attackerRecord?.firstName ?? ""} ${attackerRecord?.lastName ?? ""}`.trim() || "someone"; const corpseOrigin = lootOrigin(victimName, killerName); const result = this.workers[record.workerId].call({ type: WorkerMessage.spawnCorpseDrops, characterId: event.characterId, tileX: event.tileX, tileY: event.tileY, now: this.now, dropCarriedCoins: true, coinGroundItemId: this.nextGroundItemId++, drops: [ { groundItemId: this.nextGroundItemId++, stack: attachOrigins({ itemId: ItemId.bones, quantity: 1, origins: [{ origin: corpseOrigin, quantity: 1 }] }) }, { groundItemId: this.nextGroundItemId++, stack: attachOrigins({ itemId: ItemId.skull, quantity: 1, origins: [{ origin: corpseOrigin, quantity: 1 }] }) } ] }); if (killerCharacterId && killerCharacterId !== (event.characterId | 0)) { const skullEvent = this.refreshCharacterSkull(killerCharacterId, { force: true }); if (skullEvent) { events.push(skullEvent); } } events.push({ type: "entity-despawn", entityId: event.entityId, tileX: event.tileX, tileY: event.tileY }); for (const dropEvent of result?.events ?? []) { this.#persistGroundEvent(dropEvent); events.push(dropEvent); } if (result?.private) { this.#saveBagFromView(event.characterId, result.private); if (event.sessionId != null) { events.push({ type: "inventory", sessionId: event.sessionId, ...result.private }); } } return events; } #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY) { const entityId = this.characterEntities.get(characterId); const record = entityId ? this.directory.get(entityId) : null; if (!record) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } const tileX = doorwayTileX | 0; const tileY = doorwayTileY | 0; if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY)) { const error = new Error("You are too far from that doorway."); error.userFacing = true; throw error; } const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId); const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)]; if (block?.typeId !== BlockType.doorway) { const error = new Error("There is no doorway there."); error.userFacing = true; throw error; } const config = block.config && typeof block.config === "object" ? block.config : null; const targetRaw = config?.targetDimensionId; if (targetRaw == null || String(targetRaw).trim() === "") { const error = new Error("That doorway leads nowhere."); error.userFacing = true; throw error; } const targetDimensionId = normalizeDimensionId(targetRaw); const destTileX = Number(config.tileX); const destTileY = Number(config.tileY); if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY)) { const error = new Error("That doorway leads nowhere."); error.userFacing = true; throw error; } const destX = destTileX | 0; const destY = destTileY | 0; if (!this.#isDimensionUsable(targetDimensionId)) { const error = new Error("That place is no longer reachable."); error.userFacing = true; throw error; } if (!this.isEnterable(destX, destY, targetDimensionId)) { const error = new Error("The other side is blocked."); error.userFacing = true; throw error; } const events = []; if (this.quests) { const closed = this.quests.closeDialogue(characterId, "doorway"); if (closed?.events?.length) { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); } } const loader = { ...DEFAULT_CHUNK_LOADER }; this.#ensureCoverage(destX, destY, loader, targetDimensionId); const result = this.workers[record.workerId].call({ type: WorkerMessage.relocateEntity, entityId, tileX: destX, tileY: destY, dimensionId: targetDimensionId }); if (!result?.accepted) { const error = new Error("Could not enter that doorway."); error.userFacing = true; throw error; } let moveEvents = []; if (result.transferRequest) { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); } else if (result.event) { this.#applyMoveToDirectory(result.event); moveEvents = [result.event]; const view = this.workers[record.workerId].call({ type: WorkerMessage.inspect, entityId }); if (view) { this.#remember(view, record.workerId); } } if (!moveEvents.length) { const error = new Error("Could not enter that doorway."); error.userFacing = true; throw error; } this.stateDb.saveCharacterPosition( characterId, destX, destY, record.gait ?? GAIT.walk, targetDimensionId ); this.stateDb.markDimensionVisited(characterId, targetDimensionId); this.#recalculateActivation(this.now); this.#syncGhosts(); const dimRecord = this.getDimensionRecord(targetDimensionId); events.push(...moveEvents, { type: "dimension-changed", sessionId, characterId, entityId, dimensionId: targetDimensionId, tileX: destX, tileY: destY, lightingMode: dimRecord?.lightingMode ?? "dayNight", seasonMode: dimRecord?.seasonMode ?? "auto" }); return events; } #respawnCharacter (sessionId, characterId) { const row = this.stateDb.getCharacter(characterId); if (!row?.is_dead) { const error = new Error("You are not dead."); error.userFacing = true; throw error; } const entityId = this.characterEntities.get(characterId); const record = entityId ? this.directory.get(entityId) : null; if (!record) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId); if (!destination) { const error = new Error("No open tile is available for respawn."); error.userFacing = true; throw error; } const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills(); const loader = { ...DEFAULT_CHUNK_LOADER }; this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID); const result = this.workers[record.workerId].call({ type: WorkerMessage.applyRespawn, entityId, sessionId, tileX: destination.tileX, tileY: destination.tileY, maxHealth: playerMaxHealth(skills), maxStamina: playerMaxStamina(skills) }); if (!result?.accepted) { const error = new Error("That respawn tile is no longer available."); error.userFacing = true; throw error; } let moveEvents = []; if (result.transferRequest) { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); } else if (result.event) { this.#applyMoveToDirectory(result.event); moveEvents = [result.event]; const view = this.workers[record.workerId].call({ type: WorkerMessage.inspect, entityId }); if (view) { this.#remember(view, record.workerId); } } if (!moveEvents.length) { const error = new Error("Respawn transfer failed."); error.userFacing = true; throw error; } this.stateDb.setCharacterDead(characterId, false); const respawnHealth = playerMaxHealth(skills); this.stateDb.saveCharacterHealth(characterId, respawnHealth); this.stateDb.saveCharacterPosition( characterId, destination.tileX, destination.tileY, record.gait ?? GAIT.walk, destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID ); this.#recalculateActivation(this.now); this.#syncGhosts(); const skullEvent = this.refreshCharacterSkull(characterId, { force: true }); const skullPoints = this.directory.get(entityId)?.skullValue | 0; const spawnView = this.workers[record.workerId].call({ type: WorkerMessage.inspect, entityId }); const spawn = spawnView ? replicationSpawn({ ...spawnView, skullValue: skullPoints }) : null; return [ ...moveEvents, ...(spawn ? [spawn] : []), ...(skullEvent ? [skullEvent] : []), { type: "player-respawned", entityId, characterId, sessionId, tileX: destination.tileX, tileY: destination.tileY, health: playerMaxHealth(skills), maxHealth: playerMaxHealth(skills), stamina: playerMaxStamina(skills), maxStamina: playerMaxStamina(skills), skullValue: skullPoints } ]; } #refreshAltarIndex () { const altars = []; for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId)) { const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID); const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim); for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const block = data.blocks[localY * CHUNK_SIZE + localX]; if (block?.typeId !== BlockType.churchAltar) { continue; } altars.push({ tileX: coord.chunk_x * CHUNK_SIZE + localX, tileY: coord.chunk_y * CHUNK_SIZE + localY, dimensionId: dim }); } } } this.altarTiles = altars; } #findRespawnDestination (originX, originY, entityId) { const record = this.directory.get(entityId); const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID); const ordered = [...this.altarTiles].sort((left, right) => Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) ); for (const altar of ordered) { const adjacent = []; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId }); } } adjacent.sort((left, right) => Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) ); const tile = adjacent.find((entry) => this.isEnterable(entry.tileX, entry.tileY, dimensionId) && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId) ); if (tile) { return tile; } } for (let radius = 0; radius <= 24; radius++) { for (let dy = -radius; dy <= radius; dy++) { for (let dx = -radius; dx <= radius; dx++) { if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) { continue; } const tileX = originX + dx; const tileY = originY + dy; if (this.isEnterable(tileX, tileY, dimensionId) && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId)) { return { tileX, tileY, dimensionId }; } } } } return this.findOpenSpawn(); } #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); for (const record of this.directory.values()) { const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim) { return true; } } return false; } #recalculateActivation (now) { const loaders = this.#allLoaders(); const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); for (const [key, count] of regionRes) { if (count <= 0) { continue; } const { regionX, regionY, dimensionId } = parseRegionKey(key); this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId); this.regionGraceUntil.delete(key); } for (const [key] of [...this.regionOwner.entries()]) { if ((regionRes.get(key) ?? 0) > 0) { continue; } if (!this.regionGraceUntil.has(key)) { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); } if (now >= this.regionGraceUntil.get(key)) { const { regionX, regionY, dimensionId } = parseRegionKey(key); this.#unloadRegion(regionX, regionY, dimensionId); } } for (const [workerId, worker] of this.workers.entries()) { const chunkKeys = []; for (const [key, count] of chunkSim) { if (count <= 0) { continue; } const { chunkX, chunkY, dimensionId } = parseChunkKey(key); if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId) { chunkKeys.push(key); } } worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys }); } this.#syncAllReplicas(); const nextSimulating = new Set(); for (const [key, count] of chunkSim) { if (count > 0) { nextSimulating.add(key); } } let preheated = false; for (const key of nextSimulating) { if (!this.simulatingChunkKeys.has(key)) { preheated = true; break; } } this.simulatingChunkKeys = nextSimulating; if (preheated) { this.#stepSpawners(); } } #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const coverage = loaderCoverage(tileX, tileY, loader, dim); let preferred = this.#ownerOfTile(tileX, tileY, dim); for (const region of coverage.residentRegions) { const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim); if (preferred == null) { preferred = owner; } } } #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const key = regionKey(regionX, regionY, dim); if (this.regionOwner.has(key)) { return this.regionOwner.get(key); } const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim); this.workers[workerId].call({ type: WorkerMessage.assignRegion, regionX, regionY, dimensionId: dim, chunks: this.#regionChunkBlobs(regionX, regionY, dim) }); this.regionOwner.set(key, workerId); this.#restorePersistent(regionX, regionY, workerId); this.#restoreGroundItems(regionX, regionY, workerId); return workerId; } #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const key = regionKey(regionX, regionY, dim); const workerId = this.regionOwner.get(key); if (workerId == null) { return; } const bounds = regionTileBounds(regionX, regionY); const { dropped, groundItems } = this.workers[workerId].call({ type: WorkerMessage.dropRegion, regionX, regionY, dimensionId: dim }); const persistent = []; for (const record of dropped ?? []) { if (record.characterId) { this.stateDb.saveCharacterPosition( record.characterId, record.tileX, record.tileY, record.gait ?? GAIT.walk, record.dimensionId ?? OVERWORLD_ID ); } if (record.persistent) { persistent.push(record); } this.#forget(record.entityId); } this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent); for (const item of groundItems ?? []) { this.stateDb.upsertGroundItem(item); } this.regionOwner.delete(key); this.regionGraceUntil.delete(key); } #restorePersistent (regionX, regionY, workerId) { const bounds = regionTileBounds(regionX, regionY); const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); for (const row of rows) { if (this.directory.has(row.entity_id)) { continue; } const components = JSON.parse(row.components_blob); const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId: row.entity_id, components }); this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1); this.#remember(view, workerId); } } #applyTransfers (requests) { const events = []; for (const request of requests) { const destWorkerId = this.#ensureRegion( request.toRegionX, request.toRegionY, request.fromWorkerId, request.dimensionId ?? OVERWORLD_ID ); if (destWorkerId === request.fromWorkerId) { this.workers[request.fromWorkerId].call({ type: WorkerMessage.abortTransfer, entityId: request.entityId }); continue; } let result; try { result = this.workers[destWorkerId].call({ type: WorkerMessage.applyTransfer, payload: request.payload, destTileX: request.destTileX, destTileY: request.destTileY, dimensionId: request.dimensionId ?? OVERWORLD_ID }); } catch { result = { accepted: false }; } if (!result?.accepted) { this.workers[request.fromWorkerId].call({ type: WorkerMessage.abortTransfer, entityId: request.entityId }); continue; } this.workers[request.fromWorkerId].call({ type: WorkerMessage.commitTransfer, entityId: request.entityId }); this.#remember(result.entity, destWorkerId); events.push({ type: "entity-move", entityId: request.entityId, fromTileX: request.fromTileX, fromTileY: request.fromTileY, fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId, tileX: result.entity.tileX, tileY: result.entity.tileY, dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID, gait: result.entity.gait }); } return events; } #syncAllReplicas () { for (const [workerId, worker] of this.workers.entries()) { const ownedKeys = new Set(); for (const [key, owner] of this.regionOwner) { if (owner !== workerId) { continue; } const { regionX, regionY, dimensionId } = parseRegionKey(key); for (const chunk of chunksInRegion(regionX, regionY)) { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); } } const replicas = []; for (const key of replicaNeededForOwnedChunks(ownedKeys)) { if (ownedKeys.has(key)) { continue; } const { chunkX, chunkY, dimensionId } = parseChunkKey(key); replicas.push({ chunkX, chunkY, dimensionId, data: this.#authoredChunk(chunkX, chunkY, dimensionId) }); } worker.call({ type: WorkerMessage.setReplicas, chunks: replicas }); } } #syncGhosts () { const entities = []; for (const worker of this.workers) { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); } for (const [workerId, worker] of this.workers.entries()) { const ghosts = entities.filter((entity) => { const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID); if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId) { return false; } return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim); }); worker.call({ type: WorkerMessage.setGhosts, ghosts }); } } #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); for (const [key, owner] of this.regionOwner) { if (owner !== workerId) { continue; } const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key); if (regionDim !== dim) { continue; } for (const chunk of chunksInRegion(regionX, regionY)) { if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2) { return true; } } } return false; } #allLoaders () { const loaders = []; for (const worker of this.workers) { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); } return loaders; } #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const votes = new Map(); for (const loader of loaders) { const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID); if (loaderDim !== dim) { continue; } const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim); if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY)) { continue; } const record = this.directory.get(loader.entityId); if (record?.workerId == null) { continue; } votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1); } let best = null; let bestVotes = -1; for (const [workerId, count] of votes) { if (count > bestVotes) { best = workerId; bestVotes = count; } } return best; } #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const pinned = this.pinRegion?.(regionX, regionY, dim); if (pinned != null) { return pinned; } const neighborOwners = []; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim)); if (owner != null) { neighborOwners.push(owner); } } } const scores = this.workers.map((_, workerId) => ({ workerId, neighbors: neighborOwners.filter((owner) => owner === workerId).length, load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length })); if (preferredWorkerId != null && scores[preferredWorkerId]) { const preferred = scores[preferredWorkerId]; if (preferred.neighbors > 0 || neighborOwners.length === 0) { return preferredWorkerId; } } scores.sort((left, right) => right.neighbors - left.neighbors || left.load - right.load || left.workerId - right.workerId ); return scores[0].workerId; } #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID) { return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null; } #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID) { return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId); } #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); return chunksInRegion(regionX, regionY).map((coord) => ({ chunkX: coord.chunkX, chunkY: coord.chunkY, dimensionId: dim, data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim) })); } #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const key = chunkKey(chunkX, chunkY, dim); if (this.authoredCache.has(key)) { return this.authoredCache.get(key); } const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim); const dimRecord = this.getDimensionRecord(dim); const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId; const data = row ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY) : createEmptyChunkData(defaultGroundTypeId); this.authoredCache.set(key, data); return data; } #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const data = this.#authoredChunk(chunkX, chunkY, dim); return { chunkX, chunkY, dimensionId: dim, open: data.open, closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open), grounds: data.grounds, blocks: data.blocks, light: data.light, entities: [], groundItems: [] }; } #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); for (const record of this.directory.values()) { const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); if (record.tileX === tileX && record.tileY === tileY && recordDim === dim) { return record.entityId; } } return null; } #queueReplication (event) { if (event) { this.replication.push(event); } } #stepSpawners () { const events = []; for (const worker of this.workers) { const result = worker.call({ type: WorkerMessage.stepSpawners }); for (const request of result?.spawnRequests ?? []) { try { this.spawnEntity(mobComponents(request), { requireResident: true }); } catch { continue; } } } return events; } #restoreGroundItems (regionX, regionY, workerId) { const bounds = regionTileBounds(regionX, regionY); const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY) .filter((item) => item.expiresAt > this.now); this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId()); this.workers[workerId].call({ type: WorkerMessage.setGroundItems, regionX, regionY, items }); } #persistGroundEvent (event) { if (event.type === "ground-item-appear") { this.stateDb.upsertGroundItem({ groundItemId: event.groundItemId, tileX: event.tileX, tileY: event.tileY, stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity }, droppedAt: event.droppedAt ?? this.now, expiresAt: event.expiresAt, source: event.source ?? "player-drop", droppedByCharacterId: event.droppedByCharacterId ?? null }); } if (event.type === "ground-item-despawn") { this.stateDb.deleteGroundItem(event.groundItemId); } } #saveBag (entityId, workerId) { const record = this.directory.get(entityId); const bag = this.workers[workerId].call({ type: WorkerMessage.inspectBag, entityId }); if (!bag || !record?.characterId) { return; } this.#saveBagFromView(record.characterId, bag); const skills = this.workers[workerId].call({ type: WorkerMessage.inspectSkills, entityId }); if (skills) { this.stateDb.saveSkills(record.characterId, skills); } } #applySkillsUpdated (event) { if (!event?.characterId || !event.stored) { return; } this.stateDb.saveSkills(event.characterId, { xp: event.stored }); this.pushSkills(event.characterId, event.skills ?? [], event.combatLevel ?? 0); } #applySpellsUpdated (event) { if (!event?.characterId || !event.stored) { return; } this.stateDb.saveSpells(event.characterId, event.stored); this.pushSpells(event.characterId, { spells: event.spells ?? [], favorites: event.favorites ?? [], autoCast: !!event.autoCast }); } #applySummonEntity (event) { const isFairy = event.mobTypeId === MobId.fairy || event.mobTypeId === "fairy"; const components = isFairy ? jadeiteFairyComponents({ tileX: event.tileX | 0, tileY: event.tileY | 0, level: event.level | 0 || 1, ownerEntityId: event.ownerEntityId, ownerCharacterId: event.ownerCharacterId ?? null, ownerName: event.ownerName, dimensionId: event.dimensionId }) : shadeSummonComponents({ tileX: event.tileX | 0, tileY: event.tileY | 0, level: event.level | 0 || 1, ownerEntityId: event.ownerEntityId, expiresAt: event.expiresAt, dimensionId: event.dimensionId }); try { const entityId = this.spawnEntity(components, { requireResident: true }); if (entityId == null) { return []; } return []; } catch { return []; } } #applyJewelryTeleport (event) { const entityId = event.entityId ?? this.characterEntities.get(event.characterId); const record = entityId ? this.directory.get(entityId) : null; if (!record) { return []; } const destination = this.#findJewelryTeleportDestination( event.fromTileX | 0, event.fromTileY | 0, entityId, event.destination ); if (!destination) { return [{ type: "command-error", sessionId: event.sessionId, message: event.destination === "bank" ? "No bank is available." : "No church altar is available." }]; } const loader = { ...DEFAULT_CHUNK_LOADER }; this.#ensureCoverage( destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID ); const result = this.workers[record.workerId].call({ type: WorkerMessage.relocateEntity, entityId, tileX: destination.tileX, tileY: destination.tileY, dimensionId: destination.dimensionId ?? OVERWORLD_ID }); if (!result?.accepted) { return [{ type: "command-error", sessionId: event.sessionId, message: "The destination is no longer available." }]; } const events = []; if (result.transferRequest) { events.push(...this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }])); } else if (result.event) { this.#applyMoveToDirectory(result.event); events.push(result.event); const view = this.workers[record.workerId].call({ type: WorkerMessage.inspect, entityId }); if (view) { this.#remember(view, record.workerId); } } return events; } #findJewelryTeleportDestination (originX, originY, entityId, destination) { if (destination === "church") { return this.#findRespawnDestination(originX, originY, entityId); } if (destination !== "bank") { return null; } const record = this.directory.get(entityId); const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID); const bank = this.courier?.nearestBank(originX, originY); if (!bank) { return null; } const adjacent = []; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } adjacent.push({ tileX: bank.tileX + dx, tileY: bank.tileY + dy, dimensionId }); } } adjacent.sort((left, right) => Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) ); const tile = adjacent.find((entry) => this.isEnterable(entry.tileX, entry.tileY, dimensionId) && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId) ); return tile ?? null; } #skillLevelUpEvents (event) { const levelUps = event?.levelUps ?? []; if (!levelUps.length) { return []; } const entityId = event.entityId ?? this.characterEntities.get(event.characterId); if (entityId == null) { return []; } const record = this.directory.get(entityId); const tileX = record?.tileX ?? 0; const tileY = record?.tileY ?? 0; return levelUps.map((levelUp) => ({ type: "skill-level-up", entityId, characterId: event.characterId, tileX, tileY, skillId: levelUp.skillId, level: levelUp.level, previousLevel: levelUp.previousLevel, displayName: levelUp.displayName, icon: levelUp.icon })); } #saveBagFromView (characterId, bag) { this.stateDb.saveBag(characterId, { inventory: bag.inventory, equipment: bag.equipment, vault: bag.vault, vaultReserved: bag.vaultReserved }); } releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null) { const onlineId = this.characterEntities.get(issuerCharacterId); const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); if (!bag) { return { ok: false, error: "Issuer vault not found." }; } const reserved = [...(bag.vaultReserved ?? [])]; const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId }); if (index < 0) { return { ok: false, error: "That cheque cannot be redeemed." }; } const [stack] = reserved.splice(index, 1); bag.vaultReserved = reserved; this.stateDb.saveBag(issuerCharacterId, bag); if (onlineId) { this.applyBag(onlineId, bag); this.pushInventory(issuerCharacterId, bag); } return { ok: true, stack }; } restoreChequeReservation (issuerCharacterId, stack) { const onlineId = this.characterEntities.get(issuerCharacterId); const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); if (!bag) { return; } bag.vaultReserved = [...(bag.vaultReserved ?? []), stack]; this.stateDb.saveBag(issuerCharacterId, bag); if (onlineId) { this.applyBag(onlineId, bag); this.pushInventory(issuerCharacterId, bag); } } #remember (view, workerId) { if (!view) { return; } const previous = this.directory.get(view.entityId); this.directory.set(view.entityId, { ...view, workerId, // Keep simulation-only fields that publicEntityView does not carry. skullValue: previous?.skullValue ?? view.skullValue ?? 0 }); if (view.characterId) { this.characterEntities.set(view.characterId, view.entityId); } } #applyMoveToDirectory (event) { const record = this.directory.get(event.entityId); if (!record) { return; } record.tileX = event.tileX; record.tileY = event.tileY; record.gait = event.gait; if (event.dimensionId != null) { record.dimensionId = normalizeDimensionId(event.dimensionId); } if (event.worldX != null) { record.worldX = event.worldX; } if (event.worldY != null) { record.worldY = event.worldY; } if (event.freeFlight != null) { record.freeFlight = !!event.freeFlight; } } #forget (entityId) { const record = this.directory.get(entityId); if (record?.characterId) { this.characterEntities.delete(record.characterId); } this.directory.delete(entityId); } }