import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { defaultSpawnerConfig, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js"; import { Component } from "../ecs/components.js"; import { tileToRegion } from "../world/coordinates.js"; export function collectSpawnRequests (world) { const requests = []; const counts = countBySpawner(world); for (const [key, chunk] of world.chunks) { if (chunk.replica || !chunk.simulating || !chunk.data.open) { continue; } const [chunkX, chunkY] = key.split(",").map(Number); for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const block = chunk.data.blocks[localY * CHUNK_SIZE + localX]; if (block?.typeId !== BlockType.spawner) { continue; } const config = { ...defaultSpawnerConfig(`${chunkX}:${chunkY}:${localY * CHUNK_SIZE + localX}`), ...(block.config ?? {}) }; if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive) { continue; } const originX = chunkX * CHUNK_SIZE + localX; const originY = chunkY * CHUNK_SIZE + localY; const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles); if (!tile) { continue; } requests.push({ ...tile, mobTypeId: config.mobTypeId, spawnerId: config.spawnerId, persistent: !!mobDefinition(config.mobTypeId)?.persistent }); counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1); } } } return requests; } export function mobComponents (request) { const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer"); const components = { position: { tileX: request.tileX, tileY: request.tileY }, movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 }, path: { tiles: [] }, appearance: { sex: def.sex ?? "male", firstName: def.displayName, lastName: "", sprite: mobSpriteName(def.mobTypeId) }, creature: { mobTypeId: def.mobTypeId }, health: { current: def.health ?? 8, max: def.health ?? 8 }, spawnOrigin: { spawnerId: request.spawnerId } }; if (def.persistent) { components.persistent = {}; } return components; } function countBySpawner (world) { const counts = new Map(); for (const entity of world.ecs.query(Component.spawnOrigin)) { const id = entity.spawnOrigin.spawnerId; counts.set(id, (counts.get(id) ?? 0) + 1); } return counts; } function pickSpawnTile (world, originX, originY, range) { const radius = Math.max(1, range | 0); for (let attempt = 0; attempt < 24; attempt++) { const tileX = originX + randInt(-radius, radius); const tileY = originY + randInt(-radius, radius); if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY))) { continue; } if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY)) { continue; } return { tileX, tileY }; } return null; } function randInt (min, max) { return min + Math.floor(Math.random() * (max - min + 1)); }