/** * Registry of average sprite colours for grounds and blocks. * * Filled by {@link installTileAverageColors} from a sprite catalog that already * carries `averageColor` / `stateColors` (the server computes those from PNGs * when it builds the catalog). Game code asks {@link groundAverageColor} or * {@link blockAverageColor} rather than sampling textures itself. * * A missing state falls back to the type's default-state colour. A missing * type returns null. */ const groundColors = new Map(); const blockColors = new Map(); /** * @param {object | null | undefined} catalog */ export function installTileAverageColors (catalog) { groundColors.clear(); blockColors.clear(); installGroup(groundColors, catalog?.grounds); installGroup(blockColors, catalog?.blocks); } /** * @param {number | string | null | undefined} typeId * @param {string | null | undefined} [state] * @returns {{ r: number, g: number, b: number } | null} */ export function groundAverageColor (typeId, state = null) { return lookupAverageColor(groundColors, typeId, state); } /** * @param {number | string | null | undefined} typeId * @param {string | null | undefined} [state] * @returns {{ r: number, g: number, b: number } | null} */ export function blockAverageColor (typeId, state = null) { return lookupAverageColor(blockColors, typeId, state); } export { AVERAGE_COLOR_ALPHA_THRESHOLD } from "./averageSpriteColor.js"; function installGroup (target, types) { for (const type of Object.values(types ?? {})) { if (type?.typeId == null) { continue; } const stateColors = {}; for (const [state, color] of Object.entries(type.stateColors ?? {})) { const stored = freezeColor(color); if (stored) { stateColors[state] = stored; } } target.set(type.typeId, { averageColor: freezeColor(type.averageColor) ?? firstColor(stateColors), stateColors }); } } function lookupAverageColor (groups, typeId, state) { if (typeId == null) { return null; } const entry = groups.get(typeId); if (!entry) { return null; } if (state != null && state !== "") { const specific = entry.stateColors[state]; if (specific) { return specific; } } return entry.averageColor ?? null; } function firstColor (stateColors) { for (const color of Object.values(stateColors)) { if (color) { return color; } } return null; } function freezeColor (color) { if (!color) { return null; } const r = clampByte(color.r); const g = clampByte(color.g); const b = clampByte(color.b); if (r == null || g == null || b == null) { return null; } return Object.freeze({ r, g, b }); } function clampByte (value) { const number = Number(value); if (!Number.isFinite(number)) { return null; } return Math.max(0, Math.min(255, Math.round(number))); }