import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js"; import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; import { chunkKey, chunkToRegion, parseChunkKey, regionKey, tileKey, tileToChunk, tileToLocal, tileToRegion, tileIndex } from "../world/coordinates.js"; import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js"; import { closedNeighborEdges } from "../world/chunkFlags.js"; import { EcsWorld } from "../ecs/world.js"; import { Component } from "../ecs/components.js"; import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js"; import { chunkBoundsAround, findPath } from "../navigation/astar.js"; import { WorkerMessage } from "./protocol.js"; import { collectSpawnRequests } from "./spawners.js"; import { mobDefinition } from "../../../shared/definitions/mobs.js"; import { bagView, applyBagView, addGroundItem, expireGroundItems, groundItemsInChunk, groundItemsInRegion, handleItemCommand, removeGroundItem, publicGroundItem, setGroundItemsForRegion, stripCarriedCoinsForDeath } from "../items/bags.js"; import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js"; import { stepSummons } from "../spells/summons.js"; import { publicSpellsView } from "../../../shared/spells/state.js"; import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js"; import { handleGatherCommand, stepGather, cancelGather, clearOreRespawnsForChunk, clearTreeRespawnsForChunk, clearPlantRespawnsForChunk } from "../gathering/service.js"; import { handleCraftCommand, stepCrafting } from "../crafting/service.js"; import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js"; import { handleFishingCommand, stepFishing } from "../fishing/service.js"; import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js"; import { handleAlchemyCommand } from "../alchemy/service.js"; import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js"; import { applyRemoteMeleeSwing, applyRemoteRangedShot, attackProfileOf, clearEngage, engageTarget, ensureMobCombat, isUntargetable, queueMeleeApproach, queueStandInRangeApproach, resolveCombatTarget, silenceDeadPlayer, stepAggression, stepCombat, stepPassiveHealthRegen, chebyshev } from "../combat/service.js"; import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js"; import { SkillId } from "../../../shared/definitions/skills.js"; import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js"; import { syncCharacterChunkPresence } from "../navigation/chunkPresence.js"; import { STAMINA_REGEN_PER_SECOND, STAMINA_XP_PER_POINT_SPENT, staminaCostPerRunStep, publicStaminaView } from "../../../shared/stamina/rules.js"; import { stepCostForGround, PATH_GROUND_STEP_COST, SOFT_OCCUPIED_DWELL_MS } from "../../../shared/navigation/pathGround.js"; import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js"; import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js"; import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js"; import { stepStatusEffects } from "../statusEffects/service.js"; import { hasStatusEffect, StatusEffectType } from "../../../shared/statusEffects/rules.js"; export class WorkerWorld { constructor (workerId) { this.workerId = workerId; this.ecs = new EcsWorld(); this.chunks = new Map(); this.ownedRegions = new Set(); this.occupancy = new Map(); this.ghosts = new Map(); this.ghostOccupancy = new Map(); this.characterEntities = new Map(); this.frozen = new Set(); this.groundItems = new Map(); this.groundByTile = new Map(); this.oreRespawns = new Map(); this.treeRespawns = new Map(); this.campfireExpires = new Map(); this.fireSessions = new Map(); this.fishingSpotRespawns = new Map(); this.fishSessions = new Map(); this.pendingSpellImpacts = []; this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.activeRevisionId = 1; } handle (message) { switch (message.type) { case WorkerMessage.configure: return this.#configure(message); case WorkerMessage.assignRegion: return this.#assignRegion(message); case WorkerMessage.dropRegion: return this.#dropRegion(message); case WorkerMessage.replaceRegionChunks: return this.#replaceRegionChunks(message); case WorkerMessage.setReplicas: return this.#setReplicas(message); case WorkerMessage.setSimulatingChunks: return this.#setSimulatingChunks(message); case WorkerMessage.setGhosts: return this.#setGhosts(message); case WorkerMessage.spawn: return this.#spawn(message); case WorkerMessage.despawn: return this.#despawn(message.entityId); case WorkerMessage.despawnCharacter: return this.#despawnCharacter(message.characterId); case WorkerMessage.reattachSession: return this.#reattachSession(message.characterId, message.sessionId); case WorkerMessage.command: return this.#command(message); case WorkerMessage.stepMovement: return this.#stepMovement(message.now); case WorkerMessage.stepSystems: return this.#stepSystems(message.now, message.dt ?? (1 / 20)); case WorkerMessage.stepSpawners: return { spawnRequests: collectSpawnRequests(this, Date.now()) }; case WorkerMessage.setGroundItems: setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion); return { ok: true }; case WorkerMessage.inspectBag: return this.#inspectBag(message.entityId); case WorkerMessage.inspectSkills: return this.#inspectSkills(message.entityId); case WorkerMessage.inspectSpells: return this.#inspectSpells(message.entityId); case WorkerMessage.inspectStamina: return this.#inspectStamina(message.entityId); case WorkerMessage.applyBag: return this.#applyBag(message.entityId, message.bag); case WorkerMessage.applyAppearance: return this.#applyAppearance(message.entityId, message.appearance); case WorkerMessage.engageTarget: return this.#engageTargetMessage(message); case WorkerMessage.listTownGuardsNear: return this.#listTownGuardsNear(message); case WorkerMessage.updateFlight: return this.#updateFlight(message.entityId, message.flight, message.now); case WorkerMessage.chunkIsSimulating: return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId); case WorkerMessage.applyTransfer: return this.#applyTransfer(message); case WorkerMessage.commitTransfer: return this.#commitTransfer(message.entityId); case WorkerMessage.abortTransfer: return this.#abortTransfer(message.entityId); case WorkerMessage.snapshotChunk: return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId); case WorkerMessage.listLoaders: return this.#listLoaders(); case WorkerMessage.listPublicEntities: return this.#listPublicEntities(); case WorkerMessage.entitiesInRegion: return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId); case WorkerMessage.inspect: return publicEntityView(this.ecs, message.entityId); case WorkerMessage.remoteCombatEngage: return this.#remoteCombatEngage(message); case WorkerMessage.applyRemoteMelee: return this.#applyRemoteMelee(message); case WorkerMessage.applyRemoteRanged: return this.#applyRemoteRanged(message); case WorkerMessage.applyCombatHitXp: return this.#applyCombatHitXp(message); case WorkerMessage.spawnCorpseDrops: return this.#spawnCorpseDrops(message); case WorkerMessage.applyRespawn: return this.#applyRespawn(message); case WorkerMessage.relocateEntity: return this.#relocateEntity(message); case WorkerMessage.clearCombat: { clearEngage(this.ecs, message.entityId); const handle = this.ecs.handleOf(message.entityId); if (handle != null) { silenceDeadPlayer(this.ecs, handle); cancelGather(this.ecs, handle); clearFollow(this.ecs, message.entityId); } for (const entity of this.ecs.query(Component.combat)) { if (entity.combat.targetEntityId === message.targetEntityId) { entity.combat.targetEntityId = null; } } return { ok: true }; } case WorkerMessage.setItemLastSales: { this.itemLastSales = new Map(); for (const [key, sale] of Object.entries(message.sales ?? {})) { this.itemLastSales.set(Number(key), sale); } return { ok: true }; } case WorkerMessage.stationExchangeClerk: return this.#stationExchangeClerk(message); case WorkerMessage.releaseExchangeClerk: return this.#releaseExchangeClerk(message); case WorkerMessage.pinDialogue: return this.#pinDialogue(message.entityId, message.characterId); case WorkerMessage.unpinDialogue: return this.#unpinDialogue(message.entityId, message.characterId); default: throw new Error(`Unknown worker message ${message.type}`); } } ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID) { return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId)); } requireOwnedEntity (sessionId, characterId) { return this.#requireOwnedEntity(sessionId, characterId); } chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID) { return this.#chunkData(chunkX, chunkY, dimensionId); } #configure (message) { if (message.settings) { this.settings = { ...this.settings, ...message.settings }; } if (message.activeRevisionId != null) { this.activeRevisionId = message.activeRevisionId; } return { ok: true }; } #assignRegion (message) { const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim)); for (const chunk of message.chunks ?? []) { const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim); clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), { data: cloneChunkData(chunk.data), simulating: false, replica: false, dimensionId: chunkDim }); } return { ok: true }; } #replaceRegionChunks (message) { const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); for (const chunk of message.chunks ?? []) { const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim); const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim); const existing = this.chunks.get(key); clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); this.chunks.set(key, { data: cloneChunkData(chunk.data), simulating: existing?.simulating ?? false, replica: existing?.replica ?? false, dimensionId: chunkDim }); } return { ok: true }; } #dropRegion (message) { const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); const dropped = []; for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim)) { const components = record.payload?.components; if (components?.creature && !components?.character && components?.health) { components.health.current = components.health.max; } dropped.push(record); this.#destroyEntity(record.entityId); } const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion); for (const item of groundItems) { removeGroundItem(this, item.groundItemId); } for (const [key, chunk] of [...this.chunks.entries()]) { const { chunkX, chunkY, dimensionId } = parseChunkKey(key); if (chunk.replica) { continue; } if (dimensionId !== dim) { continue; } if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY) { clearOreRespawnsForChunk(this, chunkX, chunkY); clearTreeRespawnsForChunk(this, chunkX, chunkY); clearPlantRespawnsForChunk(this, chunkX, chunkY); this.chunks.delete(key); } } this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim)); return { dropped, groundItems }; } #setReplicas (message) { const keep = new Set(); for (const chunk of message.chunks ?? []) { const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID); const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim); keep.add(key); const existing = this.chunks.get(key); if (existing && !existing.replica) { continue; } this.chunks.set(key, { data: cloneChunkData(chunk.data), simulating: false, replica: true, dimensionId: chunkDim }); } for (const [key, chunk] of [...this.chunks.entries()]) { if (chunk.replica && !keep.has(key)) { this.chunks.delete(key); } } return { ok: true }; } #setSimulatingChunks (message) { const simulating = new Set(message.chunkKeys ?? []); for (const [key, chunk] of this.chunks) { if (chunk.replica) { chunk.simulating = false; continue; } chunk.simulating = simulating.has(key); } return { ok: true }; } #setGhosts (message) { this.ghosts.clear(); this.ghostOccupancy.clear(); for (const ghost of message.ghosts ?? []) { this.ghosts.set(ghost.entityId, ghost); const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID); const key = tileKey(ghost.tileX, ghost.tileY, dim); let set = this.ghostOccupancy.get(key); if (!set) { set = new Set(); this.ghostOccupancy.set(key, set); } set.add(ghost.entityId); } return { ok: true }; } #spawn (message) { const entityId = deserializeEntity(this.ecs, message); const handle = this.ecs.handleOf(entityId); const position = this.ecs.get(handle, Component.position); if (!position) { this.ecs.destroy(handle); throw new Error("Spawned entity is missing position."); } const flying = this.#isFlying(handle); if (!flying) { if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY)) { this.ecs.destroy(handle); const error = new Error("That tile is occupied."); error.userFacing = true; throw error; } this.#occupy(entityId, position.tileX, position.tileY); } const creature = this.ecs.get(handle, Component.creature); const def = creature ? mobDefinition(creature.mobTypeId) : null; if (def?.freeFlight) { ensureFlightComponent(this.ecs, handle, position, def); } const character = this.ecs.get(handle, Component.character); if (character?.characterId) { this.characterEntities.set(character.characterId, entityId); syncCharacterChunkPresence(this.ecs, handle, Date.now()); } return publicEntityView(this.ecs, entityId); } #despawn (entityId) { return this.#destroyEntity(entityId); } #despawnCharacter (characterId) { releaseShopBrowsersForCharacter(this, characterId); const entityId = this.characterEntities.get(characterId); if (!entityId) { return null; } return this.#destroyEntity(entityId); } #reattachSession (characterId, sessionId) { const entityId = this.characterEntities.get(characterId | 0); if (!entityId) { return { ok: false }; } const handle = this.ecs.handleOf(entityId); if (handle == null) { return { ok: false }; } this.ecs.add(handle, Component.networkIdentity, { sessionId }); return { ok: true, entityId }; } #destroyEntity (entityId) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } const view = publicEntityView(this.ecs, entityId); const position = this.ecs.get(handle, Component.position); const character = this.ecs.get(handle, Component.character); if (position && !this.#isFlying(handle)) { this.#vacate(entityId, position.tileX, position.tileY); } if (character?.characterId) { this.characterEntities.delete(character.characterId); } this.frozen.delete(entityId); this.ecs.destroy(handle); return view; } #command (message) { const { sessionId, command } = message; 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); case "attack": return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now()); case "cancel-attack": return this.#cancelAttack(sessionId, command.characterId); case "interact": return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose); case "follow": return this.#follow(sessionId, command.characterId, command.targetEntityId); case "cancel-follow": return this.#cancelFollow(sessionId, command.characterId); case "set-spell-favorite": case "set-spell-autocast": case "arm-spell": case "cancel-arm-spell": case "cast-spell-tile": case "cast-spell-entity": case "read-spellbook": return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] }; default: { const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now()); if (gather) { return gather; } const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now()); if (fire) { return fire; } const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now()); if (fishing) { return fishing; } const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now()); if (shearing) { return shearing; } const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now()); if (craft) { return craft; } const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now()); if (shop) { return shop; } const alchemy = handleAlchemyCommand(this, sessionId, command); if (alchemy) { return alchemy; } const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now()); return result ?? { events: [] }; } } } #spawnCorpseDrops (message) { const events = []; const drops = [...(message.drops ?? [])]; let privateBag = null; if (message.dropCarriedCoins) { const stripped = stripCarriedCoinsForDeath(this, message.characterId); privateBag = stripped.private; if (stripped.stack && message.coinGroundItemId != null) { drops.push({ groundItemId: message.coinGroundItemId, stack: stripped.stack }); } } for (const drop of drops) { const stack = drop.stack ?? { itemId: drop.itemId, quantity: 1 }; const item = { groundItemId: drop.groundItemId, tileX: message.tileX, tileY: message.tileY, stack, droppedAt: message.now, expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000), source: "player-death", droppedByCharacterId: message.characterId }; addGroundItem(this, item); events.push({ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }); } return { events, private: privateBag }; } #applyRespawn (message) { const handle = this.ecs.handleOf(message.entityId); if (handle == null || !this.ecs.has(handle, Component.dead)) { return { accepted: false }; } const position = this.ecs.get(handle, Component.position); const fromTileX = position.tileX; const fromTileY = position.tileY; const health = this.ecs.get(handle, Component.health); const stamina = this.ecs.get(handle, Component.stamina); if (health) { health.max = message.maxHealth; health.current = message.maxHealth; } if (stamina) { stamina.max = message.maxStamina; stamina.current = message.maxStamina; } else { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); } this.ecs.remove(handle, Component.dead); clearEngage(this.ecs, message.entityId); const path = this.ecs.get(handle, Component.path); if (path) { path.tiles = []; } clearFollow(this.ecs, message.entityId); const destRegionX = tileToRegion(message.tileX); const destRegionY = tileToRegion(message.tileY); const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) { this.frozen.add(message.entityId); return { accepted: true, transferRequest: { entityId: message.entityId, fromTileX, fromTileY, destTileX: message.tileX, destTileY: message.tileY, toRegionX: destRegionX, toRegionY: destRegionY, dimensionId, payload: serializeEntity(this.ecs, message.entityId) } }; } if (!this.isEnterable(message.tileX, message.tileY, dimensionId)) { return { accepted: false }; } this.#vacate(message.entityId, fromTileX, fromTileY); position.tileX = message.tileX; position.tileY = message.tileY; syncCharacterChunkPresence(this.ecs, handle, Date.now()); this.#occupy(message.entityId, position.tileX, position.tileY); return { accepted: true, event: { type: "entity-move", entityId: message.entityId, fromTileX, fromTileY, tileX: position.tileX, tileY: position.tileY, dimensionId, gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk } }; } /** Move an entity to a tile/dimension; clears path and updates occupancy. */ #relocateEntity (message) { const handle = this.ecs.handleOf(message.entityId); if (handle == null) { return { accepted: false }; } const position = this.ecs.get(handle, Component.position); if (!position) { return { accepted: false }; } const fromTileX = position.tileX; const fromTileY = position.tileY; const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); const destTileX = message.tileX | 0; const destTileY = message.tileY | 0; const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId); clearEngage(this.ecs, message.entityId); const path = this.ecs.get(handle, Component.path); if (path) { path.tiles = []; } clearFollow(this.ecs, message.entityId); const destRegionX = tileToRegion(destTileX); const destRegionY = tileToRegion(destTileY); if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) { this.frozen.add(message.entityId); const payload = serializeEntity(this.ecs, message.entityId); if (payload.components?.position) { payload.components.position.tileX = destTileX; payload.components.position.tileY = destTileY; payload.components.position.dimensionId = dimensionId; } return { accepted: true, transferRequest: { entityId: message.entityId, fromTileX, fromTileY, fromDimensionId, destTileX, destTileY, toRegionX: destRegionX, toRegionY: destRegionY, dimensionId, payload } }; } if (!this.isEnterable(destTileX, destTileY, dimensionId)) { return { accepted: false }; } if (!this.#isFlying(handle)) { this.#vacate(message.entityId, fromTileX, fromTileY); } position.tileX = destTileX; position.tileY = destTileY; position.dimensionId = dimensionId; syncCharacterChunkPresence(this.ecs, handle, Date.now()); if (!this.#isFlying(handle)) { this.#occupy(message.entityId, destTileX, destTileY); } return { accepted: true, event: { type: "entity-move", entityId: message.entityId, fromTileX, fromTileY, fromDimensionId, tileX: destTileX, tileY: destTileY, dimensionId, gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk } }; } #inspectBag (entityId) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } return bagView(this.ecs, handle); } #inspectSkills (entityId) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } const skills = this.ecs.get(handle, Component.skills); if (!skills?.xp) { return null; } return skills; } #inspectSpells (entityId) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } const spells = this.ecs.get(handle, Component.spells); const skills = this.ecs.get(handle, Component.skills); const casting = this.ecs.get(handle, Component.spellcasting); if (!spells) { return null; } return { spells: publicSpellsView(spells, skills), autoCast: !!spells.autoCast, armedSpellId: casting?.armedSpellId ?? null }; } #inspectStamina (entityId) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } const stamina = this.ecs.get(handle, Component.stamina); const movement = this.ecs.get(handle, Component.movement); if (!stamina) { return null; } return { ...publicStaminaView(stamina), gait: movement?.gait ?? GAIT.walk }; } #applyBag (entityId, bag) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } return applyBagView(this.ecs, handle, bag); } #applyAppearance (entityId, appearancePatch) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } const appearance = this.ecs.get(handle, Component.appearance); if (!appearance) { return null; } Object.assign(appearance, appearancePatch ?? {}); return publicEntityView(this.ecs, entityId); } #updateFlight (entityId, flightPatch, now = Date.now()) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } let flight = this.ecs.get(handle, Component.flight); if (!flight) { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); } else { Object.assign(flight, flightPatch); } const position = this.ecs.get(handle, Component.position); const movement = this.ecs.get(handle, Component.movement); const fromTileX = position.tileX; const fromTileY = position.tileY; const tileX = Math.floor(flight.x); const tileY = Math.floor(flight.y); position.tileX = tileX; position.tileY = tileY; syncCharacterChunkPresence(this.ecs, handle, now); const destRegionX = tileToRegion(tileX); const destRegionY = tileToRegion(tileY); const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) { this.frozen.add(entityId); return { transferRequest: { type: "transfer-request", entityId, fromTileX, fromTileY, destTileX: tileX, destTileY: tileY, toRegionX: destRegionX, toRegionY: destRegionY, dimensionId } }; } const dt = flight.lastAt && now > flight.lastAt ? Math.min(0.25, (now - flight.lastAt) / 1000) : 1 / 20; return { event: { type: "entity-move", entityId, fromTileX, fromTileY, tileX, tileY, worldX: flight.x, worldY: flight.y, gait: movement?.gait ?? "walk", lerpMs: Math.max(50, Math.round(dt * 1000)), freeFlight: true } }; } #moveTo (sessionId, characterId, tileX, tileY) { const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); if (this.frozen.has(entityId)) { return { events: [] }; } clearEngage(this.ecs, entityId); clearFollow(this.ecs, entityId); cancelGather(this.ecs, handle); clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting)); const position = this.ecs.get(handle, Component.position); const movement = this.ecs.get(handle, Component.movement); let path = this.ecs.get(handle, Component.path); if (!path) { path = this.ecs.add(handle, Component.path, { tiles: [] }); } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); path.tiles = findPath( position.tileX, position.tileY, tileX, tileY, (x, y) => this.walkableFor(entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, this.pathfindOptions({ preferVertical: true, preferPaths: true, entityId }) ); movement.walkCarry = 0; const events = []; /** Open immediately when the next step is a door (player already adjacent). */ const first = path.tiles[0]; if (first) { const doorDelta = maybeOpenDoorOnApproach(this, entityId, first.x, first.y); if (doorDelta) { events.push(doorDelta); } } return { events }; } #attack (sessionId, characterId, targetEntityId, now) { const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); if (targetEntityId === entityId) { const error = new Error("Cannot attack yourself."); error.userFacing = true; throw error; } const target = resolveCombatTarget(this, targetEntityId); if (!target) { const error = new Error("Target is not here."); error.userFacing = true; throw error; } if (target.health && target.health.current <= 0) { const error = new Error("That cannot be attacked."); error.userFacing = true; throw error; } if (!this.ecs.get(handle, Component.combat)) { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } clearFollow(this.ecs, entityId); cancelGather(this.ecs, handle); clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting)); engageTarget(this.ecs, entityId, targetEntityId, now); const position = this.ecs.get(handle, Component.position); const profile = attackProfileOf(this.ecs, handle); if (position && target.pos) { if (profile.mode === "ranged") { queueStandInRangeApproach( this, entityId, handle, position, target.pos.tileX, target.pos.tileY, profile.rangeTiles | 0 || COMBAT_RANGE_TILES, 1 ); } else if (profile.mode === "melee") { queueMeleeApproach(this, entityId, handle, position, target.pos); } } return { events: [] }; } #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() }) { // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click. void attackerEntityId; void targetEntityId; void now; return { events: [] }; } #engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() }) { if (this.ecs.handleOf(attackerEntityId) == null) { return { ok: false }; } engageTarget(this.ecs, attackerEntityId, targetEntityId, now); return { ok: true }; } /** * Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY). * Optionally restrict to one spawnerId. */ #listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 }) { const guards = []; for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position)) { if (!entity.spawnOrigin?.townGuard) { continue; } if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId) { continue; } const originX = entity.spawnOrigin.originTileX; const originY = entity.spawnOrigin.originTileY; const range = entity.spawnOrigin.wanderRangeTiles | 0; const dx = Math.abs(tileX - originX); const dy = Math.abs(tileY - originY); if (Math.max(dx, dy) > range) { continue; } const health = this.ecs.get(entity.handle, Component.health); if (health && health.current <= 0) { continue; } if (this.ecs.has(entity.handle, Component.dead)) { continue; } guards.push({ entityId: entity.entityId, spawnerId: entity.spawnOrigin.spawnerId, busy: entity.combat?.targetEntityId != null }); if (guards.length >= limit) { break; } } return { guards }; } #applyRemoteMelee (payload) { return applyRemoteMeleeSwing(this, payload); } #applyRemoteRanged (payload) { return applyRemoteRangedShot(this, payload); } #applyCombatHitXp ({ entityId, profile, damage }) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return { events: [] }; } const character = this.ecs.get(handle, Component.character); if (!character) { return { events: [] }; } const xpAward = awardCombatHitXp(this.ecs, handle, profile, damage); if (!xpAward) { return { events: [] }; } return { events: [{ type: "skills-updated", entityId, characterId: character.characterId, skills: xpAward.skills, combatLevel: xpAward.combatLevel, stored: xpAward.stored, levelUps: xpAward.levelUps ?? [] }] }; } #cancelAttack (sessionId, characterId) { const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); clearEngage(this.ecs, entityId); clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting)); return { events: [] }; } #interact (sessionId, characterId, targetEntityId, purpose = null) { this.#requireOwnedEntity(sessionId, characterId); const targetHandle = this.ecs.handleOf(targetEntityId); if (targetHandle == null) { const error = new Error("Target is not here."); error.userFacing = true; throw error; } if (isUntargetable(this.ecs, targetHandle)) { const error = new Error("Nothing to say."); error.userFacing = true; throw error; } const creature = this.ecs.get(targetHandle, Component.creature); const def = creature ? mobDefinition(creature.mobTypeId) : null; const shop = this.ecs.get(targetHandle, Component.shop); const hasShop = shopHasInterface(shop); const origin = this.ecs.get(targetHandle, Component.spawnOrigin); const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : ""; const intent = purpose === "shop" || purpose === "talk" ? purpose : null; if (intent === "shop" && hasShop) { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } if (intent === "talk" && dialogueId) { // Pin in-worker before return so wander cannot start before the sim thread pins. this.#pinDialogue(targetEntityId, characterId); return { events: [{ type: "open-dialogue", sessionId, characterId, entityId: targetEntityId, dialogueId }] }; } if (intent === "talk" && hasShop) { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } // Default click: prefer dialogue when assigned, else shop, else talkable no-op. if (dialogueId) { this.#pinDialogue(targetEntityId, characterId); return { events: [{ type: "open-dialogue", sessionId, characterId, entityId: targetEntityId, dialogueId }] }; } if (hasShop) { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } if (!def?.talkable) { const error = new Error("They have nothing to say."); error.userFacing = true; throw error; } return { events: [] }; } #follow (sessionId, characterId, targetEntityId) { const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); const targetHandle = this.ecs.handleOf(targetEntityId); if (targetHandle == null) { const error = new Error("Target is not here."); error.userFacing = true; throw error; } if (targetEntityId === entityId) { const error = new Error("Cannot follow yourself."); error.userFacing = true; throw error; } if (!this.ecs.get(targetHandle, Component.position)) { const error = new Error("That cannot be followed."); error.userFacing = true; throw error; } clearEngage(this.ecs, entityId); setFollow(this.ecs, entityId, targetEntityId); const path = this.ecs.get(handle, Component.path); if (path) { path.tiles = []; } return { events: [] }; } #cancelFollow (sessionId, characterId) { const { entityId } = this.#requireOwnedEntity(sessionId, characterId); clearFollow(this.ecs, entityId); return { events: [] }; } #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 { handle } = this.#requireOwnedEntity(sessionId, characterId); const movement = this.ecs.get(handle, Component.movement); const stamina = this.ecs.get(handle, Component.stamina); if (gait === GAIT.run && !(Number(stamina?.current) > 0)) { const error = new Error("You are too exhausted to run."); error.userFacing = true; throw error; } movement.gait = gait; const character = this.ecs.get(handle, Component.character); return { events: character ? [this.#staminaEvent(handle, character.characterId, movement.gait)] : [] }; } #staminaEvent (handle, characterId, gait = null) { const stamina = this.ecs.get(handle, Component.stamina); const movement = this.ecs.get(handle, Component.movement); return { type: "stamina", characterId, ...publicStaminaView(stamina), gait: gait ?? movement?.gait ?? GAIT.walk }; } #consumeRunStamina (handle, events) { const character = this.ecs.get(handle, Component.character); if (!character) { return; } let stamina = this.ecs.get(handle, Component.stamina); if (!stamina) { stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 }); } const skills = this.ecs.get(handle, Component.skills); syncPlayerStamina(this.ecs, handle); const position = this.ecs.get(handle, Component.position); const onPath = position ? this.groundTypeAt(position.tileX, position.tileY, position.dimensionId) === GroundType.path : false; const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond, { onPath }); stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost); stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost; let skillsChanged = false; const levelUps = []; while (stamina.xpDebt >= 1 && skills?.xp) { stamina.xpDebt -= 1; const result = applySkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT); if (result.changed) { skillsChanged = true; syncPlayerStamina(this.ecs, handle); } if (result.levelUp) { levelUps.push(result.levelUp); } } const movement = this.ecs.get(handle, Component.movement); if (stamina.current <= 0 && movement) { stamina.current = 0; movement.gait = GAIT.walk; } events.push(this.#staminaEvent(handle, character.characterId)); if (skillsChanged) { events.push({ type: "skills-updated", entityId: this.ecs.entityIdOf(handle), characterId: character.characterId, ...publicSkillsPayload(skills), stored: storedSkillXp(skills), levelUps }); } } #regenStamina (dt, events) { if (!(dt > 0)) { return; } for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement)) { const { handle, character, stamina, movement } = entity; if (this.ecs.has(handle, Component.dead)) { continue; } const status = this.ecs.get(handle, Component.statusEffects); if (hasStatusEffect(status, StatusEffectType.staminaBlock, Date.now())) { continue; } // Run gait only blocks regen while actually stepping along a path. const path = this.ecs.get(handle, Component.path); if (movement.gait === GAIT.run && path?.tiles?.length) { continue; } syncPlayerStamina(this.ecs, handle); const before = Number(stamina.current) || 0; if (before >= stamina.max) { continue; } stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND); const after = Number(stamina.current) || 0; // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam. if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max)) { events.push(this.#staminaEvent(handle, character.characterId)); } } } #requireOwnedEntity (sessionId, characterId) { const entityId = this.characterEntities.get(characterId); if (!entityId) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } const handle = this.ecs.handleOf(entityId); const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null; if (!identity || identity.sessionId !== sessionId) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } if (this.ecs.has(handle, Component.dead)) { const error = new Error("You are dead."); error.userFacing = true; throw error; } return { handle, entityId }; } #stepSystems (now = Date.now(), dt = 1 / 20) { const events = []; const transferRequests = []; this.#regenStamina(dt, events); events.push(...stepStatusEffects(this, now, dt)); events.push(...stepPassiveHealthRegen(this, now, dt)); const flight = stepFreeFlight(this, now); for (const event of flight) { if (event.type === "transfer-request") { const payload = serializeEntity(this.ecs, event.entityId); transferRequests.push({ entityId: event.entityId, fromTileX: event.fromTileX, fromTileY: event.fromTileY, destTileX: event.destTileX, destTileY: event.destTileY, toRegionX: event.toRegionX, toRegionY: event.toRegionY, dimensionId: event.dimensionId ?? OVERWORLD_ID, payload }); continue; } events.push(event); } stepAggression(this, now); events.push(...stepCombat(this, now)); events.push(...stepPendingSpellCast(this, now)); events.push(...processSpellImpacts(this, now)); events.push(...stepSpellAutoCast(this, now)); events.push(...tickSpellLights(this, now)); const summons = stepSummons(this, now); events.push(...(summons.events ?? [])); for (const entityId of summons.despawnIds ?? []) { const dropped = this.#destroyEntity(entityId); if (dropped) { events.push({ type: "entity-despawn", entityId }); } } stepFollow(this); const gather = stepGather(this, now); events.push(...gather.events); for (const entry of gather.privates ?? []) { events.push({ type: "inventory", characterId: entry.characterId, ...entry.bag }); } const fire = stepFirestarting(this, now); events.push(...fire.events); for (const entry of fire.privates ?? []) { events.push({ type: "inventory", characterId: entry.characterId, ...entry.bag }); } const fishing = stepFishing(this, now); events.push(...fishing.events); for (const entry of fishing.privates ?? []) { events.push({ type: "inventory", characterId: entry.characterId, ...entry.bag }); } const shearing = stepShearing(this, now); events.push(...shearing.events); for (const entry of shearing.privates ?? []) { events.push({ type: "inventory", characterId: entry.characterId, ...entry.bag }); } const craft = stepCrafting(this, now); events.push(...craft.events); for (const entry of craft.privates ?? []) { events.push({ type: "inventory", characterId: entry.characterId, ...entry.bag }); } events.push(...stepDoors(this)); return { events, transferRequests }; } #stepMovement (now = Date.now()) { const events = expireGroundItems(this, now); const transferRequests = []; events.push(...pruneShopBrowsers(this)); events.push(...this.#pruneDialogueBrowsers()); this.#queueAmbientWander(); this.#queueSpawnerWander(); this.#queueExchangeStations(); for (const entity of this.ecs.query(Component.position, Component.movement)) { const { handle, entityId, position, movement } = entity; if (this.ecs.has(handle, Component.dead)) { continue; } if (this.ecs.has(handle, Component.flight)) { continue; } const path = this.ecs.get(handle, Component.path); const tiles = path?.tiles; if (this.frozen.has(entityId) || !tiles?.length) { if (path) { path.stuckSince = null; } continue; } if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID)) { continue; } this.#repathIfNavigationStuck(entityId, position, movement, path, now); const stamina = this.ecs.get(handle, Component.stamina); if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0)) { movement.gait = GAIT.walk; } const isWalk = movement.gait !== GAIT.run; if (isWalk) { movement.walkCarry = (movement.walkCarry + 1) % 2; if (movement.walkCarry !== 0) { continue; } } const next = tiles[0]; if (!next) { continue; } const destRegionX = tileToRegion(next.x); const destRegionY = tileToRegion(next.y); const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) { this.frozen.add(entityId); transferRequests.push({ entityId, fromTileX: position.tileX, fromTileY: position.tileY, destTileX: next.x, destTileY: next.y, toRegionX: destRegionX, toRegionY: destRegionY, dimensionId, payload: serializeEntity(this.ecs, entityId) }); continue; } if (!this.walkableFor(entityId, next.x, next.y)) { const combat = this.ecs.get(handle, Component.combat); if (combat?.targetEntityId != null) { const targetHandle = this.ecs.handleOf(combat.targetEntityId); const targetPos = targetHandle != null ? this.ecs.get(targetHandle, Component.position) : null; const blockedByTarget = targetPos && next.x === targetPos.tileX && next.y === targetPos.tileY; if (!blockedByTarget) { path.tiles = []; } } continue; } const doorDelta = maybeOpenDoorOnApproach(this, entityId, next.x, next.y); if (doorDelta) { events.push(doorDelta); } const combat = this.ecs.get(handle, Component.combat); if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y)) { continue; } const fromTileX = position.tileX; const fromTileY = position.tileY; const flying = this.#isFlying(handle); if (!flying) { this.#vacate(entityId, fromTileX, fromTileY); } position.tileX = next.x; position.tileY = next.y; tiles.shift(); if (!flying) { this.#occupy(entityId, position.tileX, position.tileY, now); } path.stuckSince = now; path.stuckTileX = position.tileX; path.stuckTileY = position.tileY; recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY); consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY); syncCharacterChunkPresence(this.ecs, handle, now); if (!isWalk) { this.#consumeRunStamina(handle, events); } events.push(this.#moveEvent(entityId, fromTileX, fromTileY)); } return { events, transferRequests }; } /** * If we still have a destination but have not left this tile for NAV_STUCK_MS, * recompute A* to the same goal (around whoever is blocking the old route). */ #repathIfNavigationStuck (entityId, position, movement, path, now) { if (!path?.tiles?.length) { path.stuckSince = null; return; } if ( path.stuckSince == null || path.stuckTileX !== position.tileX || path.stuckTileY !== position.tileY ) { path.stuckSince = now; path.stuckTileX = position.tileX; path.stuckTileY = position.tileY; return; } if (now - path.stuckSince < NAV_STUCK_MS) { return; } const goal = path.tiles[path.tiles.length - 1]; if (!goal || (goal.x === position.tileX && goal.y === position.tileY)) { path.tiles = []; path.stuckSince = null; return; } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const stuckHandle = this.ecs.handleOf(entityId); const inCombat = stuckHandle != null && this.ecs.get(stuckHandle, Component.combat)?.targetEntityId != null; path.tiles = findPath( position.tileX, position.tileY, goal.x, goal.y, (x, y) => this.isClearStanding(entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, this.pathfindOptions({ preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character), preferPaths: !inCombat, entityId }) ); path.stuckSince = now; path.stuckTileX = position.tileX; path.stuckTileY = position.tileY; if (movement) { movement.walkCarry = 0; } } #queueAmbientWander () { for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature)) { const def = mobDefinition(entity.creature.mobTypeId); if (!def?.ambient || def.freeFlight) { continue; } if (this.ecs.get(entity.handle, Component.spawnOrigin)) { continue; } const path = this.ecs.get(entity.handle, Component.path); if (!path) { continue; } if (path.tiles?.length) { continue; } if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID)) { continue; } if (Math.random() > 0.35) { continue; } const dirs = [ { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } ]; const dir = dirs[Math.floor(Math.random() * dirs.length)]; const nextX = entity.position.tileX + dir.x; const nextY = entity.position.tileY + dir.y; if (!this.isClearStanding(entity.entityId, nextX, nextY)) { continue; } path.tiles = [{ x: nextX, y: nextY }]; } } /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */ #queueSpawnerWander () { for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin)) { const combat = this.ecs.get(entity.handle, Component.combat); if (combat?.targetEntityId != null) { continue; } const follow = this.ecs.get(entity.handle, Component.follow); if (follow?.targetEntityId != null) { continue; } const shop = this.ecs.get(entity.handle, Component.shop); if (shopHasActiveBrowsers(shop)) { continue; } const origin = entity.spawnOrigin; if (originIsBusyPinned(origin)) { continue; } if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY)) { continue; } const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId); if (def?.freeFlight) { continue; } const path = this.ecs.get(entity.handle, Component.path); if (!path || path.tiles?.length) { continue; } if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID)) { continue; } const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX; const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY; const range = Math.max(0, origin.wanderRangeTiles | 0); const homeDist = Math.max( Math.abs(entity.position.tileX - originX), Math.abs(entity.position.tileY - originY) ); const tooFar = homeDist > range; // Outside the leash: always try to step home. Inside: mostly idle. if (!tooFar && Math.random() > 0.1) { continue; } if (tooFar) { if (this.#queueReturnTowardSpawn(entity.entityId, entity.handle, entity.position, path, originX, originY)) { continue; } queueLocalRandomWanderStep(this, entity.entityId, entity.position, path); continue; } const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range); if (!goal) { continue; } if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY) { continue; } const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS); const tiles = findPath( entity.position.tileX, entity.position.tileY, goal.tileX, goal.tileY, (x, y) => this.walkableFor(entity.entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, this.pathfindOptions({ preferPaths: true, entityId: entity.entityId }) ); if (!tiles?.length) { continue; } path.tiles = tiles; } } /** * Path toward the spawner within the current pathfinding window (chunk-step home). * @returns {boolean} true if a return path was queued */ #queueReturnTowardSpawn (entityId, handle, position, path, originX, originY) { const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const goal = pickClearGoalToward( this, entityId, position.tileX, position.tileY, originX, originY, bounds ); if (!goal) { return false; } if (goal.tileX === position.tileX && goal.tileY === position.tileY) { return false; } const tiles = findPath( position.tileX, position.tileY, goal.tileX, goal.tileY, (x, y) => this.walkableFor(entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, this.pathfindOptions({ preferPaths: true, entityId }) ); if (!tiles?.length) { return false; } path.tiles = tiles; const movement = this.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } return true; } /** * Send an idle Central Exchange clerk to the staff-side tile of a counter. * message: { stationTileX, stationTileY } */ #stationExchangeClerk (message) { const stationTileX = message.stationTileX | 0; const stationTileY = message.stationTileY | 0; if (!this.isEnterable(stationTileX, stationTileY)) { return { ok: false, reason: "blocked" }; } for (const entity of this.ecs.query(Component.spawnOrigin, Component.position)) { if (!entity.spawnOrigin?.centralExchange) { continue; } if ( Number.isInteger(entity.spawnOrigin.stationTileX) && entity.spawnOrigin.stationTileX === stationTileX && entity.spawnOrigin.stationTileY === stationTileY ) { return { ok: true, entityId: entity.entityId, already: true }; } } let best = null; let bestDist = Infinity; for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path)) { if (!entity.spawnOrigin?.centralExchange) { continue; } if (Number.isInteger(entity.spawnOrigin.stationTileX)) { continue; } const dist = Math.max( Math.abs(entity.position.tileX - stationTileX), Math.abs(entity.position.tileY - stationTileY) ); if (dist < bestDist) { bestDist = dist; best = entity; } } if (!best) { return { ok: false, reason: "none-available" }; } const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS); const tiles = findPath( best.position.tileX, best.position.tileY, stationTileX, stationTileY, (x, y) => this.walkableFor(best.entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, this.pathfindOptions({ preferPaths: true, entityId: best.entityId }) ); best.spawnOrigin.stationTileX = stationTileX; best.spawnOrigin.stationTileY = stationTileY; if (tiles?.length) { best.path.tiles = tiles; } else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY) { best.path.tiles = []; } else { return { ok: false, reason: "no-path" }; } return { ok: true, entityId: best.entityId }; } /** * Clear a CE clerk's station assignment so wander can resume. * message: { stationTileX, stationTileY } */ #releaseExchangeClerk (message) { const stationTileX = message.stationTileX | 0; const stationTileY = message.stationTileY | 0; let released = 0; for (const entity of this.ecs.query(Component.spawnOrigin, Component.path)) { if (!entity.spawnOrigin?.centralExchange) { continue; } if ( entity.spawnOrigin.stationTileX !== stationTileX || entity.spawnOrigin.stationTileY !== stationTileY ) { continue; } entity.spawnOrigin.stationTileX = null; entity.spawnOrigin.stationTileY = null; entity.path.tiles = []; released += 1; } return { ok: true, released }; } #pinDialogue (entityId, characterId) { const handle = this.ecs.handleOf(entityId | 0); if (handle == null) { return { ok: false }; } const origin = this.ecs.get(handle, Component.spawnOrigin); if (!origin) { return { ok: false }; } if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object") { origin.dialogueBrowsers = Object.create(null); } origin.dialogueBrowsers[characterId | 0] = true; const path = this.ecs.get(handle, Component.path); if (path) { path.tiles = []; } return { ok: true }; } #unpinDialogue (entityId, characterId) { const handle = this.ecs.handleOf(entityId | 0); if (handle == null) { return { ok: false }; } const origin = this.ecs.get(handle, Component.spawnOrigin); if (!origin?.dialogueBrowsers) { return { ok: true }; } delete origin.dialogueBrowsers[characterId | 0]; return { ok: true }; } #pruneDialogueBrowsers () { const events = []; for (const entity of this.ecs.query(Component.spawnOrigin, Component.position)) { const browsers = entity.spawnOrigin?.dialogueBrowsers; const shearBrowsers = entity.spawnOrigin?.shearBrowsers; const dialogueIds = browsers && typeof browsers === "object" ? Object.keys(browsers).map((id) => Number(id)) : []; const shearIds = shearBrowsers && typeof shearBrowsers === "object" ? Object.keys(shearBrowsers).map((id) => Number(id)) : []; if (!dialogueIds.length && !shearIds.length) { continue; } const path = this.ecs.get(entity.handle, Component.path); if (path) { path.tiles = []; } for (const characterId of dialogueIds) { const playerEntityId = this.characterEntities.get(characterId); if (playerEntityId == null) { delete browsers[characterId]; continue; } const playerHandle = this.ecs.handleOf(playerEntityId); const playerPos = this.ecs.get(playerHandle, Component.position); const stillNear = playerPos && chebyshev( playerPos.tileX, playerPos.tileY, entity.position.tileX, entity.position.tileY ) <= 1; if (stillNear) { continue; } delete browsers[characterId]; const identity = this.ecs.get(playerHandle, Component.networkIdentity); events.push({ type: "dialogue-walk-away", sessionId: identity?.sessionId ?? null, characterId, npcEntityId: entity.entityId }); } for (const characterId of shearIds) { const playerEntityId = this.characterEntities.get(characterId); if (playerEntityId == null) { delete shearBrowsers[characterId]; continue; } const playerHandle = this.ecs.handleOf(playerEntityId); const playerPos = this.ecs.get(playerHandle, Component.position); const stillNear = playerPos && chebyshev( playerPos.tileX, playerPos.tileY, entity.position.tileX, entity.position.tileY ) <= 1; if (stillNear) { continue; } delete shearBrowsers[characterId]; } } return events; } /** Keep stationed CE clerks at their counter tile. */ #queueExchangeStations () { for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path)) { if (!entity.spawnOrigin?.centralExchange) { continue; } const sx = entity.spawnOrigin.stationTileX; const sy = entity.spawnOrigin.stationTileY; if (!Number.isInteger(sx) || !Number.isInteger(sy)) { continue; } if (entity.position.tileX === sx && entity.position.tileY === sy) { entity.path.tiles = []; continue; } if (entity.path.tiles?.length) { continue; } const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS); const tiles = findPath( entity.position.tileX, entity.position.tileY, sx, sy, (x, y) => this.walkableFor(entity.entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, this.pathfindOptions({ preferPaths: true, entityId: entity.entityId }) ); if (tiles?.length) { entity.path.tiles = tiles; } } } #applyTransfer (message) { const payload = message.payload; const entityId = payload.entityId; if (this.ecs.hasEntity(entityId)) { return { accepted: false, reason: "already-present" }; } const position = payload.components?.position; const destTileX = message.destTileX ?? position?.tileX; const destTileY = message.destTileY ?? position?.tileY; const dimensionId = normalizeDimensionId( message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID ); if (destTileX == null || destTileY == null) { return { accepted: false, reason: "missing-destination" }; } if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId)) { return { accepted: false, reason: "not-owner" }; } const creature = payload.components?.creature; const flying = !!mobDefinition(creature?.mobTypeId)?.flying; if (flying) { const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId); if (!data?.open) { return { accepted: false, reason: "blocked" }; } } else if (!this.isEnterable(destTileX, destTileY, dimensionId)) { return { accepted: false, reason: "blocked" }; } deserializeEntity(this.ecs, payload); const handle = this.ecs.handleOf(entityId); const livePosition = this.ecs.get(handle, Component.position); const path = this.ecs.get(handle, Component.path); livePosition.tileX = destTileX; livePosition.tileY = destTileY; livePosition.dimensionId = dimensionId; if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY) { path.tiles.shift(); } if (!flying) { this.#occupy(entityId, destTileX, destTileY); } const character = this.ecs.get(handle, Component.character); if (character?.characterId) { this.characterEntities.set(character.characterId, entityId); } this.frozen.delete(entityId); return { accepted: true, entity: publicEntityView(this.ecs, entityId) }; } #commitTransfer (entityId) { if (!this.ecs.hasEntity(entityId)) { return null; } return this.#destroyEntity(entityId); } #abortTransfer (entityId) { this.frozen.delete(entityId); return publicEntityView(this.ecs, entityId); } #listLoaders () { return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({ entityId: entity.entityId, tileX: entity.position.tileX, tileY: entity.position.tileY, dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID), chunkLoader: { ...entity.chunkLoader } })); } #listPublicEntities () { const out = []; for (const entity of this.ecs.query(Component.position)) { if (this.ecs.has(entity.handle, Component.dead)) { continue; } const view = publicEntityView(this.ecs, entity.entityId); if (view) { out.push(view); } } return out; } #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const records = []; for (const entity of this.ecs.query(Component.position)) { const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID); if (entityDim !== dim) { continue; } if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY) { continue; } records.push({ ...publicEntityView(this.ecs, entity.entityId), persistent: this.ecs.has(entity.handle, Component.persistent), payload: serializeEntity(this.ecs, entity.entityId) }); } return records; } #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const data = this.#chunkData(chunkX, chunkY, dim); if (staticOnly) { return { chunkX, chunkY, dimensionId: dim, open: data.open, closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open), grounds: data.grounds, blocks: data.blocks, light: data.light, occlusion: data.occlusion, entities: [], groundItems: [] }; } const entities = []; for (const entity of this.ecs.query(Component.position, Component.appearance)) { if (this.ecs.has(entity.handle, Component.dead)) { continue; } const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID); if (entityDim !== dim) { continue; } if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY) { continue; } entities.push(publicEntityView(this.ecs, entity.entityId)); } return { chunkX, chunkY, dimensionId: dim, open: data.open, closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open), grounds: data.grounds, blocks: data.blocks, light: data.light, occlusion: data.occlusion, entities, groundItems: groundItemsInChunk(this, chunkX, chunkY) }; } #moveEvent (entityId, fromTileX, fromTileY) { const view = publicEntityView(this.ecs, entityId); return { type: "entity-move", entityId, fromTileX, fromTileY, tileX: view.tileX, tileY: view.tileY, worldX: view.worldX, worldY: view.worldY, gait: view.gait, freeFlight: !!view.freeFlight }; } chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) { const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)); return !!chunk && !chunk.replica && chunk.simulating; } walkableFor (entityId, tileX, tileY) { const dim = this.#entityDimensionId(entityId); const handle = this.ecs.handleOf(entityId); if (this.#isFlying(handle)) { const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim); return !!data?.open; } // Entities pass through each other; only terrain / closed chunks block movement. return this.isEnterable(tileX, tileY, dim, { canOpenDoors: entityCanOpenDoors(this.ecs, entityId) }); } /** Ground type id at a world tile (defaults to world default ground). */ groundTypeAt (tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId) ?? OVERWORLD_ID; const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim); const entry = normalizeGround(data.grounds[tileIndex(tileToLocal(tileX), tileToLocal(tileY))]); return entry?.typeId ?? this.settings.defaultGroundTypeId ?? GroundType.grass; } /** * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null }} [options] */ pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null } = {}) { const options = { preferVertical: !!preferVertical }; const now = Date.now(); const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID; options.stepCost = (x, y) => stepCostForGround( this.groundTypeAt(x, y, dimensionId), { preferPaths: !!preferPaths, softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now) } ); options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1; return options; } /** * True when another living occupant has stood on this tile for SOFT_OCCUPIED_DWELL_MS+. * Soft cost only — never blocks pathing. */ #isSoftOccupiedTile (tileX, tileY, dimensionId, selfEntityId, now = Date.now()) { const key = tileKey(tileX, tileY, dimensionId); const local = this.occupancy.get(key); if (!local?.size) { return false; } for (const id of local) { if (id === selfEntityId) { continue; } const handle = this.ecs.handleOf(id); if (handle == null) { continue; } const position = this.ecs.get(handle, Component.position); const enteredAt = position?.tileEnteredAt; if (enteredAt == null) { continue; } if (now - enteredAt >= SOFT_OCCUPIED_DWELL_MS) { return true; } } return false; } /** * Standing tile with no other mob/player (self allowed). Used for wander goals * and melee attack stance. */ isClearStanding (entityId, tileX, tileY) { const dim = this.#entityDimensionId(entityId); if (!this.isEnterable(tileX, tileY, dim, { canOpenDoors: entityCanOpenDoors(this.ecs, entityId) })) { return false; } return !this.#hasOtherOccupant(entityId, tileX, tileY, dim); } destroyEntity (entityId) { return this.#destroyEntity(entityId); } occupied (tileX, tileY, dimensionId = OVERWORLD_ID) { return this.#anyOccupant(tileX, tileY, dimensionId); } #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) { return this.chunkIsSimulating(tileX, tileY, dimensionId); } #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID) { const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId)); if (loaded) { return loaded.data; } return createEmptyChunkData(this.settings.defaultGroundTypeId); } isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false } = {}) { const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId); if (!data.open) { return false; } return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), { canOpenDoors }); } isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID) { const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId); if (!data.open) { return false; } return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY)); } #walkableFor (entityId, tileX, tileY) { return this.walkableFor(entityId, tileX, tileY); } #isFlying (handle) { if (handle == null) { return false; } const creature = this.ecs.get(handle, Component.creature); return !!mobDefinition(creature?.mobTypeId)?.flying; } #entityDimensionId (entityId) { const handle = this.ecs.handleOf(entityId); const position = handle != null ? this.ecs.get(handle, Component.position) : null; return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID); } #occupy (entityId, tileX, tileY, now = Date.now()) { const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId)); let set = this.occupancy.get(key); if (!set) { set = new Set(); this.occupancy.set(key, set); } set.add(entityId); const handle = this.ecs.handleOf(entityId); const position = handle != null ? this.ecs.get(handle, Component.position) : null; if (position) { position.tileEnteredAt = now; } } #vacate (entityId, tileX, tileY) { const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId)); const set = this.occupancy.get(key); if (!set) { return; } set.delete(entityId); if (set.size === 0) { this.occupancy.delete(key); } } #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID) { const key = tileKey(tileX, tileY, dimensionId); const local = this.occupancy.get(key); if (local?.size) { return local.values().next().value; } const ghosts = this.ghostOccupancy.get(key); if (ghosts?.size) { return ghosts.values().next().value; } return null; } #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null) { const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId); const key = tileKey(tileX, tileY, dim); const local = this.occupancy.get(key); if (local) { for (const id of local) { if (id !== entityId) { return true; } } } const ghosts = this.ghostOccupancy.get(key); if (ghosts) { for (const id of ghosts) { if (id !== entityId) { return true; } } } return false; } /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */ #occupied (tileX, tileY, dimensionId = OVERWORLD_ID) { return this.#anyOccupant(tileX, tileY, dimensionId); } } function pickWanderGoalInRange (world, entityId, originX, originY, range) { const radius = Math.max(0, range | 0); for (let attempt = 0; attempt < 24; attempt++) { const tileX = originX + randInt(-radius, radius); const tileY = originY + randInt(-radius, radius); if (!world.isClearStanding(entityId, tileX, tileY)) { continue; } return { tileX, tileY }; } return null; } /** * Clearest standable tile in pathfinding bounds, pulled toward (destX, destY). * When the destination is outside the window this becomes a chunk-step toward home. */ function pickClearGoalToward (world, entityId, fromX, fromY, destX, destY, bounds) { const idealX = Math.max(bounds.minX, Math.min(bounds.maxX, destX | 0)); const idealY = Math.max(bounds.minY, Math.min(bounds.maxY, destY | 0)); if (world.isClearStanding(entityId, idealX, idealY)) { return { tileX: idealX, tileY: idealY }; } for (let radius = 1; radius <= 4; radius++) { for (let dy = -radius; dy <= radius; dy++) { for (let dx = -radius; dx <= radius; dx++) { if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius) { continue; } const tileX = idealX + dx; const tileY = idealY + dy; if (tileX < bounds.minX || tileX > bounds.maxX || tileY < bounds.minY || tileY > bounds.maxY) { continue; } if (tileX === fromX && tileY === fromY) { continue; } if (!world.isClearStanding(entityId, tileX, tileY)) { continue; } return { tileX, tileY }; } } } return null; } /** One random adjacent step so a stranded mob does not freeze in place. */ function queueLocalRandomWanderStep (world, entityId, position, path) { const dirs = [ { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } ]; for (let i = dirs.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const tmp = dirs[i]; dirs[i] = dirs[j]; dirs[j] = tmp; } for (const dir of dirs) { const nextX = position.tileX + dir.x; const nextY = position.tileY + dir.y; if (!world.isClearStanding(entityId, nextX, nextY)) { continue; } path.tiles = [{ x: nextX, y: nextY }]; return true; } return false; } function hasDialogueBrowsers (origin) { return originIsBusyPinned(origin); } function randInt (min, max) { return min + Math.floor(Math.random() * (max - min + 1)); } export function replicaNeededForOwnedChunks (ownedChunkKeys) { const needed = new Set(); for (const key of ownedChunkKeys) { const { chunkX, chunkY, dimensionId } = parseChunkKey(key); for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId)); } } } return needed; }