import { readdirSync } from "node:fs"; import { extname, join } from "node:path"; import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js"; import { spriteImageName } from "../../../shared/definitions/tileSprites.js"; export function buildSpriteCatalog (assetRoot) { const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground"); const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block"); return { grounds: grounds.types, blocks: blocks.types, images: [...grounds.images, ...blocks.images] }; } function scanLayer (layerDir, definitions, layer) { const types = {}; const images = []; for (const def of Object.values(definitions)) { const folder = join(layerDir, def.key); const states = listPngStates(folder); if (states.length === 0) { throw new Error(`No PNG states in ${folder}`); } const frames = Math.max(1, def.frames ?? 1); const framesPerRow = Math.max(1, def.framesPerRow ?? 1); const animationSpeed = Math.max(0, def.animationSpeed ?? 0); types[def.key] = { key: def.key, typeId: def.id, states, defaultState: states[0], frames, framesPerRow, animationSpeed }; for (const state of states) { images.push({ name: spriteImageName(layer, def.key, state), url: `/assets/${layer === "ground" ? "grounds" : "blocks"}/${def.key}/${state}.png`, subImgTotal: frames, perRow: framesPerRow, loop: animationSpeed > 0, animationSpeed }); } } return { types, images }; } function listPngStates (folder) { let entries; try { entries = readdirSync(folder, { withFileTypes: true }); } catch (error) { if (error.code === "ENOENT") { return []; } throw error; } return entries .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png") .map((entry) => entry.name.slice(0, -extname(entry.name).length)) .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" })); }