Fluid and item visuals

This commit is contained in:
2026-10-25 18:46:48 -03:00
parent 08df7f1b6b
commit 233c518def
15 changed files with 549 additions and 122 deletions
+130 -11
View File
@@ -3,15 +3,15 @@
// blocks drawn with code: the chunk mesher finds them, their visuals come and go with them and their chunks, and the gpu
// draws their instances, placed and turned by the time
import { assert, assertEquals, assertRejects } from "@std/assert";
import { assert, assertEquals, assertRejects, assertThrows } from "@std/assert";
import { mat4 } 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 { RotatingInstance, Visual } from "$/common/mod_api/client.ts";
import { block_visuals, InstanceGroup, pack_model, Visuals } from "$/client/rendering/visuals.ts";
import type { FluidInstance, Instances, RotatingInstance, Visual } from "$/common/mod_api/client.ts";
import { block_visuals, instance_quads, InstanceGroup, pack_model, Visuals } from "$/client/rendering/visuals.ts";
import { INSTANCE_FLOATS, INSTANCED_BUFFERS, terrain_shader_src, type Texture } from "$/client/renderer/mod.ts";
import type { BakedQuad } from "$/common/block_models.ts";
import { AssetManager } from "$/client/assets.ts";
@@ -25,10 +25,13 @@ const HALF = {
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
// testmod: a shaft with an axis state and a model of half of one, syrup, a jar drawn with the syrup in it, 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 });
for (const folder of ["blocks", "models", "scripts", "fluids", "items"]) {
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,
@@ -48,16 +51,30 @@ function write_testmod(dir: string, client_script?: string) {
},
});
write("models/half.json", { format_version: 1, model: { id: "testmod:half", ...HALF } });
write("fluids/syrup.json", {
format_version: 1,
fluid: { id: "testmod:syrup", color: "#a0522d", texture: "testmod:syrup_still" },
});
write("items/jar.json", {
format_version: 1,
item: {
id: "testmod:jar",
texture: "engine:missing",
fluid_container: { capacity: 250 },
layers: [{ texture: "engine:break_0", tint: "fluid" }],
},
});
if (client_script) Deno.writeTextFileSync(`${mod}/scripts/client.ts`, client_script);
}
// a game's registries with mods/bworld and testmod
// a game's registries with mods/bworld and testmod. there's no atlas, so every texture is where the missing one would be
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 });
AssetManager.instance.assets["bworld:textures_info"] = {};
const nid = (id: string) => EverythingRegistry.get_id("blocks", id)!;
const value = (id: string, state = 0) => block_value(nid(id), state);
return { nid, value };
@@ -262,6 +279,110 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl
block_visuals.clear();
});
// a visual on one shaft, at 1 64 1, that makes what make does
function one_visual(nid: (id: string) => number, value: (id: string) => number, make: (instances: Instances) => void) {
const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => 0 });
block_visuals.clear();
block_visuals.set(nid("testmod:shaft"), {
mod: "testmod",
replaces_model: false,
create(_block, instances) {
make(instances);
return {};
},
});
const mesh = (blocks: number[]) => visuals.meshed(0, 0, Uint32Array.from(blocks));
mesh([index_of(1, 64, 1), value("testmod:shaft")]);
return { visuals, mesh };
}
// the smallest and biggest of every nth number from the first'th, like an axis of a model's positions or uvs
const range = (groups: InstanceGroup[], numbers: "positions" | "uvs", nth: number, first: number) => {
const picked = groups.flatMap((group) => group.quads.flatMap((quad) => quad[numbers]))
.filter((_, i) => i % nth === first);
return [Math.min(...picked), Math.max(...picked)];
};
const SYRUP = [0xa0 / 255, 0x52 / 255, 0x2d / 255];
Deno.test("an item is drawn the size it is on the ground, with one model for every stack that looks the same", async () => {
const { nid, value } = await registries();
const full = { fluid: { id: "testmod:syrup" } };
const { visuals } = one_visual(nid, value, (instances) => {
instances.item({ id: "testmod:jar", count: 16 });
instances.item({ id: "testmod:jar", count: 1 });
instances.item({ id: "testmod:jar", count: 1, data: full });
instances.item({ id: "testmod:shaft", count: 1 });
assertThrows(
() => instances.item({ id: "testmod:nothing", count: 1 }),
Error,
"there's no item testmod:nothing",
);
});
// the jar's front and back, and its syrup's when it's full, and the shaft's item is a cube. one of each, whatever the
// count
assertEquals(drawn(visuals), ["2 quads x2", "4 quads x1", "6 quads x1"]);
const [empty, filled, cube] = [...visuals.groups()].filter((group) => group.instances.length > 0);
assertEquals(filled.quads.slice(2).map((quad) => quad.tint), [SYRUP, SYRUP]);
// half a block across like a dropped item, and a block a quarter, around the block's middle
assertEquals([range([empty], "positions", 3, 0), range([empty], "positions", 3, 1)], [[0.25, 0.75], [0.25, 0.75]]);
assertEquals([0, 1, 2].map((axis) => range([cube], "positions", 3, axis)), [
[0.375, 0.625],
[0.375, 0.625],
[0.375, 0.625],
]);
block_visuals.clear();
});
Deno.test("a fluid's box is its texture cut to fit and tinted in its color, a model of its own that goes with it", async () => {
const { nid, value } = await registries();
AssetManager.instance.assets["bworld:textures_info"] = {
"testmod:syrup_still": { x: 32, y: 0, width: 16, height: 16 },
};
let box: FluidInstance | undefined;
const { visuals, mesh } = one_visual(nid, value, (instances) => {
box = instances.fluid({ id: "testmod:syrup" });
assertThrows(() => instances.fluid({ id: "testmod:nothing" }), Error, "there's no fluid testmod:nothing");
});
const boxes = () => [...visuals.groups()].filter((group) => group.translucent);
// nothing until it has a box
assertEquals(boxes().map((group) => group.quads.length), [0]);
box!.set_box([2, 2, 2], [14, 8, 14]);
const [group] = boxes();
assertEquals(group.quads.length, 6);
assert(group.quads.every((quad) => quad.tint === group.quads[0].tint && quad.shade));
assertEquals(group.quads[0].tint, SYRUP);
// in the block's space, and its top is the middle 12 pixels of the texture, not all 16 squeezed into it
assertEquals([0, 1, 2].map((axis) => range([group], "positions", 3, axis)), [
[0.125, 0.875],
[0.125, 0.5],
[0.125, 0.875],
]);
const top = new InstanceGroup(
group.quads.filter((quad) => quad.positions.every((at, i) => i % 3 !== 1 || at === 0.5)),
);
assertEquals([range([top], "uvs", 2, 0), range([top], "uvs", 2, 1)], [[34, 46], [2, 14]]);
// where it's drawn back to front from
assertEquals([...group.center], [1.5, 64 + 5 / 16, 1.5]);
// two blocks long it's a piece in each, and the texture repeats
box!.set_box([0, 0, 0], [32, 16, 16]);
assertEquals([group.quads.length, group.model_changed], [10, true]);
assertEquals(range([group], "positions", 3, 0), [0, 2]);
assertEquals([range([group], "uvs", 2, 0), range([group], "uvs", 2, 1)], [[32, 48], [0, 16]]);
// it goes with its instance, or its visual
box!.delete();
assertEquals(boxes(), []);
mesh([]);
mesh([index_of(1, 64, 1), value("testmod:shaft")]);
assertEquals(boxes().length, 1);
visuals.unload(0, 0);
assertEquals(boxes(), []);
block_visuals.clear();
});
const adapter = await navigator.gpu?.requestAdapter().catch(() => null) ?? null;
Deno.test({
@@ -316,16 +437,14 @@ Deno.test({
AssetManager.instance.assets["bworld:textures_info"] = {
"testmod:shaft": { x: 0, y: 0, width: 16, height: 16 },
};
const model = buffer(
GPUBufferUsage.VERTEX,
pack_model([quad], [[1, 1, 1]], { width: 16, height: 16 } as Texture),
);
const quads = instance_quads([quad], () => [1, 1, 1]);
const model = buffer(GPUBufferUsage.VERTEX, pack_model(quads, { width: 16, height: 16 } as Texture));
const indices = buffer(GPUBufferUsage.INDEX, Uint32Array.of(0, 1, 2, 0, 2, 3));
const camera = mat4.orthoZO(mat4.create(), 0, 1, 0, 1, -10, 10);
// the red of the 2x2 pixels the block covers: top left, top right, bottom left, bottom right
const render = async (time: number, rpm: number, offset: number) => {
const group = new InstanceGroup([quad], [[1, 1, 1]]);
const group = new InstanceGroup(quads);
group.add({ group, index: -1, placement: mat4.create(), axis: [0, 0, 1], rpm, offset, light: 0xff });
device.queue.writeBuffer(uniforms, 0, Float32Array.of(...camera, time, 0, 0, 0));
const target = device.createTexture({