Pipeline to draw models !

This commit is contained in:
2026-10-14 00:10:58 -03:00
parent 6ad476ac18
commit d7f1b91c0a
9 changed files with 593 additions and 201 deletions
+181 -53
View File
@@ -1,23 +1,20 @@
// 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";
// 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 { 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 { Visual } from "$/common/mod_api/client.ts";
import {
block_visuals,
type DrawnInstance,
facing_shade,
instance_matrix,
Visuals,
} from "$/client/rendering/visuals.ts";
import type { RotatingInstance, Visual } from "$/common/mod_api/client.ts";
import { block_visuals, 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";
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";
@@ -111,11 +108,19 @@ Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models
assert(meshed.min_y <= 63 && meshed.max_y >= 66, `${meshed.min_y} to ${meshed.max_y}`);
});
// what the gpu would draw: each model's quad count and how many of it, for the models drawn at all
const drawn = (visuals: Visuals) =>
[...visuals.groups()].filter((group) => group.instances.length > 0)
.map((group) => `${group.quads.length} quads x${group.instances.length}`);
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);
const visuals = new Visuals({
get_block_data: (x, y, z) => x === 1 && y === 64 && z === 1 ? data : undefined,
get_light: () => 0,
});
block_visuals.clear();
block_visuals.set(nid("testmod:shaft"), {
mod: "testmod",
@@ -135,6 +140,8 @@ Deno.test("a visual is made with its block, told when its client data changes, a
visuals.meshed(0, 0, shaft(1));
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1"]);
// the half model has one face, the block's own model is a cube
assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]);
// meshed again for something else, it stays
visuals.meshed(0, 0, shaft(1));
assertEquals(log.splice(0), []);
@@ -144,29 +151,25 @@ Deno.test("a visual is made with its block, told when its client data changes, a
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);
// only visuals in chunks in view get on_frame
visuals.frame([{ x: 1, z: 0 }], 10.5);
assertEquals(log.splice(0), []);
visuals.frame([{ x: 0, z: 0 }], 10.5);
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
assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]);
// and it goes with the block, or with the chunk, and so do its instances
visuals.meshed(0, 0, new Uint32Array());
assertEquals(log.splice(0), ["delete 1 64 1"]);
assert(!visuals.has(0, 0));
assertEquals(drawn(visuals), []);
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, []);
assertEquals(drawn(visuals), []);
block_visuals.clear();
});
@@ -189,7 +192,7 @@ Deno.test("a visual that throws is logged and left out, and not made again until
};
},
});
const visuals = new Visuals(() => undefined);
const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => 0 });
const errors: unknown[] = [];
const console_error = console.error;
console.error = (...args) => errors.push(args);
@@ -197,13 +200,11 @@ Deno.test("a visual that throws is logged and left out, and not made again until
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);
assertEquals(drawn(visuals), []);
// 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, () => {});
for (let frame = 0; frame < 3; frame++) visuals.frame([{ x: 0, z: 0 }], frame);
assertEquals([made, errors.length], [3, 2]);
} finally {
console.error = console_error;
@@ -211,33 +212,160 @@ Deno.test("a visual that throws is logged and left out, and not made again until
}
});
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 },
Deno.test("an instance's placement, spin and light are kept for the gpu, and only what changed is sent again", async () => {
const { nid, value } = await registries();
let light = 0xf0;
const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => light });
const made: RotatingInstance[] = [];
block_visuals.clear();
block_visuals.set(nid("testmod:shaft"), {
mod: "testmod",
replaces_model: true,
create(block, instances) {
const instance = instances.rotating("testmod:half");
instance.set_rotation("x", block.x * 10, 22.5);
made.push(instance);
return {};
},
});
// 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]);
const shafts = Uint32Array.of(
...[1, 2, 3].flatMap((x) => [index_of(x, 64, 1), value("testmod:shaft")]),
);
visuals.meshed(0, 0, shafts);
const group = [...visuals.groups()].find((group) => group.instances.length > 0)!;
const at = (i: number) => [...group.data.subarray(i * INSTANCE_FLOATS, (i + 1) * INSTANCE_FLOATS)];
const sent = () => {
const dirty = [group.dirty_from, group.dirty_to];
group.dirty_from = Infinity;
group.dirty_to = -1;
return dirty;
};
// at its block's corner, spinning around x at its rpm from its offset, lit by its block's light: block light 15
// and sky light 0, as lightmap coordinates
assertEquals(at(1), [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 64, 1, 1, 1, 0, 0, 20, 22.5, 15.5 / 16, 0.5 / 16, 0]);
assertEquals(sent(), [0, 2]);
// 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]);
made[2].set_rotation("y", 5);
assertEquals(sent(), [2, 2]);
// the last one moves into a deleted one's place, so the ones drawn are always the first ones
made[0].delete();
assertEquals(group.instances.length, 2);
assertEquals(at(0)[12], 3);
assertEquals(sent(), [0, 0]);
// a new light comes with the chunk's mesh
light = 0x0f;
visuals.meshed(0, 0, shafts);
assertEquals([at(0)[21], at(0)[22]], [0.5 / 16, 15.5 / 16]);
assertEquals(sent(), [0, 1]);
block_visuals.clear();
});
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);
const adapter = await navigator.gpu?.requestAdapter().catch(() => null) ?? null;
Deno.test({
name: "the gpu turns a rotating instance by the time, rpm and offset, and shades it by the way it faces",
ignore: !adapter,
async fn() {
const device = await adapter!.requestDevice();
const module = device.createShaderModule({ code: terrain_shader_src });
const pipeline = device.createRenderPipeline({
layout: "auto",
vertex: { module, entryPoint: "vs_instance", buffers: INSTANCED_BUFFERS },
fragment: { module, entryPoint: "fs_cutout_discard", targets: [{ format: "rgba8unorm" }] },
primitive: { topology: "triangle-list", cullMode: "back", frontFace: "ccw" },
});
const buffer = (usage: number, data: Uint8Array<ArrayBuffer> | Uint32Array | Float32Array) => {
const made = device.createBuffer({ size: data.byteLength, usage: usage | GPUBufferUsage.COPY_DST });
device.queue.writeBuffer(made, 0, data);
return made;
};
const white = (size: number) => {
const texture = device.createTexture({
size: [size, size],
format: "rgba8unorm",
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
});
const pixels = new Uint8Array(size * size * 4).fill(255);
device.queue.writeTexture({ texture }, pixels, { bytesPerRow: size * 4 }, [size, size]);
return texture.createView();
};
const uniforms = device.createBuffer({ size: 80, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
const sampler = device.createSampler();
const bind = (index: number, entries: GPUBindGroupEntry[]) =>
device.createBindGroup({ layout: pipeline.getBindGroupLayout(index), entries });
const bind_groups = [
bind(0, [{ binding: 0, resource: { buffer: uniforms } }]),
bind(1, [{ binding: 0, resource: white(1) }, { binding: 1, resource: sampler }]),
bind(2, [{ binding: 0, resource: white(16) }, { binding: 1, resource: sampler }]),
];
// the left half of a block's south face, seen from the south by a camera that shows just the block
const quad: BakedQuad = {
positions: [0, 0, 1, 0.5, 0, 1, 0.5, 1, 1, 0, 1, 1],
uvs: [0, 16, 16, 16, 16, 0, 0, 0],
texture: "testmod:shaft",
variables: [],
face: 2,
cull: -1,
flush: false,
aligned: true,
shade: true,
};
// the atlas is just its texture
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 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]]);
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({
size: [2, 2],
format: "rgba8unorm",
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
});
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [{
view: target.createView(),
loadOp: "clear",
storeOp: "store",
clearValue: [0, 0, 0, 1],
}],
});
pass.setPipeline(pipeline);
bind_groups.forEach((group, index) => pass.setBindGroup(index, group));
pass.setIndexBuffer(indices, "uint32");
pass.setVertexBuffer(0, model);
pass.setVertexBuffer(1, buffer(GPUBufferUsage.VERTEX, group.data));
pass.drawIndexed(6, 1);
pass.end();
const read = device.createBuffer({ size: 512, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
encoder.copyTextureToBuffer({ texture: target }, { buffer: read, bytesPerRow: 256 }, [2, 2]);
device.queue.submit([encoder.finish()]);
await read.mapAsync(GPUMapMode.READ);
const pixels = new Uint8Array(read.getMappedRange());
return [pixels[0], pixels[4], pixels[256], pixels[260]];
};
// facing south it's shaded 0.8 like a block's south face
assertEquals(await render(0, 50, 0), [204, 0, 204, 0]);
// 50 rpm is 15 degrees a tick, so a quarter turn counterclockwise takes the left half to the bottom
assertEquals(await render(6, 50, 0), [0, 0, 204, 204]);
assertEquals(await render(6, -50, 0), [204, 204, 0, 0]);
// still, but half a turn along
assertEquals(await render(1000, 0, 180), [0, 204, 0, 204]);
device.destroy();
},
});
Deno.test("client scripts register visuals during setup, for blocks that exist", async () => {