Files
bworld/tests/visuals_test.ts
T
2026-10-13 23:52:30 -03:00

279 lines
11 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// blocks drawn with code: the chunk mesher finds them, their visuals come and go with them and their chunks, and their
// instances are placed and turned by the time
import { assert, assertAlmostEquals, assertEquals, assertRejects } from "@std/assert";
import { mat4, vec3 } from "gl-matrix";
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
import { block_value } from "$/common/utils.ts";
import type { ModListing } from "$/common/mod_loader.ts";
import { read_bmod } from "$/common/bmod.ts";
import type { Visual } from "$/common/mod_api/client.ts";
import {
block_visuals,
type DrawnInstance,
facing_shade,
instance_matrix,
Visuals,
} from "$/client/rendering/visuals.ts";
import { load_client_mods } from "$/client/mods.ts";
import { load_and_check } from "$/tools/check_mods.ts";
import { pack_mod } from "$/tools/pack_mod.ts";
import { copy_dir, test_game } from "./helpers.ts";
const HALF = {
textures: { "0": "testmod:shaft" },
elements: [{ from: [6, 0, 6], to: [10, 8, 10], faces: { north: { texture: "#0" } } }],
};
// testmod: a shaft with an axis state and a model of half of one, and maybe a client script
function write_testmod(dir: string, client_script?: string) {
const mod = `${dir}/testmod`;
for (const folder of ["blocks", "models", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true });
const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
write("manifest.json", {
format_version: 1,
id: "testmod",
name: "Test",
version: "1.0.0",
...(client_script && { scripts: { client: "scripts/client.ts" } }),
});
write("blocks/shaft.json", {
format_version: 1,
block: {
id: "testmod:shaft",
textures: "testmod:shaft",
render_layer: "cutout",
states: [{ name: "axis", bits: 2, default: 1 }],
mining: { toughness: 1 },
},
});
write("models/half.json", { format_version: 1, model: { id: "testmod:half", ...HALF } });
if (client_script) Deno.writeTextFileSync(`${mod}/scripts/client.ts`, client_script);
}
// a game's registries with mods/bworld and testmod
async function registries() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" });
copy_dir("mods/bworld", `${dir}/bworld`);
write_testmod(dir);
await test_game(dir);
Deno.removeSync(dir, { recursive: true });
const nid = (id: string) => EverythingRegistry.get_id("blocks", id)!;
const value = (id: string, state = 0) => block_value(nid(id), state);
return { nid, value };
}
const index_of = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models they replace", async () => {
const { nid, value } = await registries();
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
worker.postMessage({
type: "init",
blocks_registry: JSON.parse(JSON.stringify(EverythingRegistry.get_registry<BlockRegistry>("blocks"))),
models: Object.fromEntries(EverythingRegistry.entries("models")),
textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [[nid("bworld:stone"), true], [nid("bworld:cobblestone"), false]],
});
const chunks = Array.from({ length: 9 }, () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT));
const middle = chunks[4];
middle[index_of(1, 64, 1)] = value("bworld:stone");
middle[index_of(4, 64, 1)] = value("bworld:cobblestone");
middle[index_of(7, 64, 1)] = value("bworld:dirt");
// deno-lint-ignore no-explicit-any
const meshed = await new Promise<any>((resolve) => {
worker.onmessage = (e) => resolve(e.data);
worker.postMessage({
type: "mesh",
chunk_x: 0,
chunk_z: 0,
version: 1,
chunks,
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
});
});
worker.terminate();
assertEquals([...meshed.visuals], [
index_of(1, 64, 1),
value("bworld:stone"),
index_of(4, 64, 1),
value("bworld:cobblestone"),
]);
// the cobblestone and the dirt, not the stone
assertEquals(meshed.solid.quad_count, 12);
// a visual can reach past its block, so the chunk is in view when that might be
assert(meshed.min_y <= 63 && meshed.max_y >= 66, `${meshed.min_y} to ${meshed.max_y}`);
});
Deno.test("a visual is made with its block, told when its client data changes, and goes with it", async () => {
const { nid, value } = await registries();
const log: string[] = [];
const data: Record<string, unknown> = { speed: 16 };
const visuals = new Visuals((x, y, z) => x === 1 && y === 64 && z === 1 ? data : undefined);
block_visuals.clear();
block_visuals.set(nid("testmod:shaft"), {
mod: "testmod",
replaces_model: true,
create(block, instances): Visual {
log.push(`create ${block.id} ${block.x} ${block.y} ${block.z} axis ${block.states.axis}`);
instances.rotating().set_rotation("y", block.get_client_data<number>("speed")!);
instances.transformed("testmod:half");
return {
update: () => log.push(`update ${block.get_client_data("speed")}`),
on_frame: (time) => log.push(`frame ${time}`),
on_delete: () => log.push(`delete ${block.x} ${block.y} ${block.z}`),
};
},
});
const shaft = (axis: number) => Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", axis));
visuals.meshed(0, 0, shaft(1));
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1"]);
// meshed again for something else, it stays
visuals.meshed(0, 0, shaft(1));
assertEquals(log.splice(0), []);
data.speed = 32;
visuals.data_changed(1, 64, 1);
visuals.data_changed(2, 64, 1);
assertEquals(log.splice(0), ["update 32"]);
// only chunks in view are drawn, each instance where its block is
const drawn: string[] = [];
const draw = (instance: DrawnInstance, x: number, y: number, z: number) =>
drawn.push(`${instance.rotation ? "rotating" : "transformed"} ${instance.quads.length} at ${x} ${y} ${z}`);
visuals.render([{ x: 1, z: 0 }], 10.5, draw);
assertEquals([log.splice(0), drawn.splice(0)], [[], []]);
visuals.render([{ x: 0, z: 0 }], 10.5, draw);
assertEquals(log.splice(0), ["frame 10.5"]);
// the block's own model is a cube, the half model has one face
assertEquals(drawn.splice(0), ["rotating 6 at 1 64 1", "transformed 1 at 1 64 1"]);
// its states changing makes it again
visuals.meshed(0, 0, shaft(2));
assertEquals(log.splice(0), ["delete 1 64 1", "create testmod:shaft 1 64 1 axis 2"]);
// and it goes with the block, or with the chunk
visuals.meshed(0, 0, new Uint32Array());
assertEquals(log.splice(0), ["delete 1 64 1"]);
assert(!visuals.has(0, 0));
visuals.meshed(0, 0, shaft(1));
visuals.unload(0, 0);
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1", "delete 1 64 1"]);
visuals.render([{ x: 0, z: 0 }], 11, draw);
assertEquals(drawn, []);
block_visuals.clear();
});
Deno.test("a visual that throws is logged and left out, and not made again until its block changes", async () => {
const { nid, value } = await registries();
let made = 0;
block_visuals.clear();
block_visuals.set(nid("testmod:shaft"), {
mod: "testmod",
replaces_model: false,
create(block, instances) {
made += 1;
instances.rotating();
if (block.states.axis === 1) throw new Error("broken");
return {
on_frame() {
made += 1;
throw new Error("broken every frame");
},
};
},
});
const visuals = new Visuals(() => undefined);
const errors: unknown[] = [];
const console_error = console.error;
console.error = (...args) => errors.push(args);
try {
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
assertEquals([made, errors.length], [1, 1]);
let drawn = 0;
visuals.render([{ x: 0, z: 0 }], 0, () => drawn += 1);
assertEquals(drawn, 0);
// an on_frame that throws isn't called again
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 2)));
for (let frame = 0; frame < 3; frame++) visuals.render([{ x: 0, z: 0 }], frame, () => {});
assertEquals([made, errors.length], [3, 2]);
} finally {
console.error = console_error;
block_visuals.clear();
}
});
Deno.test("a rotating instance turns around its block's middle by the time, rpm and offset", () => {
const near = (actual: ArrayLike<number>, expected: number[]) =>
expected.forEach((v, i) => assertAlmostEquals(actual[i], v, 1e-9));
const point = (instance: DrawnInstance, time: number, p: [number, number, number]) =>
vec3.transformMat4(vec3.create(), p, instance_matrix(mat4.create(), instance, 10, 20, 30, time));
const turning = (rpm: number, offset = 0): DrawnInstance => ({
quads: [],
tints: [],
rotation: { axis: [0, 1, 0], rpm, offset },
});
// 50 rpm is 15 degrees a tick. a quarter turn counterclockwise seen from above takes east to north
near(point(turning(50), 6, [1, 0.5, 0.5]), [10.5, 20.5, 30]);
near(point(turning(50), 0, [1, 0.5, 0.5]), [11, 20.5, 30.5]);
near(point(turning(-50), 6, [1, 0.5, 0.5]), [10.5, 20.5, 31]);
near(point(turning(0, 90), 1000, [1, 0.5, 0.5]), [10.5, 20.5, 30]);
// a transformed one is where its matrix puts it in its block
const moved: DrawnInstance = { quads: [], tints: [], matrix: mat4.fromTranslation(mat4.create(), [0, 0.25, 0]) };
near(point(moved, 0, [0.5, 0, 0.5]), [10.5, 20.25, 30.5]);
});
Deno.test("a turned quad is shaded between the sides it faces", () => {
const quad = (corners: number[][]) => corners.map((c) => vec3.fromValues(c[0], c[1], c[2]));
assertAlmostEquals(facing_shade(quad([[0, 1, 1], [1, 1, 1], [1, 1, 0], [0, 1, 0]])), 1);
assertAlmostEquals(facing_shade(quad([[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]])), 0.5);
// facing up and north at once
assertAlmostEquals(facing_shade(quad([[0, 0, 0], [1, 0, 0], [1, 1, -1], [0, 1, -1]])), 0.9);
});
Deno.test("client scripts register visuals during setup, for blocks that exist", async () => {
const load = async (script: string) => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" });
write_testmod(dir, script);
const mod = load_and_check(dir)[0];
const bmod = read_bmod(await pack_mod(mod), "testmod.bmod");
Deno.removeSync(dir, { recursive: true });
const listing: ModListing = { id: "testmod", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };
EverythingRegistry.clear();
await load_client_mods([listing], [bmod]);
};
await load(`
import type { ClientContext } from "bworld/client";
export function setup(ctx: ClientContext) {
ctx.render.register_visual("testmod:shaft", (_block, instances) => {
instances.rotating();
return {};
}, { replaces_model: true });
}
`);
const visual = block_visuals.get(EverythingRegistry.get_id("blocks", "testmod:shaft")!);
assertEquals([visual?.mod, visual?.replaces_model], ["testmod", true]);
await assertRejects(
() =>
load(`
import type { ClientContext } from "bworld/client";
export function setup(ctx: ClientContext) {
ctx.render.register_visual("testmod:gear", () => ({}));
}
`),
Error,
"unknown block testmod:gear",
);
block_visuals.clear();
});