import { CHUNK_SIZE, DEFAULT_CHUNK_LOADER, GAIT, REGION_RUNTIME_STATE, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.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 { mobComponents } from "./spawners.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.authoredCache = new Map(); 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(); 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); } } get now () { return this.nowFn(); } applySettings (settings) { this.settings = { ...this.settings, ...settings }; this.#configureWorkers(); } reloadWorld () { this.activeRevisionId = this.worldDb.getActiveRevisionId(); this.settings = this.worldDb.getLiveSettings(); this.authoredCache.clear(); this.#configureWorkers(); for (const [key, workerId] of this.regionOwner) { const { regionX, regionY } = parseRegionKey(key); this.workers[workerId].call({ type: WorkerMessage.replaceRegionChunks, chunks: this.#regionChunkBlobs(regionX, regionY) }); } this.#syncAllReplicas(); } enqueue (sessionId, command) { this.commandQueue.push({ sessionId, command, receivedAt: this.now }); } step (now = this.now) { this.tickIndex += 1; 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 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); } this.#persistGroundEvent(event); 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()); } this.#syncGhosts(); 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 }; } spawnCharacter (sessionId, character) { this.despawnCharacter(character.character_id); let tileX = character.tile_x; let tileY = character.tile_y; if (!this.isEnterable(tileX, tileY) || this.#occupiedTile(tileX, tileY)) { 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, character.gait); } const bag = this.stateDb.getBag(character.character_id) ?? { inventory: emptySlots(), equipment: emptyEquipment(), currency: 0, vault: emptySlots(), vaultCurrency: 0 }; const entityId = this.nextEntityId++; const components = { position: { tileX, tileY }, movement: { gait: character.gait || GAIT.walk, walkCarry: 0 }, path: { tiles: [] }, appearance: { sex: character.sex, firstName: character.first_name, lastName: character.last_name }, character: { characterId: character.character_id, accountId: character.account_id }, networkIdentity: { sessionId }, chunkLoader: { ...DEFAULT_CHUNK_LOADER }, inventory: { slots: bag.inventory ?? emptySlots() }, equipment: bag.equipment ?? emptyEquipment(), currency: { amount: bag.currency ?? 0 }, vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 } }; this.#ensureCoverage(tileX, tileY, components.chunkLoader); const workerId = this.#ownerOfTile(tileX, tileY); const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId, components }); this.#remember(view, workerId); this.#queueReplication(replicationSpawn(view)); this.#recalculateActivation(this.now); this.#syncGhosts(); 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."); } if (components.chunkLoader) { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); } else { this.#ensureRegion( tileToRegion(position.tileX), tileToRegion(position.tileY), null ); } const workerId = this.#ownerOfTile(position.tileX, position.tileY); 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; } despawnCharacter (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 ); 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 } : 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 coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS); return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY)); } snapshotChunk (chunkX, chunkY) { const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)); if (owner == null) { return this.#syntheticSnapshot(chunkX, chunkY); } return this.workers[owner].call({ type: WorkerMessage.snapshotChunk, chunkX, chunkY }); } findOpenSpawn () { const coords = this.worldDb.listChunkCoords(this.activeRevisionId); for (const coord of coords) { const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y); 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) && !this.#occupiedTile(tileX, tileY)) { return { tileX, tileY }; } } } } return null; } isEnterable (tileX, tileY) { const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY)); 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) { 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++; } 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, currency: 0 } ); } for (const event of result?.events ?? []) { this.#persistGroundEvent(event); } const events = [...(result?.events ?? [])]; if (result?.private) { events.push({ type: "inventory", sessionId: item.sessionId, bank: !!result.bank, ...result.private }); } return events; } #recalculateActivation (now) { const loaders = this.#allLoaders(); const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); for (const [key, count] of regionRes) { if (count <= 0) { continue; } const { regionX, regionY } = parseRegionKey(key); this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY)); 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 } = parseRegionKey(key); this.#unloadRegion(regionX, regionY); } } for (const [workerId, worker] of this.workers.entries()) { const chunkKeys = []; for (const [key, count] of chunkSim) { if (count <= 0) { continue; } const { chunkX, chunkY } = parseChunkKey(key); if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId) { chunkKeys.push(key); } } worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys }); } this.#syncAllReplicas(); } #ensureCoverage (tileX, tileY, loader) { const coverage = loaderCoverage(tileX, tileY, loader); let preferred = this.#ownerOfTile(tileX, tileY); for (const region of coverage.residentRegions) { const owner = this.#ensureRegion(region.regionX, region.regionY, preferred); if (preferred == null) { preferred = owner; } } } #ensureRegion (regionX, regionY, preferredWorkerId) { const key = regionKey(regionX, regionY); if (this.regionOwner.has(key)) { return this.regionOwner.get(key); } const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId); this.workers[workerId].call({ type: WorkerMessage.assignRegion, regionX, regionY, chunks: this.#regionChunkBlobs(regionX, regionY) }); this.regionOwner.set(key, workerId); this.#restorePersistent(regionX, regionY, workerId); this.#restoreGroundItems(regionX, regionY, workerId); return workerId; } #unloadRegion (regionX, regionY) { const key = regionKey(regionX, regionY); 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 }); const persistent = []; for (const record of dropped ?? []) { if (record.characterId) { this.stateDb.saveCharacterPosition( record.characterId, record.tileX, record.tileY, record.gait ?? GAIT.walk ); } 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); 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 }); } 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, tileX: result.entity.tileX, tileY: result.entity.tileY, 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 } = parseRegionKey(key); for (const chunk of chunksInRegion(regionX, regionY)) { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); } } const replicas = []; for (const key of replicaNeededForOwnedChunks(ownedKeys)) { if (ownedKeys.has(key)) { continue; } const { chunkX, chunkY } = parseChunkKey(key); replicas.push({ chunkX, chunkY, data: this.#authoredChunk(chunkX, chunkY) }); } 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) => { if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId) { return false; } return this.#nearWorker(workerId, entity.tileX, entity.tileY); }); worker.call({ type: WorkerMessage.setGhosts, ghosts }); } } #nearWorker (workerId, tileX, tileY) { const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); for (const [key, owner] of this.regionOwner) { if (owner !== workerId) { continue; } const { regionX, regionY } = parseRegionKey(key); 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) { const votes = new Map(); for (const loader of loaders) { const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader); 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) { const pinned = this.pinRegion?.(regionX, regionY); 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)); 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) { return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null; } #regionKeyForChunk (chunkX, chunkY) { return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY)); } #regionChunkBlobs (regionX, regionY) { return chunksInRegion(regionX, regionY).map((coord) => ({ chunkX: coord.chunkX, chunkY: coord.chunkY, data: this.#authoredChunk(coord.chunkX, coord.chunkY) })); } #authoredChunk (chunkX, chunkY) { const key = chunkKey(chunkX, chunkY); if (this.authoredCache.has(key)) { return this.authoredCache.get(key); } const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId); const data = row ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId) : createEmptyChunkData(this.settings.defaultGroundTypeId); this.authoredCache.set(key, data); return data; } #syntheticSnapshot (chunkX, chunkY) { const data = this.#authoredChunk(chunkX, chunkY); return { chunkX, chunkY, open: data.open, closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open), grounds: data.grounds, blocks: data.blocks, light: data.light, entities: [], groundItems: [] }; } #occupiedTile (tileX, tileY) { for (const record of this.directory.values()) { if (record.tileX === tileX && record.tileY === tileY) { 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)); } 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); } #saveBagFromView (characterId, bag) { this.stateDb.saveBag(characterId, { inventory: bag.inventory, equipment: bag.equipment, currency: bag.currency, vault: bag.vault, vaultCurrency: bag.vaultCurrency }); } #remember (view, workerId) { if (!view) { return; } this.directory.set(view.entityId, { ...view, workerId }); 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; } #forget (entityId) { const record = this.directory.get(entityId); if (record?.characterId) { this.characterEntities.delete(record.characterId); } this.directory.delete(entityId); } }