import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js"; import { tileToChunk, tileToLocal, chunkKey, visibleChunkCoords, tileKey } from "../world/coordinates.js"; import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js"; import { EcsWorld } from "../ecs/world.js"; import { chunkBoundsAround, findPath } from "../navigation/astar.js"; import { closedNeighborEdges } from "../world/chunkFlags.js"; export class Simulation { constructor (worldDb, stateDb) { this.worldDb = worldDb; this.stateDb = stateDb; this.ecs = new EcsWorld(); this.chunks = new Map(); this.occupancy = new Map(); this.characterEntities = new Map(); this.commandQueue = []; this.movementTickCounter = 0; this.activeRevisionId = worldDb.getActiveRevisionId(); this.settings = worldDb.getSettings(this.activeRevisionId); this.tickIndex = 0; this.reloadWorld(); } reloadWorld () { this.activeRevisionId = this.worldDb.getActiveRevisionId(); this.settings = this.worldDb.getSettings(this.activeRevisionId); this.chunks.clear(); for (const entity of this.ecs.query("position")) { const pos = entity.position; this.#ensureChunk(tileToChunk(pos.tileX), tileToChunk(pos.tileY)); } } enqueue (sessionId, command) { this.commandQueue.push({ sessionId, command, receivedAt: Date.now() }); } step (now = Date.now()) { this.tickIndex += 1; const commands = this.commandQueue.splice(0); const events = []; for (const item of commands) { try { const produced = this.#handleCommand(item.sessionId, item.command) ?? []; events.push(...produced); } catch (error) { events.push({ sessionId: item.sessionId, type: "command-error", message: error.userFacing ? error.message : "Command failed." }); } } const movementHz = this.settings.walkTilesPerSecond * 2; const simHz = this.settings.simulationTickHz; const movementEvery = Math.max(1, Math.round(simHz / movementHz)); if (this.tickIndex % movementEvery === 0) { this.movementTickCounter += 1; events.push(...this.#stepMovement()); } return { now, events }; } worldTime (now = Date.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); const tileX = character.tile_x; const tileY = character.tile_y; if (!this.isEnterable(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; } character.tile_x = spawn.tileX; character.tile_y = spawn.tileY; this.stateDb.saveCharacterPosition(character.character_id, spawn.tileX, spawn.tileY, character.gait); } const id = this.ecs.entity(); this.ecs.add(id, "position", { tileX: character.tile_x, tileY: character.tile_y }); this.ecs.add(id, "movement", { gait: character.gait || GAIT.walk, path: [], walkCarry: 0 }); this.ecs.add(id, "appearance", { sex: character.sex, firstName: character.first_name, lastName: character.last_name }); this.ecs.add(id, "character", { characterId: character.character_id, accountId: character.account_id, sessionId }); this.characterEntities.set(character.character_id, id); this.#occupy(id, character.tile_x, character.tile_y); this.#ensureVisibleChunks(character.tile_x, character.tile_y); return id; } despawnCharacter (characterId) { const id = this.characterEntities.get(characterId); if (!id) { return; } const position = this.ecs.get(id, "position"); const movement = this.ecs.get(id, "movement"); if (position) { this.#vacate(id, position.tileX, position.tileY); this.stateDb.saveCharacterPosition(characterId, position.tileX, position.tileY, movement?.gait ?? GAIT.walk); } this.ecs.destroy(id); this.characterEntities.delete(characterId); } entityForCharacter (characterId) { return this.characterEntities.get(characterId) ?? null; } snapshotFor (entityId) { const position = this.ecs.get(entityId, "position"); if (!position) { return []; } const coords = visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS); return coords.map((coord) => this.#chunkSnapshot(coord.chunkX, coord.chunkY)); } findOpenSpawn () { const coords = this.worldDb.listChunkCoords(this.activeRevisionId); for (const coord of coords) { const data = this.#ensureChunk(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.#occupied(tileX, tileY)) { return { tileX, tileY }; } } } } return null; } isEnterable (tileX, tileY) { const data = this.#ensureChunk(tileToChunk(tileX), tileToChunk(tileY)); if (!data.open) { return false; } return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); } #handleCommand (sessionId, command) { switch (command.type) { case "move-to": return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY); case "set-gait": return this.#setGait(sessionId, command.characterId, command.gait); default: return []; } } #moveTo (sessionId, characterId, tileX, tileY) { const id = this.#requireOwnedEntity(sessionId, characterId); const position = this.ecs.get(id, "position"); const movement = this.ecs.get(id, "movement"); const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const path = findPath( position.tileX, position.tileY, tileX, tileY, (x, y) => this.#walkableFor(id, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); movement.path = path; movement.walkCarry = 0; return []; } #setGait (sessionId, characterId, gait) { if (gait !== GAIT.walk && gait !== GAIT.run) { const error = new Error("Gait must be walk or run."); error.userFacing = true; throw error; } const id = this.#requireOwnedEntity(sessionId, characterId); this.ecs.get(id, "movement").gait = gait; return []; } #requireOwnedEntity (sessionId, characterId) { const id = this.characterEntities.get(characterId); if (!id) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } const character = this.ecs.get(id, "character"); if (!character || character.sessionId !== sessionId) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } return id; } #stepMovement () { const events = []; for (const entity of this.ecs.query("position", "movement")) { const { id, position, movement } = entity; if (!movement.path.length) { continue; } const isWalk = movement.gait !== GAIT.run; if (isWalk) { movement.walkCarry = (movement.walkCarry + 1) % 2; if (movement.walkCarry !== 0) { continue; } } const next = movement.path[0]; if (!this.#walkableFor(id, next.x, next.y)) { continue; } const fromTileX = position.tileX; const fromTileY = position.tileY; this.#vacate(id, fromTileX, fromTileY); position.tileX = next.x; position.tileY = next.y; movement.path.shift(); this.#occupy(id, position.tileX, position.tileY); this.#ensureVisibleChunks(position.tileX, position.tileY); const character = this.ecs.get(id, "character"); events.push({ type: "entity-move", entityId: id, characterId: character?.characterId, fromTileX, fromTileY, tileX: position.tileX, tileY: position.tileY, gait: movement.gait }); } return events; } #walkableFor (entityId, tileX, tileY) { if (!this.isEnterable(tileX, tileY)) { return false; } const occupant = this.#occupied(tileX, tileY); return !occupant || occupant === entityId; } #ensureVisibleChunks (tileX, tileY) { for (const coord of visibleChunkCoords(tileToChunk(tileX), tileToChunk(tileY), VISIBLE_CHUNK_RADIUS)) { this.#ensureChunk(coord.chunkX, coord.chunkY); } } #ensureChunk (chunkX, chunkY) { const key = chunkKey(chunkX, chunkY); if (this.chunks.has(key)) { return this.chunks.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.chunks.set(key, data); return data; } #chunkSnapshot (chunkX, chunkY) { const data = this.#ensureChunk(chunkX, chunkY); const entities = []; for (const entity of this.ecs.query("position", "appearance")) { if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY) { continue; } const movement = this.ecs.get(entity.id, "movement"); const character = this.ecs.get(entity.id, "character"); entities.push({ entityId: entity.id, characterId: character?.characterId ?? null, tileX: entity.position.tileX, tileY: entity.position.tileY, gait: movement?.gait ?? GAIT.walk, sex: entity.appearance.sex, firstName: entity.appearance.firstName, lastName: entity.appearance.lastName }); } return { chunkX, chunkY, open: data.open, closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#ensureChunk(x, y).open), grounds: data.grounds, blocks: data.blocks, light: data.light, entities }; } #occupy (entityId, tileX, tileY) { this.occupancy.set(tileKey(tileX, tileY), entityId); } #vacate (entityId, tileX, tileY) { const key = tileKey(tileX, tileY); if (this.occupancy.get(key) === entityId) { this.occupancy.delete(key); } } #occupied (tileX, tileY) { return this.occupancy.get(tileKey(tileX, tileY)) ?? null; } }