// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // the texture atlas: the engine's textures and every mod's in one image, built by the client when it joins a server // from the textures in the server's .bmod files import { TEXTURE_SIZE } from "$/common/constants.ts"; import type { SpriteRegion } from "$/common/constants.ts"; import { type Animation, texture_animation, type TextureJson } from "$/common/texture_animation.ts"; import { AnimatedTexture } from "./texture_animations.ts"; export interface AtlasLayout { // in pixels, a power of two size: number; // by texture id regions: Record; } export interface TextureSize { width: number; height: number; } // pixels around each texture, copies of its edge, so a face whose uvs reach the texture's edge never shows a bit of // the next texture over, however the lookup rounds. see extrude_borders export const ATLAS_BORDER = 1; // shelves, tallest first so each row wastes little, and by id when they're the same size so the same textures always // give the same atlas. cubi:missing is 16×16 and always there export function atlas_layout(sizes: Map): AtlasLayout { const entries = [...sizes].filter(([id]) => id !== "cubi:missing"); entries.push(["cubi:missing", { width: TEXTURE_SIZE, height: TEXTURE_SIZE }]); entries.sort(([a, sa], [b, sb]) => sb.height - sa.height || sb.width - sa.width || a.localeCompare(b)); const area = entries.reduce( (sum, [, { width, height }]) => sum + (width + 2 * ATLAS_BORDER) * (height + 2 * ATLAS_BORDER), 0, ); const widest = Math.max(...entries.map(([, { width }]) => width + 2 * ATLAS_BORDER)); let size = 2 ** Math.ceil(Math.log2(Math.max(Math.sqrt(area), widest))); while (true) { const regions = pack_shelves(entries, size); if (regions) return { size, regions }; size *= 2; } } // undefined if they don't fit in a size × size square. regions are the textures themselves, inside their border function pack_shelves(entries: [string, TextureSize][], size: number) { const regions: Record = {}; let x = 0; let y = 0; let shelf = 0; for (const [id, { width, height }] of entries) { const [outer_width, outer_height] = [width + 2 * ATLAS_BORDER, height + 2 * ATLAS_BORDER]; if (x + outer_width > size) { x = 0; y += shelf; shelf = 0; } regions[id] = { x: x + ATLAS_BORDER, y: y + ATLAS_BORDER, width, height }; x += outer_width; shelf = Math.max(shelf, outer_height); } return y + shelf <= size ? regions : undefined; } // textures are png bytes by id, texture_json the .json of the ones that have one. ones that don't decode show as // missing. an animated texture takes one frame's room, its first frame, and plays from animated (see // texture_animations.ts) export async function build_atlas(textures: Map, texture_json = new Map()) { const images = new Map(); await Promise.all([...textures].map(async ([id, png]) => { try { images.set(id, await createImageBitmap(new Blob([png as Uint8Array], { type: "image/png" }))); } catch { console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`); } })); images.get("cubi:missing")?.close(); images.delete("cubi:missing"); const animations = new Map(); for (const [id, image] of images) { const json = texture_json.get(id); const animation = json && texture_animation(json, image); if (animation) animations.set(id, animation); } const sizes = new Map([...images].map(([id, image]) => { const animation = animations.get(id); return [id, animation ? { width: animation.frame_width, height: animation.frame_height } : image]; })); const { size, regions } = atlas_layout(sizes); const canvas = new OffscreenCanvas(size, size); const ctx = canvas.getContext("2d")!; // magenta and black checker const missing = regions["cubi:missing"]; const half = TEXTURE_SIZE / 2; ctx.fillStyle = "magenta"; ctx.fillRect(missing.x, missing.y, half, half); ctx.fillRect(missing.x + half, missing.y + half, half, half); ctx.fillStyle = "black"; ctx.fillRect(missing.x + half, missing.y, half, half); ctx.fillRect(missing.x, missing.y + half, half, half); const animated: AnimatedTexture[] = []; for (const [id, image] of images) { const animation = animations.get(id); const { x, y, width, height } = regions[id]; if (animation) { const first = animation.frames[0]; ctx.drawImage(image, first.x, first.y, width, height, x, y, width, height); animated.push(new AnimatedTexture(regions[id], animation, image_pixels(image), image.width)); } else { ctx.drawImage(image, x, y); } image.close(); } for (const id of textures.keys()) { regions[id] ??= missing; } const image_data = ctx.getImageData(0, 0, size, size); const pixels = image_data.data; extrude_borders(pixels, size, regions); ctx.putImageData(image_data, 0, 0); // which pixels of each texture can be seen, for the 3d models of dropped items (see item_model.ts) built_atlas = image_data; opaque.clear(); for (const [id, region] of Object.entries(regions)) { const mask = new Uint8Array(region.width * region.height); for (let py = 0; py < region.height; py++) { for (let px = 0; px < region.width; px++) { const i = ((region.y + py) * size + region.x + px) * 4; mask[py * region.width + px] = pixels[i + 3] > 0 ? 1 : 0; } } opaque.set(id, { width: region.width, height: region.height, mask }); } return { image: canvas.transferToImageBitmap(), regions, animated }; } // fills each region's border with copies of its edge pixels, the corners with its corners. pixels is a size × size // rgba atlas. an animated texture's border keeps its first frame's edge, only rounding ever shows it export function extrude_borders(pixels: Uint8ClampedArray, size: number, regions: Record) { const copy = (from_x: number, from_y: number, to_x: number, to_y: number) => { if (to_x < 0 || to_y < 0 || to_x >= size || to_y >= size) return; const from = (from_y * size + from_x) * 4; const to = (to_y * size + to_x) * 4; for (let c = 0; c < 4; c++) pixels[to + c] = pixels[from + c]; }; // the missing texture fills in for unknown ids too, once is enough for (const { x, y, width, height } of new Set(Object.values(regions))) { for (let b = 1; b <= ATLAS_BORDER; b++) { for (let px = -b; px < width + b; px++) { const from_x = x + Math.min(Math.max(px, 0), width - 1); copy(from_x, y, x + px, y - b); copy(from_x, y + height - 1, x + px, y + height - 1 + b); } for (let py = -b; py < height + b; py++) { const from_y = y + Math.min(Math.max(py, 0), height - 1); copy(x, from_y, x - b, y + py); copy(x + width - 1, from_y, x + width - 1 + b, y + py); } } } } // every frame of an animated texture stays in memory, to copy into the atlas when it's that frame's turn function image_pixels(image: ImageBitmap) { const ctx = new OffscreenCanvas(image.width, image.height).getContext("2d")!; ctx.drawImage(image, 0, 0); return ctx.getImageData(0, 0, image.width, image.height).data; } // a texture's pixels, 1 (can be seen) or 0, row by row from the top export interface OpaqueMask { width: number; height: number; mask: Uint8Array; } // by texture id const opaque = new Map(); // which pixels of a texture aren't fully see-through, undefined before the atlas is built or for unknown textures export function opaque_pixels(texture_id: string): OpaqueMask | undefined { return opaque.get(texture_id); } // the last atlas built, before any animated texture moved on from its first frame let built_atlas: ImageData | undefined; // the atlas as a png, undefined before one is built. for the f3 screen's copy button export function atlas_png(): Promise | undefined { if (!built_atlas) return undefined; const canvas = new OffscreenCanvas(built_atlas.width, built_atlas.height); canvas.getContext("2d")!.putImageData(built_atlas, 0, 0); return canvas.convertToBlob({ type: "image/png" }); } // the engine's own textures, which come with the client instead of a mod. see build_engine_textures in build.ts export async function engine_textures(): Promise> { const names: string[] = await (await fetch("/assets/textures/index.json")).json(); const textures = new Map(); await Promise.all(names.map(async (name) => { const response = await fetch(`/assets/textures/${name}.png`); textures.set(`cubi:${name}`, new Uint8Array(await response.arrayBuffer())); })); return textures; }