Allow for textures that aren't 16x16

This commit is contained in:
2026-09-28 16:20:37 -03:00
parent 52ef4e5ca6
commit fe149bb9ad
18 changed files with 268 additions and 136 deletions
+3 -1
View File
@@ -204,7 +204,9 @@ program**, so the server and each client can number blocks differently. Saves an
- Every `.png` in `textures/` becomes a texture with id `<mod_id>:<file name without .png>`. Subfolders are joined with
`_`, so `textures/ores/tin.png` becomes `<mod_id>:ores_tin`.
- Textures are 16×16. They go in the mod's `.bmod`, and clients put every mod's textures into one atlas when they join.
- Textures can be any size up to 256×256. Blocks and items are made for 16×16 and stretch a texture of another size
over the same face, so a 32×32 block texture is just a sharper one. Bigger ones are for things like entity sprites.
- They go in the mod's `.bmod`, and clients put every mod's textures into one atlas when they join.
- A missing texture shows the magenta and black checker (`engine:missing`) and logs a warning. It isn't a load error.
- The engine's own textures use the `engine` namespace: `engine:missing` and the breaking cracks `engine:break_0` to
`engine:break_8`. They come from `assets/`, not from a mod.
+81 -37
View File
@@ -6,71 +6,115 @@ import type { SpriteRegion } from "$/common/constants.ts";
export interface AtlasLayout {
// in pixels, a power of two
size: number;
// in sprites, by texture id. engine:missing is always at 0, 0
// by texture id
regions: Record<string, SpriteRegion>;
}
// engine:missing first, then every other texture sorted by id, row by row
export function atlas_layout(ids: Iterable<string>): AtlasLayout {
const sorted = [...new Set(ids)].filter((id) => id !== "engine:missing").sort((a, b) => a.localeCompare(b));
const count = sorted.length + 1;
const size = 2 ** Math.ceil(Math.log2(Math.ceil(Math.sqrt(count)) * TEXTURE_SIZE));
const per_row = size / TEXTURE_SIZE;
const regions: Record<string, SpriteRegion> = { "engine:missing": { x: 0, y: 0 } };
sorted.forEach((id, i) => {
regions[id] = { x: (i + 1) % per_row, y: Math.floor((i + 1) / per_row) };
});
return { size, regions };
export interface TextureSize {
width: number;
height: number;
}
// 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. engine:missing is 16×16 and always there
export function atlas_layout(sizes: Map<string, TextureSize>): AtlasLayout {
const entries = [...sizes].filter(([id]) => id !== "engine:missing");
entries.push(["engine: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 * height, 0);
const widest = Math.max(...entries.map(([, { width }]) => width));
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
function pack_shelves(entries: [string, TextureSize][], size: number) {
const regions: Record<string, SpriteRegion> = {};
let x = 0;
let y = 0;
let shelf = 0;
for (const [id, { width, height }] of entries) {
if (x + width > size) {
x = 0;
y += shelf;
shelf = 0;
}
regions[id] = { x, y, width, height };
x += width;
shelf = Math.max(shelf, height);
}
return y + shelf <= size ? regions : undefined;
}
// textures are png bytes by id. ones that don't decode show as missing
export async function build_atlas(textures: Map<string, Uint8Array>) {
const { size, regions } = atlas_layout(textures.keys());
const images = new Map<string, ImageBitmap>();
await Promise.all([...textures].map(async ([id, png]) => {
try {
images.set(id, await createImageBitmap(new Blob([png as Uint8Array<ArrayBuffer>], { type: "image/png" })));
} catch {
console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`);
}
}));
images.get("engine:missing")?.close();
images.delete("engine:missing");
const { size, regions } = atlas_layout(new Map([...images].map(([id, image]) => [id, image])));
const canvas = new OffscreenCanvas(size, size);
const ctx = canvas.getContext("2d")!;
// magenta and black checker
const missing = regions["engine:missing"];
const half = TEXTURE_SIZE / 2;
ctx.fillStyle = "magenta";
ctx.fillRect(0, 0, 8, 8);
ctx.fillRect(8, 8, 8, 8);
ctx.fillRect(missing.x, missing.y, half, half);
ctx.fillRect(missing.x + half, missing.y + half, half, half);
ctx.fillStyle = "black";
ctx.fillRect(8, 0, 8, 8);
ctx.fillRect(0, 8, 8, 8);
ctx.fillRect(missing.x + half, missing.y, half, half);
ctx.fillRect(missing.x, missing.y + half, half, half);
await Promise.all([...textures].map(async ([id, png]) => {
const region = regions[id];
try {
const image = await createImageBitmap(new Blob([png as Uint8Array<ArrayBuffer>], { type: "image/png" }));
ctx.drawImage(image, region.x * TEXTURE_SIZE, region.y * TEXTURE_SIZE);
image.close();
} catch {
console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`);
regions[id] = regions["engine:missing"];
}
}));
for (const [id, image] of images) {
ctx.drawImage(image, regions[id].x, regions[id].y);
image.close();
}
for (const id of textures.keys()) {
regions[id] ??= missing;
}
// which pixels of each texture can be seen, for the 3d models of dropped items (see item_model.ts)
const pixels = ctx.getImageData(0, 0, size, size).data;
opaque.clear();
for (const [id, region] of Object.entries(regions)) {
const mask = new Uint8Array(TEXTURE_SIZE * TEXTURE_SIZE);
for (let py = 0; py < TEXTURE_SIZE; py++) {
for (let px = 0; px < TEXTURE_SIZE; px++) {
const i = ((region.y * TEXTURE_SIZE + py) * size + region.x * TEXTURE_SIZE + px) * 4;
mask[py * TEXTURE_SIZE + px] = pixels[i + 3] > 0 ? 1 : 0;
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, mask);
opaque.set(id, { width: region.width, height: region.height, mask });
}
return { image: canvas.transferToImageBitmap(), regions };
}
// by texture id, TEXTURE_SIZE * TEXTURE_SIZE of 1 (can be seen) or 0, row by row from the top
const opaque = new Map<string, Uint8Array>();
// 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<string, OpaqueMask>();
// 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): Uint8Array | undefined {
export function opaque_pixels(texture_id: string): OpaqueMask | undefined {
return opaque.get(texture_id);
}
+13 -13
View File
@@ -1,7 +1,7 @@
import { add_player_hotbar, add_player_inventory, GuiInventoryScreen, Slot } from "./gui_screen.ts";
import { canvas, draw_rect, draw_texture_region, Texture } from "$/client/renderer/mod.ts";
import { AssetManager } from "../assets.ts";
import { SLOT_SIZE, TEXTURE_SIZE } from "$/common/constants.ts";
import { SLOT_SIZE } from "$/common/constants.ts";
import { ClientMessage, ScreenLayout } from "$/common/protocol.ts";
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
import { get_sprite_region } from "$/client/sprites.ts";
@@ -62,10 +62,10 @@ export class GuiContainer extends GuiInventoryScreen {
const empty = get_sprite_region(bar.empty_texture);
draw_texture_region(
atlas,
empty.x * TEXTURE_SIZE,
empty.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
empty.x,
empty.y,
empty.width,
empty.height,
x,
y,
SLOT_SIZE,
@@ -76,10 +76,10 @@ export class GuiContainer extends GuiInventoryScreen {
if (bar.direction === "right") {
draw_texture_region(
atlas,
full.x * TEXTURE_SIZE,
full.y * TEXTURE_SIZE,
TEXTURE_SIZE * pct,
TEXTURE_SIZE,
full.x,
full.y,
full.width * pct,
full.height,
x,
y,
SLOT_SIZE * pct,
@@ -89,10 +89,10 @@ export class GuiContainer extends GuiInventoryScreen {
// fills from the bottom up
draw_texture_region(
atlas,
full.x * TEXTURE_SIZE,
full.y * TEXTURE_SIZE + TEXTURE_SIZE * (1 - pct),
TEXTURE_SIZE,
TEXTURE_SIZE * pct,
full.x,
full.y + full.height * (1 - pct),
full.width,
full.height * pct,
x,
y + SLOT_SIZE * (1 - pct),
SLOT_SIZE,
+5 -5
View File
@@ -1,6 +1,6 @@
// the immediate mode drawing mods' client scripts get (Graphics in common/mod_api/client.ts), on top of the renderer.
// one per screen, so text inputs keep their text and focus while it's open
import { SLOT_SIZE, TEXTURE_SIZE } from "$/common/constants.ts";
import { SLOT_SIZE } from "$/common/constants.ts";
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import { ItemStack } from "$/common/inventory.ts";
import type { Color, Graphics } from "$/common/mod_api/client.ts";
@@ -102,10 +102,10 @@ export class ModGraphics implements Graphics {
const region = get_sprite_region(id);
draw_texture_region(
atlas,
region.x * TEXTURE_SIZE,
region.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
region.x,
region.y,
region.width,
region.height,
x,
y,
w,
+39 -25
View File
@@ -1,20 +1,19 @@
// the 3d model of a flat item, like minecraft's item/generated: its sprite on the front and back, one pixel apart, with
// a side face along every edge between a pixel that can be seen and one that can't (or the sprite's border)
import { TEXTURE_SIZE } from "$/common/constants.ts";
import { opaque_pixels } from "$/client/atlas.ts";
import { opaque_pixels, type OpaqueMask } from "$/client/atlas.ts";
export interface ItemQuad {
// 4 corners counter clockwise seen from outside. x from -0.5 to 0.5 and y from 0 to 1 across the sprite, z its
// thickness around 0
corners: [number, number, number][];
// u v per corner, in pixels of the sprite (0 to TEXTURE_SIZE, v down)
// u v per corner, in pixels of the sprite (0 to its width or height, v down)
uvs: [number, number][];
shade: number;
}
// one pixel of a 16 pixel sprite
const PIXEL = 1 / TEXTURE_SIZE;
const HALF_THICKNESS = PIXEL / 2;
// as thick as a pixel of a 16 pixel sprite, whatever the sprite's size
const HALF_THICKNESS = 1 / TEXTURE_SIZE / 2;
// keeps lookups off the neighboring sprite, and side faces in the middle of their pixel
const FACE_PAD = 0.02;
const SIDE_PAD = 0.25;
@@ -37,35 +36,50 @@ export function item_model(texture_id: string): ItemQuad[] {
}
// the model for a sprite's opaque pixels (see opaque_pixels in atlas.ts)
export function extrude_item(mask: Uint8Array | undefined): ItemQuad[] {
// without a mask it's a 16×16 sprite
export function extrude_item(opaque: OpaqueMask | undefined): ItemQuad[] {
const width = opaque?.width ?? TEXTURE_SIZE;
const height = opaque?.height ?? TEXTURE_SIZE;
const t = HALF_THICKNESS;
const lo = FACE_PAD;
const hi = TEXTURE_SIZE - FACE_PAD;
const [u_lo, u_hi] = [FACE_PAD, width - FACE_PAD];
const [v_lo, v_hi] = [FACE_PAD, height - FACE_PAD];
const quads: ItemQuad[] = [
// the front, and the back mirrored so it reads the same way round as minecraft's
quad([[-0.5, 0, t], [0.5, 0, t], [0.5, 1, t], [-0.5, 1, t]], [[lo, hi], [hi, hi], [hi, lo], [lo, lo]], [
0,
0,
quad(
[[-0.5, 0, t], [0.5, 0, t], [0.5, 1, t], [-0.5, 1, t]],
[[u_lo, v_hi], [u_hi, v_hi], [u_hi, v_lo], [
u_lo,
v_lo,
]],
[0, 0, 1],
1,
], 1),
quad([[0.5, 0, -t], [-0.5, 0, -t], [-0.5, 1, -t], [0.5, 1, -t]], [[hi, hi], [lo, hi], [lo, lo], [hi, lo]], [
0,
0,
-1,
], 1),
),
quad(
[[0.5, 0, -t], [-0.5, 0, -t], [-0.5, 1, -t], [0.5, 1, -t]],
[[u_hi, v_hi], [u_lo, v_hi], [u_lo, v_lo], [
u_hi,
v_lo,
]],
[0, 0, -1],
1,
),
];
if (!mask) return quads;
if (!opaque) return quads;
const { mask } = opaque;
const seen = (px: number, py: number) =>
px >= 0 && py >= 0 && px < TEXTURE_SIZE && py < TEXTURE_SIZE && mask[py * TEXTURE_SIZE + px] === 1;
px >= 0 && py >= 0 && px < width && py < height && mask[py * width + px] === 1;
for (let py = 0; py < TEXTURE_SIZE; py++) {
for (let px = 0; px < TEXTURE_SIZE; px++) {
// a sprite that isn't square is squeezed into the square
const pixel_w = 1 / width;
const pixel_h = 1 / height;
for (let py = 0; py < height; py++) {
for (let px = 0; px < width; px++) {
if (!seen(px, py)) continue;
const x0 = px * PIXEL - 0.5;
const x1 = x0 + PIXEL;
const y1 = 1 - py * PIXEL;
const y0 = y1 - PIXEL;
const x0 = px * pixel_w - 0.5;
const x1 = x0 + pixel_w;
const y1 = 1 - py * pixel_h;
const y0 = y1 - pixel_h;
// the whole side face is this pixel's color
const u0 = px + SIDE_PAD;
const u1 = px + 1 - SIDE_PAD;
+8 -8
View File
@@ -1,4 +1,4 @@
import { TEXTURE_SIZE } from "$/common/constants.ts";
import type { SpriteRegion } from "$/common/constants.ts";
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { AssetManager } from "$/client/assets.ts";
import { get_sprite_region } from "$/client/sprites.ts";
@@ -91,8 +91,8 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf
const texture_id = item_texture(item);
const region = get_sprite_region(texture_id);
const u = (pixels: number) => (region.x * TEXTURE_SIZE + pixels) / atlas.width;
const v = (pixels: number) => (region.y * TEXTURE_SIZE + pixels) / atlas.height;
const u = (pixels: number) => (region.x + pixels) / atlas.width;
const v = (pixels: number) => (region.y + pixels) / atlas.height;
for (const quad of item_model(texture_id)) {
for (const i of [0, 1, 2, 0, 2, 3]) {
const [px, py, pz] = transform(...quad.corners[i]);
@@ -102,11 +102,11 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf
}
}
function push_textured_quad(atlas: Texture, region: { x: number; y: number }, corners: number[][], color: number[]) {
const u0 = (region.x * TEXTURE_SIZE + UV_PAD) / atlas.width;
const v0 = (region.y * TEXTURE_SIZE + UV_PAD) / atlas.height;
const u1 = ((region.x + 1) * TEXTURE_SIZE - UV_PAD) / atlas.width;
const v1 = ((region.y + 1) * TEXTURE_SIZE - UV_PAD) / atlas.height;
function push_textured_quad(atlas: Texture, region: SpriteRegion, corners: number[][], color: number[]) {
const u0 = (region.x + UV_PAD) / atlas.width;
const v0 = (region.y + UV_PAD) / atlas.height;
const u1 = (region.x + region.width - UV_PAD) / atlas.width;
const v1 = (region.y + region.height - UV_PAD) / atlas.height;
for (const i of [0, 1, 2, 0, 2, 3]) {
const [px, py, pz] = corners[i];
+4 -5
View File
@@ -1,4 +1,3 @@
import { TEXTURE_SIZE } from "$/common/constants.ts";
import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel } from "$/client/level/client_level.ts";
import { Camera } from "$/client/camera.ts";
import { AssetManager } from "$/client/assets.ts";
@@ -138,10 +137,10 @@ export class LevelRenderer {
block.x,
block.y,
block.z,
region.x * TEXTURE_SIZE,
region.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
region.x,
region.y,
region.width,
region.height,
);
}
}
+13 -13
View File
@@ -1,4 +1,4 @@
import { SLOT_SIZE, TEXTURE_SIZE } from "$/common/constants.ts";
import { SLOT_SIZE } from "$/common/constants.ts";
import { get_sprite_region } from "$/client/sprites.ts";
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { AssetManager } from "$/client/assets.ts";
@@ -132,10 +132,10 @@ function draw_item_block(block_info: BlockRegistry, x: number, y: number) {
draw_texture_region_skewed(
atlas,
top.x * TEXTURE_SIZE,
top.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
top.x,
top.y,
top.width,
top.height,
[
{ x: cx, y: cy - half_h },
{ x: cx + half_w, y: cy },
@@ -146,10 +146,10 @@ function draw_item_block(block_info: BlockRegistry, x: number, y: number) {
);
draw_texture_region_skewed(
atlas,
left.x * TEXTURE_SIZE,
left.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
left.x,
left.y,
left.width,
left.height,
[
{ x: cx - half_w, y: cy },
{ x: cx, y: cy + half_h },
@@ -160,10 +160,10 @@ function draw_item_block(block_info: BlockRegistry, x: number, y: number) {
);
draw_texture_region_skewed(
atlas,
front.x * TEXTURE_SIZE,
front.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
front.x,
front.y,
front.width,
front.height,
[
{ x: cx + half_w, y: cy },
{ x: cx, y: cy + half_h },
+3 -2
View File
@@ -1,9 +1,10 @@
import { SpriteRegion } from "$/common/constants.ts";
import { type SpriteRegion, TEXTURE_SIZE } from "$/common/constants.ts";
import { AssetManager } from "./assets.ts";
type TexturesInfo = Record<string, SpriteRegion>;
export function get_sprite_region(id: string): SpriteRegion {
const textures_info = AssetManager.instance.get<TexturesInfo>("bworld:textures_info");
return textures_info?.[id] ?? { x: 0, y: 0 };
return textures_info?.[id] ?? textures_info?.["engine:missing"] ??
{ x: 0, y: 0, width: TEXTURE_SIZE, height: TEXTURE_SIZE };
}
+5 -3
View File
@@ -396,13 +396,15 @@ function push_quad(
buffer.count += 1;
}
// pixels of a sprite to atlas coordinates, kept off the sprite's edge
// model uvs (0 to TEXTURE_SIZE across the sprite, whatever its size) to atlas coordinates, kept off the sprite's edge
function atlas_u(sprite: SpriteRegion, u: number) {
return (sprite.x * TEXTURE_SIZE + Math.min(Math.max(u, UV_PAD), TEXTURE_SIZE - UV_PAD)) / image.width;
const px = u * sprite.width / TEXTURE_SIZE;
return (sprite.x + Math.min(Math.max(px, UV_PAD), sprite.width - UV_PAD)) / image.width;
}
function atlas_v(sprite: SpriteRegion, v: number) {
return (sprite.y * TEXTURE_SIZE + Math.min(Math.max(v, UV_PAD), TEXTURE_SIZE - UV_PAD)) / image.height;
const px = v * sprite.height / TEXTURE_SIZE;
return (sprite.y + Math.min(Math.max(px, UV_PAD), sprite.height - UV_PAD)) / image.height;
}
// the model quads for a block value, baked the first time it's seen
+11 -2
View File
@@ -2,6 +2,7 @@
// MODS.md. the same code reads them on the server and in the browser, so it only works on bytes
import { unzipSync, zipSync } from "fflate";
import type { ModelJson } from "./block_models.ts";
import { MAX_TEXTURE_SIZE } from "./constants.ts";
import {
type BlockJson,
ID_PATTERN,
@@ -162,8 +163,8 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
problems.push(`${name}: texture names must be a-z, 0-9 and _`);
} else if (!size) {
problems.push(`${name}: isn't a png`);
} else if (size.width !== 16 || size.height !== 16) {
problems.push(`${name}: is ${size.width}×${size.height}, textures must be 16×16`);
} else if (texture_size_problem(size)) {
problems.push(`${name}: ${texture_size_problem(size)}`);
} else {
textures.set(id, content);
}
@@ -193,6 +194,14 @@ function checked(list: unknown, name: string, validate: (json: unknown) => strin
return list;
}
// textures can be any size up to MAX_TEXTURE_SIZE, like 64×32 for an entity. blocks and items stretch theirs to fit
export function texture_size_problem(size: { width: number; height: number }): string | undefined {
const { width, height } = size;
if (width < 1 || height < 1 || width > MAX_TEXTURE_SIZE || height > MAX_TEXTURE_SIZE) {
return `is ${width}×${height}, textures can be at most ${MAX_TEXTURE_SIZE}×${MAX_TEXTURE_SIZE}`;
}
}
// reads the size out of the png header instead of decoding the image
export function png_size(bytes: Uint8Array): { width: number; height: number } | undefined {
const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
+7
View File
@@ -1,13 +1,20 @@
// the pixels across a block face or an item sprite. block models and item models are made in these units, a texture of
// another size is stretched to fit
export const TEXTURE_SIZE = 16;
// the most a texture can be on either side, entity sprites are bigger than blocks'
export const MAX_TEXTURE_SIZE = 256;
export const TICKS_PER_SECOND = 20;
export const TICK_DELTA = 1 / TICKS_PER_SECOND;
export const SLOT_SIZE = 18 * 3;
// where a texture is in the atlas, in pixels
export interface SpriteRegion {
x: number;
y: number;
width: number;
height: number;
}
export const faces = ["west", "east", "bottom", "top", "north", "south"] as const;
+42 -11
View File
@@ -2,6 +2,7 @@
import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows } from "@std/assert";
import { zipSync } from "fflate";
import { atlas_layout } from "$/client/atlas.ts";
import { MAX_TEXTURE_SIZE } from "$/common/constants.ts";
import { read_bmod, write_bmod } from "$/common/bmod.ts";
import { load_and_check } from "$/tools/check_mods.ts";
import { pack_mod } from "$/tools/pack_mod.ts";
@@ -79,16 +80,19 @@ Deno.test("broken .bmod files are turned away, saying why", () => {
Error,
"scripts.server scripts/server.js isn't in the file",
);
// a texture that isn't 16x16
const ui = Deno.readFileSync("assets/sprites/gui.png");
// a texture bigger than MAX_TEXTURE_SIZE. only its header is read
const big = new Uint8Array(24);
big.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
new DataView(big.buffer).setUint32(16, MAX_TEXTURE_SIZE * 2);
new DataView(big.buffer).setUint32(20, 16);
assertThrows(
() =>
read_bmod(
zip({ "manifest.json": text(manifest), "data.json": text({}), "textures/big.png": ui }),
zip({ "manifest.json": text(manifest), "data.json": text({}), "textures/big.png": big }),
"e.bmod",
),
Error,
"textures must be 16×16",
`textures can be at most ${MAX_TEXTURE_SIZE}×${MAX_TEXTURE_SIZE}`,
);
// too much once unzipped, without unzipping it all
const huge = new Uint8Array(65 * 1024 * 1024);
@@ -193,16 +197,43 @@ Deno.test("a mod with its own deno.json is bundled with it", async () => {
Deno.removeSync(sources, { recursive: true });
});
Deno.test("the atlas puts the missing texture first and the rest in order", () => {
const layout = atlas_layout(["b:two", "a:one", "engine:break_0", "a:one"]);
const sizes = (entries: [string, number, number][]) =>
new Map(entries.map(([id, width, height]) => [id, { width, height }]));
Deno.test("the atlas lays out same sized textures by id, with the missing texture among them", () => {
const layout = atlas_layout(sizes([["b:two", 16, 16], ["a:one", 16, 16], ["engine:break_0", 16, 16]]));
assertEquals(layout.size, 32);
assertEquals(layout.regions, {
"engine:missing": { x: 0, y: 0 },
"a:one": { x: 1, y: 0 },
"b:two": { x: 0, y: 1 },
"engine:break_0": { x: 1, y: 1 },
"a:one": { x: 0, y: 0, width: 16, height: 16 },
"b:two": { x: 16, y: 0, width: 16, height: 16 },
"engine:break_0": { x: 0, y: 16, width: 16, height: 16 },
"engine:missing": { x: 16, y: 16, width: 16, height: 16 },
});
assertEquals(atlas_layout(Array.from({ length: 100 }, (_, i) => `m:t${i}`)).size, 256);
const many = atlas_layout(sizes(Array.from({ length: 100 }, (_, i) => [`m:t${i}`, 16, 16])));
assertEquals(many.size, 256);
});
Deno.test("the atlas fits textures of any size, tallest first, without overlapping", () => {
const layout = atlas_layout(
sizes([["a:block", 16, 16], ["a:zombie", 64, 64], ["a:boat", 128, 32], ["a:x", 8, 24]]),
);
assertEquals(layout.size, 128);
assertEquals(layout.regions["a:zombie"], { x: 0, y: 0, width: 64, height: 64 });
assertEquals(layout.regions["a:boat"], { x: 0, y: 64, width: 128, height: 32 });
assertEquals(layout.regions["a:x"], { x: 0, y: 96, width: 8, height: 24 });
const big = atlas_layout(
sizes(Array.from({ length: 40 }, (_, i) => [`m:t${i}`, 16 + (i % 5) * 12, 8 + (i % 7) * 9])),
);
const regions = Object.values(big.regions);
for (const [i, a] of regions.entries()) {
assert(a.x >= 0 && a.y >= 0 && a.x + a.width <= big.size && a.y + a.height <= big.size);
for (const b of regions.slice(i + 1)) {
const apart = a.x + a.width <= b.x || b.x + b.width <= a.x || a.y + a.height <= b.y ||
b.y + b.height <= a.y;
assert(apart, `${JSON.stringify(a)} overlaps ${JSON.stringify(b)}`);
}
}
});
// write_bmod without anything optional still makes a file read_bmod takes
+23 -5
View File
@@ -3,10 +3,10 @@ import { assert, assertEquals } from "@std/assert";
import { extrude_item, type ItemQuad } from "$/client/rendering/item_model.ts";
import { TEXTURE_SIZE } from "$/common/constants.ts";
function mask(pixels: [number, number][]) {
const mask = new Uint8Array(TEXTURE_SIZE * TEXTURE_SIZE);
for (const [x, y] of pixels) mask[y * TEXTURE_SIZE + x] = 1;
return mask;
function mask(pixels: [number, number][], width = TEXTURE_SIZE, height = TEXTURE_SIZE) {
const mask = new Uint8Array(width * height);
for (const [x, y] of pixels) mask[y * width + x] = 1;
return { width, height, mask };
}
// each quad's corners go counter clockwise seen from outside, or it's culled from the side it should show
@@ -32,7 +32,11 @@ Deno.test("only edges next to nothing get a side, and see-through pixels get non
// two pixels side by side share an edge, so 6 sides instead of 8
assertEquals(extrude_item(mask([[0, 0], [1, 0]])).length, 2 + 6);
// a full sprite only has its border
const full = extrude_item(new Uint8Array(TEXTURE_SIZE * TEXTURE_SIZE).fill(1));
const full = extrude_item({
width: TEXTURE_SIZE,
height: TEXTURE_SIZE,
mask: new Uint8Array(TEXTURE_SIZE * TEXTURE_SIZE).fill(1),
});
assertEquals(full.length, 2 + 4 * TEXTURE_SIZE);
// nothing to see, only the (see-through) front and back
assertEquals(extrude_item(mask([])).length, 2);
@@ -47,3 +51,17 @@ Deno.test("side faces show their pixel's color, and the model is one pixel thick
for (const [, , z] of side.corners) assertEquals(Math.abs(z), 0.5 / TEXTURE_SIZE);
}
});
Deno.test("a bigger sprite has smaller pixels, and is as thick as a 16 pixel one", () => {
const [front, , ...sides] = extrude_item(mask([[31, 0]], 32, 64));
// the front covers the whole sprite
assert(front.uvs.some(([u, v]) => u > 31 && v > 63));
// the top right pixel: 1/32 across and 1/64 down
for (const side of sides) {
for (const [x, y, z] of side.corners) {
assert(x >= 0.5 - 1 / 32 - 1e-9 && x <= 0.5 + 1e-9, `x ${x}`);
assert(y >= 1 - 1 / 64 - 1e-9 && y <= 1 + 1e-9, `y ${y}`);
assertEquals(Math.abs(z), 0.5 / TEXTURE_SIZE);
}
}
});
+6 -1
View File
@@ -1,5 +1,6 @@
import { assert, assertEquals, assertThrows } from "@std/assert";
import { check_mods } from "$/tools/check_mods.ts";
import { MAX_TEXTURE_SIZE } from "$/common/constants.ts";
import { create_mod } from "$/tools/new_mod.ts";
function temp_mods_dir() {
@@ -92,7 +93,11 @@ Deno.test("check-mods finds broken mods", async () => {
},
});
// wrong texture size
Deno.copyFileSync("assets/sprites/gui.png", `${mod}/textures/huge.png`);
const huge = new Uint8Array(24);
huge.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
new DataView(huge.buffer).setUint32(16, MAX_TEXTURE_SIZE + 1);
new DataView(huge.buffer).setUint32(20, 16);
Deno.writeFileSync(`${mod}/textures/huge.png`, huge);
// a script that doesn't typecheck
Deno.writeTextFileSync(`${mod}/scripts/client.ts`, "export function setup(ctx: number) { ctx.nope(); }\n");
// a dependency that isn't installed, and no longer depending on bworld
+1 -1
View File
@@ -53,7 +53,7 @@ async function mesh_chunks(radius: number) {
type: "init",
blocks_registry: JSON.parse(JSON.stringify(blocks)),
models: {},
textures_info: { "engine:missing": { x: 0, y: 0 } },
textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
});
+1 -1
View File
@@ -21,7 +21,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
type: "init",
blocks_registry: JSON.parse(JSON.stringify(blocks)),
models: {},
textures_info: { "engine:missing": { x: 0, y: 0 } },
textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
});
+3 -3
View File
@@ -11,7 +11,7 @@ import {
validate_recipe,
} from "$/common/mod_data.ts";
import { check_references, load_order, type LoadedMod, type ModReport } from "$/common/mod_check.ts";
import { png_size } from "$/common/bmod.ts";
import { png_size, texture_size_problem } from "$/common/bmod.ts";
export { load_order, type LoadedMod, type ModReport };
@@ -140,8 +140,8 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
const size = png_size(Deno.readFileSync(`${dir}/textures/${file}`));
if (!size) {
error(`textures/${file}: isn't a png`);
} else if (size.width !== 16 || size.height !== 16) {
error(`textures/${file}: is ${size.width}×${size.height}, textures must be 16×16`);
} else if (texture_size_problem(size)) {
error(`textures/${file}: ${texture_size_problem(size)}`);
}
}