From d7f1b91c0a02c07ab48f0fa6643c0bde4a9e2ba5 Mon Sep 17 00:00:00 2001 From: Paula Date: Wed, 14 Oct 2026 00:10:58 -0300 Subject: [PATCH] Pipeline to draw models ! --- CREATE.md | 32 ++- client/level/client_level.ts | 4 +- client/renderer/core.ts | 153 +++++++++++-- client/rendering/game_renderer.ts | 2 + client/rendering/level_renderer.ts | 14 +- client/rendering/visuals.ts | 349 ++++++++++++++++++++--------- docs/modding/blocks/visuals.md | 4 +- tests/client_data_test.ts | 2 +- tests/visuals_test.ts | 234 ++++++++++++++----- 9 files changed, 593 insertions(+), 201 deletions(-) diff --git a/CREATE.md b/CREATE.md index 22e85db..9b30445 100644 --- a/CREATE.md +++ b/CREATE.md @@ -4,8 +4,9 @@ A plan for porting all of Create to bworld as a mod, `mods/create`: its kinetics redstone, contraptions, trains, equipment, decoration and schematics. It aims to do this with as little hand work as possible, and to stay fast on both the server and the client when a world has thousands of moving parts. -Built so far: the importer and Create's imported blocks and items, R1, R2, R5, S0, S7, and stonecutting from S9. Facts -about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source. +Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed` and `rotating`), R4, R5, +R8, S0, S7, and stonecutting from S9. Facts about Create come from reading `ports/create1.21.1` and +`ports/create1.19.3`, and facts about bworld from its source. ## Sources @@ -241,11 +242,11 @@ models of the ones whose visual replaces it, like `ENTITYBLOCK_ANIMATED`. A visu when a client data field changes, made again when the block's states change, and deleted with the block or chunk. It draws `rotating` and `transformed` instances of its block's model or of any model in `models/` by id, turned like a variant. A visual that has to move on the CPU (a crank easing in, a press head) gets `on_frame`, like `DynamicVisual`. -Visuals are kept per chunk and only chunks in view are drawn. Until R3, instances are worked out on the CPU each frame -and drawn in the entity batch, behind the same API, so R3 changes no mod. +Visuals are kept per chunk, and only the ones in chunks in view get `on_frame`. -**R3. Instanced drawing** (P1). A WebGPU pipeline that draws one model many times from an instance buffer, the thing -bworld has none of today (`client/renderer/core.ts` only batches vertices). The instance types, matching Create's: +**R3. Instanced drawing** (P1, `transformed` and `rotating` built). A WebGPU pipeline that draws one model many times +from an instance buffer (`vs_instance` in `client/renderer/core.ts`, cut out like cutout terrain). The instance types, +matching Create's: | Type | Per instance | Shader | | ------------- | ------------------------------------------ | ----------------------------------------------------------------------- | @@ -258,9 +259,18 @@ Instances are grouped by model and type, and each group is one draw call. Light light, updated when that light changes. `rotating` is the important one: thousands of shafts at a steady speed cost nothing per frame. See `ports/sodium` for how to keep buffer updates cheap. +As built, `transformed` and `rotating` share one instance layout (a placement matrix, an axis, rpm, offset and light, 96 +bytes): a rotating instance is placed at its block and spins, a transformed one is placed by its matrix and doesn't. So +instances are grouped by model alone. Each group keeps its instances on the CPU too, changes them there, and writes the +range from the first changed instance to the last once a frame. A deleted instance's place is taken by the last one, so +a group's instances are always its first ones. Light comes with each chunk mesh. Every instance is drawn each frame, +with no culling by chunk, since a draw call per model is cheaper than one per model per chunk until there are far more +instances than P1 has. Faces are shaded on the GPU by the way they face after turning. `scrolling` comes with belts (P4) +and `fluid` with tanks (P5). + **R4. Models without blocks** (P1). Any model in `models/` can be loaded by id for visuals, baked once into a GPU -buffer, and turned for whatever axis it's used on. Loading by id and turning are built with R2, baked for the CPU, and -the GPU buffers come with R3. +buffer, and turned for whatever axis it's used on. Built: each model is baked the first time a visual uses it and +uploaded the first time it's drawn, once per level. **R5. The model format** (P0, built). Everything Create's static models use: `parent`, `x` turns, `uvlock` on variants and parts, element `rotation` at any angle around one axis, and items drawn with models. An item's `model` draws it in @@ -278,8 +288,10 @@ glass can use it. their own, and drawn with the contraption's matrix each frame. Its moving parts (a drill on it, a bearing's shaft) are instances drawn relative to it. A block change on it remeshes only it. -**R8. Render time** (P1). World ticks plus the partial tick, as a shader uniform and for client scripts. Visuals get it -in `on_frame` (`ClientLevel.ticks`, which doesn't jump with `/time`), and the uniform comes with R3. +**R8. Render time** (P1, built). World ticks plus the partial tick, as a shader uniform and for client scripts. It's +`ClientLevel.ticks`, which doesn't jump with `/time`. Visuals get it in `on_frame`, and the shaders as `uniforms.time` +(`set_render_time`), wrapped every 24000 ticks so a 32 bit float stays precise. That's a whole number of turns at any +speed in steps of 0.05 rpm, so those don't jump when it wraps. **R9. Particles** (P3). A simple GPU particle system: sprite, velocity, gravity, lifetime. Used for rotation indicators, crushing, fan processing, steam, fluid splashes. Optional for gameplay, so it can come late. diff --git a/client/level/client_level.ts b/client/level/client_level.ts index 2bdb786..5cc8212 100644 --- a/client/level/client_level.ts +++ b/client/level/client_level.ts @@ -145,7 +145,7 @@ export class ClientLevel { entities = new Map(); // the client data of blocks that have some, see BlockRef.set_client_data, by chunk_key then position_key "x,y,z" block_data = new Map>(); - visuals = new Visuals((x, y, z) => this.get_block_data(x, y, z)); + visuals = new Visuals(this); // server_blocks is the server's block id for each of its numeric ids constructor(server_blocks: string[], view_distance: number) { @@ -259,8 +259,8 @@ export class ClientLevel { this.workers.terminate(); for (const chunk of this.chunks.values()) { this.delete_chunk_mesh(chunk); - this.visuals.unload(chunk.x, chunk.z); } + this.visuals.dispose(); this.chunks.clear(); this.#dirty.clear(); } diff --git a/client/renderer/core.ts b/client/renderer/core.ts index fbf9b69..1f1be2d 100644 --- a/client/renderer/core.ts +++ b/client/renderer/core.ts @@ -24,6 +24,18 @@ const DEPTH_FORMAT: GPUTextureFormat = "depth24plus"; // dynamic uniform offsets have to be 256 aligned const UNIFORM_SLOT_SIZE = 256; +// the matrix, then the render time and padding to 16 bytes +const UNIFORM_FLOATS = 20; +// the render time wraps around after this many ticks, so a 32 bit float keeps it precise however long the game runs. +// a whole number of turns for every speed in steps of 0.05 rpm, so those don't jump when it wraps +const RENDER_TIME_PERIOD = 24000; + +// a vertex of an instanced model, 24 bytes: position as float32x3, atlas uv as unorm16x2, tint as unorm8x3 with alpha 1 +// when the face is shaded by the way it faces, and the face's normal as snorm8x3 and a padding byte +export const MODEL_VERTEX_BYTES = 24; +// an instance, 24 floats: the matrix placing its model in the world (4 columns), the axis it spins around and its rpm, +// then its offset in degrees, its block light and sky light as lightmap coordinates and a padding float +export const INSTANCE_FLOATS = 24; let context: GPUCanvasContext; let canvas_format: GPUTextureFormat; @@ -31,6 +43,7 @@ let canvas_format: GPUTextureFormat; let pipeline_2d: GPURenderPipeline; let pipeline_3d: GPURenderPipeline; let terrain_pipelines: Record; +let instance_pipeline: GPURenderPipeline; // 0 1 2 0 2 3 for every quad, shared by all solid and cutout chunk meshes let quad_index_buffer: GPUBuffer | undefined; let quad_index_capacity = 0; @@ -53,6 +66,9 @@ let stream_offset = 0; let uniform_buffer: GPUBuffer; let uniform_bind_group: GPUBindGroup; let uniform_slot = -1; +const uniform_data = new Float32Array(UNIFORM_FLOATS); +// in ticks, see set_render_time +let render_time = 0; const texture_bind_groups = new WeakMap(); @@ -139,9 +155,11 @@ fn fs_main(in: VertexOut) -> @location(0) vec4 { } `; -const terrain_shader_src = /* wgsl */ ` +export const terrain_shader_src = /* wgsl */ ` struct Uniforms { mvp: mat4x4, + // ticks, see set_render_time + time: f32, } @group(0) @binding(0) var uniforms: Uniforms; @@ -174,6 +192,43 @@ fn vs_terrain( return out; } +// v turned angle radians around axis, counterclockwise seen from the axis's end +fn spun(v: vec3, axis: vec3, angle: f32) -> vec3 { + return v * cos(angle) + cross(axis, v) * sin(angle) + axis * dot(axis, v) * (1.0 - cos(angle)); +} + +// a model drawn many times, once per instance, see client/rendering/visuals.ts. it's turned around its block's middle +// by spin (rpm times a minute, plus the offset) before placement puts it in the world. its faces are shaded by the +// way they face after that, like the chunk mesher's, and lit by the light the instance has +@vertex +fn vs_instance( + @location(0) position: vec3, + @location(1) tex_coord: vec2, + @location(2) color: vec4, + @location(3) normal: vec4, + @location(4) placement0: vec4, + @location(5) placement1: vec4, + @location(6) placement2: vec4, + @location(7) placement3: vec4, + // the axis, then rpm + @location(8) spin: vec4, + // the offset in degrees, then block light and sky light as lightmap coordinates + @location(9) offset_light: vec4, +) -> VertexOut { + let placement = mat4x4(placement0, placement1, placement2, placement3); + // in turns first, which fract keeps small. a minute is 1200 ticks + let angle = fract(uniforms.time * spin.w / 1200.0 + offset_light.x / 360.0) * 6.2831853; + let local = spun(position - vec3(0.5), spin.xyz, angle) + vec3(0.5); + let n = normalize((placement * vec4(spun(normal.xyz, spin.xyz, angle), 0.0)).xyz); + let shade = n.x * n.x * 0.6 + n.z * n.z * 0.8 + n.y * n.y * select(0.5, 1.0, n.y > 0.0); + var out: VertexOut; + out.position = uniforms.mvp * placement * vec4(local, 1.0); + out.tex_coord = tex_coord; + out.color = vec4(color.rgb * select(1.0, shade, color.a > 0.5), 1.0); + out.light = offset_light.yz; + return out; +} + fn lit(in: VertexOut) -> vec4 { let texel = textureSample(texture0, sampler0, in.tex_coord); return vec4(texel.rgb * in.color.rgb * light_at(in), texel.a * in.color.a); @@ -423,6 +478,12 @@ export function light_color(packed: number): [number, number, number] { return [lightmap_colors[i], lightmap_colors[i + 1], lightmap_colors[i + 2]]; } +// the time rotating instances turn by, in ticks with the part of the next one (see ClientLevel.ticks). the frame's 3d +// drawing uses the time set before begin_mode_3d +export function set_render_time(ticks: number) { + render_time = ticks % RENDER_TIME_PERIOD; +} + export function end_mode_3d() { if (!mode3d) { return; @@ -514,6 +575,34 @@ export function draw_terrain( frame_stats.quads[layer] += quad_count; } +// draws a model's quads (4 vertices each, see MODEL_VERTEX_BYTES) once for each of the first instance_count instances +// in instances (see INSTANCE_FLOATS), in one draw call +export function draw_instances(model: GPUBuffer, quad_count: number, instances: GPUBuffer, instance_count: number) { + if (!current_texture || quad_count === 0 || instance_count === 0) { + return; + } + ensure_quad_indices(quad_count); + const render_pass = ensure_pass(); + if (current_pipeline !== instance_pipeline) { + render_pass.setPipeline(instance_pipeline); + current_pipeline = instance_pipeline; + terrain_binds = undefined; + } + render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]); + render_pass.setBindGroup(1, get_texture_bind_group(current_texture)); + render_pass.setBindGroup(2, lightmap_bind_group); + render_pass.setIndexBuffer(quad_index_buffer!, "uint32"); + render_pass.setVertexBuffer(0, model); + render_pass.setVertexBuffer(1, instances); + render_pass.drawIndexed(quad_count * 6, instance_count); + frame_stats.draw_calls += 1; +} + +// copies data into part of a buffer made with create_vertex_buffer, from data's first to last element +export function write_buffer(buffer: GPUBuffer, byte_offset: number, data: Float32Array, first: number, count: number) { + device.queue.writeBuffer(buffer, byte_offset, data, first, count); +} + // the camera's view and projection, for frustum culling. only meaningful in 3d mode export function view_projection(): Readonly { return mvp as Float32Array; @@ -788,8 +877,9 @@ function write_mvp() { uniform_slot = 0; } - const matrix = mode3d ? mvp : ortho; - device.queue.writeBuffer(uniform_buffer, uniform_slot * UNIFORM_SLOT_SIZE, matrix as Float32Array); + uniform_data.set(mode3d ? mvp : ortho); + uniform_data[16] = render_time; + device.queue.writeBuffer(uniform_buffer, uniform_slot * UNIFORM_SLOT_SIZE, uniform_data); } function update_camera() { @@ -824,7 +914,7 @@ function create_pipelines() { entries: [{ binding: 0, visibility: GPUShaderStage.VERTEX, - buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: 64 }, + buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: UNIFORM_FLOATS * 4 }, }], }); texture_layout ??= device.createBindGroupLayout({ @@ -907,15 +997,19 @@ function create_pipelines() { }; // like sodium and vanilla: solid and cutout don't blend, translucent blends and still writes depth // since it's drawn sorted back to front - const terrain_pipeline = (entryPoint: string, blend?: GPUBlendState, alphaToCoverageEnabled = false) => - device.createRenderPipeline({ - layout: terrain_layout, - vertex: terrain_vertex, - fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] }, - multisample: { ...multisample, alphaToCoverageEnabled }, - primitive: primitive_3d, - depthStencil: depth_3d, - }); + const terrain_pipeline = ( + entryPoint: string, + blend?: GPUBlendState, + alphaToCoverageEnabled = false, + vertex = terrain_vertex, + ) => device.createRenderPipeline({ + layout: terrain_layout, + vertex, + fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] }, + multisample: { ...multisample, alphaToCoverageEnabled }, + primitive: primitive_3d, + depthStencil: depth_3d, + }); terrain_pipelines = { solid: terrain_pipeline("fs_solid"), // alpha to coverage needs msaa @@ -927,8 +1021,39 @@ function create_pipelines() { alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" }, }), }; + // instances are cut out like cutout terrain + const instance_vertex: GPUVertexState = { + module: terrain_module, + entryPoint: "vs_instance", + buffers: INSTANCED_BUFFERS, + }; + instance_pipeline = sample_count > 1 + ? terrain_pipeline("fs_cutout", undefined, true, instance_vertex) + : terrain_pipeline("fs_cutout_discard", undefined, false, instance_vertex); } +// how vs_instance reads a model's vertices and its instances +export const INSTANCED_BUFFERS: GPUVertexBufferLayout[] = [ + { + arrayStride: MODEL_VERTEX_BYTES, + attributes: [ + { shaderLocation: 0, offset: 0, format: "float32x3" }, + { shaderLocation: 1, offset: 12, format: "unorm16x2" }, + { shaderLocation: 2, offset: 16, format: "unorm8x4" }, + { shaderLocation: 3, offset: 20, format: "snorm8x4" }, + ], + }, + { + arrayStride: INSTANCE_FLOATS * 4, + stepMode: "instance", + attributes: [4, 5, 6, 7, 8, 9].map((location, i) => ({ + shaderLocation: location, + offset: i * 16, + format: "float32x4" as const, + })), + }, +]; + function create_stream_buffer(size: number) { return device.createBuffer({ size, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }); } @@ -940,7 +1065,7 @@ function create_uniform_buffer(slots: number) { }); uniform_bind_group = device.createBindGroup({ layout: uniform_layout, - entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: 64 } }], + entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: UNIFORM_FLOATS * 4 } }], }); } diff --git a/client/rendering/game_renderer.ts b/client/rendering/game_renderer.ts index 31c09de..c1fcf08 100644 --- a/client/rendering/game_renderer.ts +++ b/client/rendering/game_renderer.ts @@ -8,6 +8,7 @@ import { clear_background, draw_rect, end_mode_3d, + set_render_time, update_lightmap, } from "$/client/renderer/mod.ts"; import { daylight } from "$/common/time.ts"; @@ -68,6 +69,7 @@ export class GameRenderer { camera.setup(client.player, partial_tick); this.#setup_sky(client, partial_tick); + set_render_time(client.level.ticks + partial_tick); begin_mode_3d(camera); const level = this.level_renderer; level.render_opaque(client.level, camera); diff --git a/client/rendering/level_renderer.ts b/client/rendering/level_renderer.ts index 5a62391..0bef20c 100644 --- a/client/rendering/level_renderer.ts +++ b/client/rendering/level_renderer.ts @@ -22,7 +22,6 @@ import { draw_terrain, flush_batch, get_current_texture, - light_color, push_vertex, set_current_texture, Texture, @@ -38,7 +37,7 @@ import type { BlockHitResult } from "$/client/level/client_level.ts"; import { FACE_GROUPS, UNALIGNED_GROUP } from "$/client/workers/chunk_messages.ts"; import { FACE_AXIS, FACE_NORMALS } from "$/client/workers/translucent_sort.ts"; import { Frustum } from "./frustum.ts"; -import { draw_instance } from "./visuals.ts"; +import { draw_visuals } from "./visuals.ts"; // draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities export class LevelRenderer { @@ -149,16 +148,13 @@ export class LevelRenderer { flush_batch(); } - // blocks drawn with code, in the chunks in view, see client/rendering/visuals.ts + // blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first render_visuals(level: ClientLevel, partial_tick: number) { if (!this.draw.visuals) return; - const atlas = AssetManager.instance.get("bworld:textures"); - set_current_texture(level.image.tex); - const time = level.ticks + partial_tick; - level.visuals.render(this.#visible, time, (instance, x, y, z) => { - draw_instance(atlas, instance, x, y, z, time, light_color(level.get_light(x, y, z))); - }); + level.visuals.frame(this.#visible, level.ticks + partial_tick); flush_batch(); + set_current_texture(level.image.tex); + draw_visuals(level.visuals, level.image); } // the cracks on the block being broken, drawn over its model's faces like minecraft's crumbling overlay, so a slab diff --git a/client/rendering/visuals.ts b/client/rendering/visuals.ts index 69c283f..9d5e0cf 100644 --- a/client/rendering/visuals.ts +++ b/client/rendering/visuals.ts @@ -2,8 +2,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // blocks drawn with code, like a shaft that turns, see ctx.render.register_visual. like flywheel's visuals: one per -// block, made when its chunk is meshed, kept by chunk so chunks out of view are skipped, and drawn as instances of -// models. instances are worked out on the cpu each frame and drawn in the same batch as entities +// block, made when its chunk is meshed and kept by chunk. what they draw are instances of models, and every instance of +// a model is drawn in one draw call from a buffer of where each is, how it spins and its light (see vs_instance in +// client/renderer/core.ts). the gpu turns rotating ones by the time, so a shaft that keeps turning costs nothing per +// frame import { mat4, vec3 } from "gl-matrix"; import type { Instances, @@ -25,10 +27,17 @@ import { } from "$/common/block_models.ts"; import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts"; import { chunk_key } from "$/common/utils.ts"; -import { push_vertex, type Texture } from "$/client/renderer/mod.ts"; +import { + create_vertex_buffer, + destroy_buffer, + draw_instances, + INSTANCE_FLOATS, + MODEL_VERTEX_BYTES, + type Texture, + write_buffer, +} from "$/client/renderer/mod.ts"; import { get_sprite_region } from "$/client/sprites.ts"; import { sprite_u, sprite_v } from "./item_renderer.ts"; -import type { Vec3 } from "./model_math.ts"; export interface VisualRegistration { mod: string; @@ -41,20 +50,85 @@ export interface VisualRegistration { export const block_visuals = new Map(); const AXES: Record = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }; -// a rotating instance turns this many degrees per tick at 1 rpm -const DEGREES_PER_TICK = 360 / 60 / 20; -// a model's quads with the color each is tinted, white but for a block's own tinted quads, like leaves -interface ModelQuads { - quads: BakedQuad[]; - tints: number[][]; +// what visuals read from their level +export interface VisualsLevel { + get_block_data(x: number, y: number, z: number): Readonly> | undefined; + // block light << 4 | sky light + get_light(x: number, y: number, z: number): number; } -// an instance as the engine keeps it, one of matrix or rotation -export interface DrawnInstance extends ModelQuads { - // from the model's space to the block's - matrix?: mat4; - rotation?: { axis: vec3; rpm: number; offset: number }; +// an instance as the engine keeps it, see INSTANCE_FLOATS +export interface DrawnInstance { + group: InstanceGroup; + // where it is in its group, -1 once it's deleted + index: number; + // takes its model to the world, after it spins around its block's middle + placement: mat4; + axis: vec3; + rpm: number; + // degrees + offset: number; + // packed like ClientLevel.get_light + light: number; +} + +// the instances of one model, drawn in one draw call. their data is changed on the cpu and written to the gpu once a +// frame, from the first instance that changed to the last +export class InstanceGroup { + readonly quads: BakedQuad[]; + // each quad's tint, white but for a block's own tinted quads, like leaves + readonly tints: number[][]; + readonly instances: DrawnInstance[] = []; + data = new Float32Array(INSTANCE_FLOATS * 16); + // the instances changed since the gpu last got them, by index + dirty_from = Infinity; + dirty_to = -1; + // made the first time it's drawn + gpu?: { model: GPUBuffer; instances: GPUBuffer; capacity: number }; + + constructor(quads: BakedQuad[], tints: number[][]) { + this.quads = quads; + this.tints = tints; + } + + add(instance: DrawnInstance) { + instance.index = this.instances.length; + this.instances.push(instance); + if (this.data.length < this.instances.length * INSTANCE_FLOATS) { + const data = new Float32Array(this.data.length * 2); + data.set(this.data); + this.data = data; + } + this.write(instance); + } + + // the last instance moves into its place, so the ones drawn are always the first ones + remove(instance: DrawnInstance) { + if (instance.index < 0) return; + const last = this.instances.pop()!; + if (last !== instance) { + last.index = instance.index; + this.instances[last.index] = last; + this.write(last); + } + instance.index = -1; + } + + // after any of its fields changed + write(instance: DrawnInstance) { + const index = instance.index; + if (index < 0) return; + const at = index * INSTANCE_FLOATS; + this.data.set(instance.placement, at); + this.data.set(instance.axis, at + 16); + this.data[at + 19] = instance.rpm; + this.data[at + 20] = instance.offset; + this.data[at + 21] = ((instance.light >> 4) + 0.5) / 16; + this.data[at + 22] = ((instance.light & 15) + 0.5) / 16; + this.dirty_from = Math.min(this.dirty_from, index); + this.dirty_to = Math.max(this.dirty_to, index); + } } interface Entry { @@ -63,6 +137,7 @@ interface Entry { z: number; value: number; mod: string; + light: number; // undefined when making it threw, until the block changes visual?: Visual; instances: Set; @@ -74,22 +149,29 @@ interface Entry { export class Visuals { // by chunk_key, then the block's index in its chunk #chunks = new Map>(); - #client_data: (x: number, y: number, z: number) => Readonly> | undefined; + #level: VisualsLevel; // baked once per level, since a level's mods don't change #models?: Record; - #model_quads = new Map(); - #block_quads = new Map(); + // models from models/ by id and turns, and blocks' own by value + #model_groups = new Map(); + #block_groups = new Map(); - constructor(client_data: (x: number, y: number, z: number) => Readonly> | undefined) { - this.#client_data = client_data; + constructor(level: VisualsLevel) { + this.#level = level; } has(chunk_x: number, chunk_z: number) { return this.#chunks.has(chunk_key(chunk_x, chunk_z)); } + *groups(): Iterable { + yield* this.#model_groups.values(); + yield* this.#block_groups.values(); + } + // the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals - // for blocks that are gone or changed go, and new ones are made + // for blocks that are gone or changed go, and new ones are made. the chunk's light came with its mesh, so the ones + // that stay take it meshed(chunk_x: number, chunk_z: number, found: Uint32Array) { const key = chunk_key(chunk_x, chunk_z); const old = this.#chunks.get(key) ?? new Map(); @@ -100,6 +182,7 @@ export class Visuals { const entry = old.get(index); old.delete(index); if (entry?.value === value) { + this.#relight(entry); kept.set(index, entry); continue; } @@ -126,21 +209,31 @@ export class Visuals { this.#chunks.delete(key); } - // the visuals in these chunks get their on_frame, then their instances are drawn - render( - chunks: Iterable<{ x: number; z: number }>, - time: number, - draw: (instance: DrawnInstance, x: number, y: number, z: number) => void, - ) { + // every visual goes, and the gpu buffers with them + dispose() { + for (const key of this.#chunks.keys()) { + for (const entry of this.#chunks.get(key)!.values()) this.#delete(entry); + } + this.#chunks.clear(); + for (const group of this.groups()) { + if (group.gpu) { + destroy_buffer(group.gpu.model); + destroy_buffer(group.gpu.instances); + } + } + this.#model_groups.clear(); + this.#block_groups.clear(); + } + + // the visuals in these chunks get their on_frame. every instance is drawn either way, it's the gpu that skips what's + // out of view + frame(chunks: Iterable<{ x: number; z: number }>, time: number) { for (const chunk of chunks) { - const entries = this.#chunks.get(chunk_key(chunk.x, chunk.z)); - if (!entries) continue; - for (const entry of entries.values()) { + for (const entry of this.#chunks.get(chunk_key(chunk.x, chunk.z))?.values() ?? []) { const visual = entry.visual; if (visual?.on_frame && !entry.frame_failed) { entry.frame_failed = !run_visual(entry, "on_frame", () => visual.on_frame!(time)); } - for (const instance of entry.instances) draw(instance, entry.x, entry.y, entry.z); } } } @@ -156,85 +249,119 @@ export class Visuals { const registration = block_visuals.get(value & ID_MASK); const block = EverythingRegistry.get_by_id("blocks", value & ID_MASK); if (!registration || !block) return undefined; - const entry: Entry = { x, y, z, value, mod: registration.mod, instances: new Set() }; - const client_data = this.#client_data; + const light = this.#level.get_light(x, y, z); + const entry: Entry = { x, y, z, value, mod: registration.mod, light, instances: new Set() }; + const level = this.#level; const view: VisualBlock = { id: block.id, x, y, z, states: Object.freeze(states_of(block, value)), - get_client_data: (field) => structuredClone(client_data(x, y, z)?.[field]) as never, + get_client_data: (field) => structuredClone(level.get_block_data(x, y, z)?.[field]) as never, }; const made = run_visual(entry, "create", () => { entry.visual = registration.create(view, this.#instances(entry, block)); }); // nothing it made before it threw is drawn - if (!made) entry.instances.clear(); + if (!made) this.#remove_instances(entry); return entry; } #delete(entry: Entry) { const visual = entry.visual; if (visual?.on_delete) run_visual(entry, "on_delete", () => visual.on_delete!()); + this.#remove_instances(entry); + } + + #remove_instances(entry: Entry) { + for (const instance of entry.instances) instance.group.remove(instance); entry.instances.clear(); } + #relight(entry: Entry) { + const light = this.#level.get_light(entry.x, entry.y, entry.z); + if (light === entry.light) return; + entry.light = light; + for (const instance of entry.instances) { + instance.light = light; + instance.group.write(instance); + } + } + #instances(entry: Entry, block: BlockRegistry): Instances { - const add = (model: ModelRef | undefined, instance: Omit) => { - const quads = model === undefined ? this.#quads_of_block(block, entry.value) : this.#quads_of(model); - const added = { ...instance, ...quads }; - entry.instances.add(added); - return added; + const corner = mat4.fromTranslation(mat4.create(), [entry.x, entry.y, entry.z]); + const add = (model: ModelRef | undefined) => { + const group = model === undefined ? this.#block_group(block, entry.value) : this.#model_group(model); + const instance: DrawnInstance = { + group, + index: -1, + placement: mat4.clone(corner), + axis: AXES.y, + rpm: 0, + offset: 0, + light: entry.light, + }; + group.add(instance); + entry.instances.add(instance); + return instance; + }; + const remove = (instance: DrawnInstance) => () => { + instance.group.remove(instance); + entry.instances.delete(instance); }; return { transformed(model): TransformedInstance { - const instance = add(model, { matrix: mat4.create() }); + const instance = add(model); return { set_transform(matrix) { if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix"); - mat4.copy(instance.matrix!, matrix as mat4); + mat4.multiply(instance.placement, corner, matrix as mat4); + instance.group.write(instance); }, - delete: () => void entry.instances.delete(instance), + delete: remove(instance), }; }, rotating(model): RotatingInstance { - const instance = add(model, { rotation: { axis: AXES.y, rpm: 0, offset: 0 } }); + const instance = add(model); return { set_rotation(axis, rpm, offset = 0) { if (!AXES[axis]) throw new Error(`an axis is "x", "y" or "z", not ${axis}`); - instance.rotation = { axis: AXES[axis], rpm, offset }; + instance.axis = AXES[axis]; + instance.rpm = rpm; + instance.offset = offset; + instance.group.write(instance); }, - delete: () => void entry.instances.delete(instance), + delete: remove(instance), }; }, }; } - #quads_of(ref: ModelRef): ModelQuads { + #model_group(ref: ModelRef): InstanceGroup { const { model, x = 0, y = 0 } = typeof ref === "string" ? { model: ref } : ref; const key = `${model} ${x} ${y}`; - let quads = this.#model_quads.get(key); - if (!quads) { + let group = this.#model_groups.get(key); + if (!group) { this.#models ??= Object.fromEntries(EverythingRegistry.entries("models")); const json = find_model(model, this.#models); if (!json) throw new Error(`there's no model ${model}`); - const baked = bake_model(json, undefined, y, x); - quads = { quads: baked, tints: baked.map(() => [1, 1, 1]) }; - this.#model_quads.set(key, quads); + const quads = bake_model(json, undefined, y, x); + group = new InstanceGroup(quads, quads.map(() => [1, 1, 1])); + this.#model_groups.set(key, group); } - return quads; + return group; } - #quads_of_block(block: BlockRegistry, value: number): ModelQuads { - let quads = this.#block_quads.get(value); - if (!quads) { + #block_group(block: BlockRegistry, value: number): InstanceGroup { + let group = this.#block_groups.get(value); + if (!group) { this.#models ??= Object.fromEntries(EverythingRegistry.entries("models")); - const baked = bake_block(block, value, this.#models); - quads = { quads: baked, tints: baked.map((quad) => item_tint(block, quad.variables)) }; - this.#block_quads.set(value, quads); + const quads = bake_block(block, value, this.#models); + group = new InstanceGroup(quads, quads.map((quad) => item_tint(block, quad.variables))); + this.#block_groups.set(value, group); } - return quads; + return group; } } @@ -249,59 +376,59 @@ function run_visual(entry: Entry, what: string, fn: () => void) { } } -// where an instance's model goes at a time, as a matrix from its space to the world's -export function instance_matrix(out: mat4, instance: DrawnInstance, x: number, y: number, z: number, time: number) { - mat4.fromTranslation(out, [x, y, z]); - if (instance.matrix) return mat4.multiply(out, out, instance.matrix); - const { axis, rpm, offset } = instance.rotation!; - const degrees = (time * rpm * DEGREES_PER_TICK + offset) % 360; - mat4.translate(out, out, [0.5, 0.5, 0.5]); - mat4.rotate(out, out, degrees * Math.PI / 180, axis); - return mat4.translate(out, out, [-0.5, -0.5, -0.5]); -} - -// reused every quad of every frame -const matrix = mat4.create(); -const corners = [vec3.create(), vec3.create(), vec3.create(), vec3.create()]; -const edge_a = vec3.create(); -const edge_b = vec3.create(); -const normal = vec3.create(); - -// an instance's quads into the batch, lit by tint. each quad is shaded by the way it faces after turning, like a -// block's faces are by theirs. the atlas has to be the current texture -export function draw_instance( - atlas: Texture, - instance: DrawnInstance, - x: number, - y: number, - z: number, - time: number, - [tr, tg, tb]: Vec3, -) { - instance_matrix(matrix, instance, x, y, z, time); - for (const [q, quad] of instance.quads.entries()) { - const p = quad.positions; - for (let k = 0; k < 4; k++) { - vec3.set(corners[k], p[k * 3], p[k * 3 + 1], p[k * 3 + 2]); - vec3.transformMat4(corners[k], corners[k], matrix); - } - const shade = quad.shade ? facing_shade(corners) : 1; - const [r, g, b] = instance.tints[q]; - const region = get_sprite_region(quad.texture); - for (const k of [0, 1, 2, 0, 2, 3]) { - const [px, py, pz] = corners[k]; - const u = sprite_u(atlas, region, quad.uvs[k * 2]); - const v = sprite_v(atlas, region, quad.uvs[k * 2 + 1]); - push_vertex(px, py, pz, u, v, shade * r * tr, shade * g * tg, shade * b * tb, 1); +// every instance, a draw call per model. a group's model goes to the gpu the first time it's drawn, and its instances +// whenever they changed. the atlas has to be the current texture +export function draw_visuals(visuals: Visuals, atlas: Texture) { + for (const group of visuals.groups()) { + const count = group.instances.length; + if (count === 0) continue; + const capacity = group.data.length / INSTANCE_FLOATS; + if (!group.gpu || group.gpu.capacity !== capacity) { + // the whole buffer again, when it's new or the cpu copy grew + if (group.gpu) destroy_buffer(group.gpu.instances); + group.gpu = { + model: group.gpu?.model ?? create_vertex_buffer(pack_model(group.quads, group.tints, atlas)), + instances: create_vertex_buffer(group.data), + capacity, + }; + } else if (group.dirty_to >= 0) { + const from = group.dirty_from * INSTANCE_FLOATS; + write_buffer( + group.gpu.instances, + from * 4, + group.data, + from, + (group.dirty_to + 1) * INSTANCE_FLOATS - from, + ); } + group.dirty_from = Infinity; + group.dirty_to = -1; + draw_instances(group.gpu.model, group.quads.length, group.gpu.instances, count); } } -// how bright a quad facing this way is, blending the shades of the sides it faces between: 1 up, 0.5 down, 0.8 -// north and south, 0.6 east and west, like the chunk mesher's -export function facing_shade([a, b, , d]: vec3[]) { - vec3.cross(normal, vec3.sub(edge_a, b, a), vec3.sub(edge_b, d, a)); - vec3.normalize(normal, normal); - const [nx, ny, nz] = normal; - return nx * nx * 0.6 + nz * nz * 0.8 + ny * ny * (ny > 0 ? 1 : 0.5); +// a model's quads as vertices for vs_instance, 4 a quad, see MODEL_VERTEX_BYTES +export function pack_model(quads: BakedQuad[], tints: number[][], atlas: Texture): Uint8Array { + const bytes = new Uint8Array(quads.length * 4 * MODEL_VERTEX_BYTES); + const view = new DataView(bytes.buffer); + const normal = vec3.create(); + quads.forEach((quad, q) => { + const p = quad.positions; + const corner = (k: number) => vec3.fromValues(p[k * 3], p[k * 3 + 1], p[k * 3 + 2]); + // counterclockwise seen from the front, so it points out of the front + const [a, b, d] = [corner(0), corner(1), corner(3)]; + vec3.normalize(normal, vec3.cross(normal, vec3.sub(b, b, a), vec3.sub(d, d, a))); + const region = get_sprite_region(quad.texture); + const tint = tints[q]; + for (let k = 0; k < 4; k++) { + const at = (q * 4 + k) * MODEL_VERTEX_BYTES; + for (let axis = 0; axis < 3; axis++) view.setFloat32(at + axis * 4, p[k * 3 + axis], true); + view.setUint16(at + 12, Math.round(sprite_u(atlas, region, quad.uvs[k * 2]) * 65535), true); + view.setUint16(at + 14, Math.round(sprite_v(atlas, region, quad.uvs[k * 2 + 1]) * 65535), true); + for (let c = 0; c < 3; c++) bytes[at + 16 + c] = Math.round(tint[c] * 255); + bytes[at + 19] = quad.shade ? 255 : 0; + for (let axis = 0; axis < 3; axis++) view.setInt8(at + 20 + axis, Math.round(normal[axis] * 127)); + } + }); + return bytes; } diff --git a/docs/modding/blocks/visuals.md b/docs/modding/blocks/visuals.md index c6ae500..a7fc5cd 100644 --- a/docs/modding/blocks/visuals.md +++ b/docs/modding/blocks/visuals.md @@ -102,4 +102,6 @@ Only visuals in chunks in view get `on_frame`, so keep anything that has to happ ## Cost -Instances are worked out on the CPU each frame for now, a little for each one in view. A few hundred are fine. +Every instance of a model is drawn in one draw call, and the GPU turns rotating instances by the time, so a block that +keeps turning costs nothing per frame. Setting an instance's rotation or transform sends just that instance to the GPU +again. What costs CPU time is `on_frame`, so use a rotating instance wherever the movement is steady. diff --git a/tests/client_data_test.ts b/tests/client_data_test.ts index d0865bb..cce5ba0 100644 --- a/tests/client_data_test.ts +++ b/tests/client_data_test.ts @@ -91,7 +91,7 @@ Deno.test("the client keeps the fields it's sent for each block until they're re const level = Object.assign(Object.create(ClientLevel.prototype), { chunks: new Map([[chunk_key(0, 0), {}]]), block_data: new Map(), - visuals: new Visuals(() => undefined), + visuals: new Visuals({ get_block_data: () => undefined, get_light: () => 0 }), }) as ClientLevel; level.set_block_data(1, 99, 1, { speed: 16, axis: "x" }); level.set_block_data(1, 99, 1, { speed: 32 }); diff --git a/tests/visuals_test.ts b/tests/visuals_test.ts index b8d5244..e8f2fe0 100644 --- a/tests/visuals_test.ts +++ b/tests/visuals_test.ts @@ -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 = { 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, 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 | 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 () => {