Render regions, disabled by default

This commit is contained in:
2026-11-07 19:35:42 -03:00
parent 206cd38f26
commit c639d1231b
8 changed files with 424 additions and 36 deletions
+1
View File
@@ -243,6 +243,7 @@ export class RenderBenchmark {
system: this.#system,
mods: this.#mods.map((mod) => `${mod.id} ${mod.version}`),
resolution: `${RESOLUTION.width}x${RESOLUTION.height}`,
render_regions: render_debug.render_regions,
level: { chunks: this.#level.chunks.size, build_ms: this.#build_ms },
first_mesh,
remesh,
+3 -1
View File
@@ -74,6 +74,8 @@ export interface BenchmarkReport {
// "id version"
mods: string[];
resolution: string;
// the f3 window's switch, see ClientLevel.use_render_regions
render_regions?: boolean;
level: { chunks: number; build_ms: number };
first_mesh: MeshingResult;
remesh: MeshingResult;
@@ -120,7 +122,7 @@ export function format_report(report: BenchmarkReport): string {
"",
`${system.browser} on ${system.os}, ${system.gpu}`,
`${system.cpu_threads} threads${memory}${refresh}, drawn at ${report.resolution}, ${system.workers} mesh workers` +
(system.timestamps ? "" : ", no gpu timestamps"),
(system.timestamps ? "" : ", no gpu timestamps") + (report.render_regions ? ", render regions" : ""),
`${report.date}, mods: ${report.mods.join(", ") || "none"}`,
"",
"| scene | fps | 1% low | 0.1% low | uncapped fps | cpu ms | gpu ms | draw calls | quads |",
+5 -1
View File
@@ -154,9 +154,13 @@ export class DebugOverlay {
for (const section of chunk.sections) {
const meshes = Object.values(section.meshes);
if (meshes.length > 0) meshed += 1;
for (const mesh of meshes) bytes += mesh.vertex_buffer.size + (mesh.index_buffer?.size ?? 0);
for (const mesh of meshes) bytes += (mesh.vertex_buffer?.size ?? 0) + (mesh.index_buffer?.size ?? 0);
}
}
// solid and cutout quads are in their regions' buffers
for (const region of client.level.regions.values()) {
for (const { buffer } of Object.values(region.layers)) bytes += buffer?.size ?? 0;
}
this.#chunk_stats = { meshed, bytes };
return this.#chunk_stats;
}
+67 -12
View File
@@ -17,7 +17,6 @@ import {
EverythingRegistry,
is_fluid_block,
light_tables,
RENDER_LAYERS,
RenderLayer,
} from "@/common/everything_registry.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
@@ -26,9 +25,10 @@ import { ChunkColumn, column_heights, section_index, type SectionBiomes, type Se
import { AssetManager } from "../assets.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts";
import type { FaceGroup, FromChunkWorker, SectionLight } from "../workers/chunk_messages.ts";
import { create_index_buffer, create_vertex_buffer, destroy_buffer, Texture } from "../renderer/mod.ts";
import { create_index_buffer, create_vertex_buffer, destroy_buffer, render_debug, Texture } from "../renderer/mod.ts";
import { crosses_planes } from "../workers/translucent_sort.ts";
import { ALL_VISIBLE } from "../workers/visibility.ts";
import { region_key, REGION_LAYERS, type RegionLayer, RenderRegion } from "./render_region.ts";
import { Camera } from "../camera.ts";
import type { Entity } from "../entity/entity.ts";
import type { ModelJson } from "@/common/block_models.ts";
@@ -79,15 +79,20 @@ export interface RenderSection {
// client/rendering/occlusion.ts
search: number;
incoming: number;
// where its solid and cutout quads are, see render_region.ts
region: RenderRegion;
}
export interface ChunkMesh {
vertex_buffer: GPUBuffer;
quad_count: number;
// the translucent layer's quads sorted back to front, the others are drawn in order
index_buffer?: GPUBuffer;
// solid and cutout quads by the way they face, see FACE_GROUPS in chunk_messages.ts
groups?: FaceGroup[];
// the section's own buffer, the translucent layer's quads sorted back to front by index_buffer. solid and cutout
// quads are in its region's buffer instead with the render_regions switch on, see render_region.ts, and slot is
// the section's place in the order the region's sections are in it
vertex_buffer?: GPUBuffer;
index_buffer?: GPUBuffer;
slot?: number;
}
interface TranslucentSort {
@@ -142,6 +147,11 @@ export class ClientLevel {
#sorted = new Set<RenderSection>();
// the sections with quads or visuals, the only ones there are to draw
drawn = new Set<RenderSection>();
// by region_key, and the ones whose sections' meshes changed since update_regions
regions = new Map<number, RenderRegion>();
#changed_regions = new Set<RenderRegion>();
// whether solid and cutout quads go in their regions' buffers, see use_render_regions
#render_regions = render_debug.render_regions;
// bumped whenever a chunk comes or goes or a section is meshed, which can change what the camera sees
sections_version = 0;
second_timer = 0;
@@ -250,6 +260,13 @@ export class ClientLevel {
} else {
const chunk: Chunk = { x, z, column, sky, biome_colors, sections: [] };
for (let index = 0; index < column.sections.length; index++) {
const key = region_key(x, index, z);
let region = this.regions.get(key);
if (!region) {
region = new RenderRegion();
this.regions.set(key, region);
}
region.section_count += 1;
chunk.sections.push({
chunk,
index,
@@ -260,6 +277,7 @@ export class ClientLevel {
visibility: ALL_VISIBLE,
search: 0,
incoming: 0,
region,
});
}
this.chunks.set(chunk_key(x, z), chunk);
@@ -292,6 +310,9 @@ export class ClientLevel {
for (const section of chunk.sections) this.#delete_mesh(section);
}
this.visuals.dispose();
for (const region of this.regions.values()) region.dispose();
this.regions.clear();
this.#changed_regions.clear();
this.chunks.clear();
this.#dirty.clear();
this.drawn.clear();
@@ -528,6 +549,12 @@ export class ClientLevel {
for (const section of chunk.sections) {
this.#delete_mesh(section);
this.drawn.delete(section);
section.region.section_count -= 1;
if (section.region.section_count === 0) {
section.region.dispose();
this.regions.delete(region_key(cx, section.index, cz));
this.#changed_regions.delete(section.region);
}
}
this.#dirty.delete(chunk);
this.chunks.delete(key);
@@ -715,19 +742,29 @@ export class ClientLevel {
else this.drawn.delete(section);
this.visuals.meshed(chunk.x, chunk.z, this.shape.min_y + section.index * SECTION_HEIGHT, mesh.visuals);
for (const layer of RENDER_LAYERS) {
for (const layer of REGION_LAYERS) {
const { vertices, quad_count, groups } = mesh[layer];
if (quad_count === 0) {
continue;
}
section.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups };
if (this.#render_regions) {
section.meshes[layer] = { quad_count, groups };
section.region.meshed(layer, section, vertices);
this.#changed_regions.add(section.region);
} else {
section.meshes[layer] = { quad_count, groups, vertex_buffer: create_vertex_buffer(vertices) };
}
}
const translucent = mesh.translucent;
if (translucent.quad_count === 0) {
continue;
}
section.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices);
section.meshes.translucent = {
quad_count: translucent.quad_count,
vertex_buffer: create_vertex_buffer(translucent.vertices),
index_buffer: create_index_buffer(translucent.indices),
};
if (translucent.sort_type === "dynamic") {
this.#sorted.add(section);
section.translucent_sort = {
@@ -758,10 +795,13 @@ export class ClientLevel {
}
#delete_mesh(section: RenderSection) {
for (const mesh of Object.values(section.meshes)) {
destroy_buffer(mesh.vertex_buffer);
if (mesh.index_buffer) {
destroy_buffer(mesh.index_buffer);
for (const [layer, mesh] of Object.entries(section.meshes)) {
if (mesh.vertex_buffer) {
destroy_buffer(mesh.vertex_buffer);
if (mesh.index_buffer) destroy_buffer(mesh.index_buffer);
} else {
section.region.removed(layer as RegionLayer, section);
this.#changed_regions.add(section.region);
}
}
section.meshes = {};
@@ -769,6 +809,21 @@ export class ClientLevel {
this.#sorted.delete(section);
}
// render regions draw solid and cutout terrain in about a fifth of the draw calls, but in firefox that didn't make
// frames any faster and the gpu took longer, so they're the f3 window's render_regions switch, off by default.
// switching meshes everything again, each section's quads going in its own buffer or its region's as they come back
use_render_regions(on: boolean) {
if (on === this.#render_regions) return;
this.#render_regions = on;
this.remesh_all();
}
// puts the buffers of the regions whose sections' solid or cutout quads changed together again, before they're drawn
update_regions() {
for (const region of this.#changed_regions) region.update();
this.#changed_regions.clear();
}
// sections that need meshing, some waiting on their chunk's neighbors to load
get dirty_count() {
let count = 0;
+138
View File
@@ -0,0 +1,138 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// sections are drawn by region, like sodium's RenderRegion: the solid and cutout quads of 8x4x8 sections share one
// buffer per layer, so drawing them binds it once. webgpu has no multi-draw, so the buffer is laid out to need fewer
// draws instead: by face group, every section's quads facing up, then every section's facing down, and so on (see
// FACE_GROUPS). the sections in view whose group faces the camera are then mostly next to each other, and a run of
// them is one draw
import { copy_buffer, create_copyable_vertex_buffer, destroy_buffer, write_buffer } from "@/client/renderer/mod.ts";
import { FACE_GROUPS, TERRAIN_QUAD_BYTES } from "@/client/workers/chunk_messages.ts";
import type { RenderSection } from "./client_level.ts";
export const REGION_WIDTH = 8;
export const REGION_HEIGHT = 4;
export type RegionLayer = "solid" | "cutout";
export const REGION_LAYERS: RegionLayer[] = ["solid", "cutout"];
// a region by the chunk and section index of any section in it. a chunk coordinate is under 2^19, so a region's x and
// z are each under 2^16 either way, and a world is at most 256 sections tall, so its regions under 2^8
export function region_key(chunk_x: number, index: number, chunk_z: number) {
return ((chunk_x >> 3) + 65536) * 2 ** 25 + ((chunk_z >> 3) + 65536) * 2 ** 8 + (index >> 2);
}
// what a region does with its buffers, apart so tests can see what's in them without a gpu
export interface RegionBuffers {
create(size: number): GPUBuffer;
write(buffer: GPUBuffer, offset: number, data: Uint8Array<ArrayBuffer>, first: number, size: number): void;
// as from offset, to offset and size in bytes, three numbers each
copy(from: GPUBuffer, to: GPUBuffer, ranges: number[]): void;
destroy(buffer: GPUBuffer): void;
}
const GPU_BUFFERS: RegionBuffers = {
create: create_copyable_vertex_buffer,
write: write_buffer,
copy: copy_buffer,
destroy: destroy_buffer,
};
interface LayerBuffer {
buffer: GPUBuffer | undefined;
// its sections in the order their quads are in each group's part of the buffer
sections: RenderSection[];
// meshed since it was last put together, with their quads as the chunk worker sent them
meshed: Map<RenderSection, Uint8Array<ArrayBuffer>>;
// whether any of its sections were meshed or lost their quads since
changed: boolean;
}
const empty_layer = (): LayerBuffer => ({ buffer: undefined, sections: [], meshed: new Map(), changed: false });
export class RenderRegion {
layers: Record<RegionLayer, LayerBuffer> = { solid: empty_layer(), cutout: empty_layer() };
// the loaded chunks' sections in it, so it goes when they do
section_count = 0;
constructor(readonly buffers = GPU_BUFFERS) {}
// a section's new quads in a layer, put in the buffer by the next update. section.meshes[layer].groups say where
// each group's quads are in vertices, and after the update where they are in the buffer
meshed(layer: RegionLayer, section: RenderSection, vertices: Uint8Array<ArrayBuffer>) {
this.layers[layer].meshed.set(section, vertices);
this.layers[layer].changed = true;
}
// a section's quads in a layer went, the next update takes them out
removed(layer: RegionLayer, section: RenderSection) {
this.layers[layer].meshed.delete(section);
this.layers[layer].changed = true;
}
// puts each layer's buffer together again: a new one, with the quads of the sections that didn't change copied over
// from the old one on the gpu, and the new quads written to it. a section with no quads in a layer anymore isn't
// in it. only for regions whose sections changed since, see ClientLevel.update_regions
update() {
for (const layer of REGION_LAYERS) {
const old = this.layers[layer];
if (!old.changed) continue;
const sections = old.sections.filter((section) => section.meshes[layer] && !old.meshed.has(section));
sections.push(...old.meshed.keys());
// where each group of each section goes, group after group
const firsts = new Uint32Array(sections.length * FACE_GROUPS);
let quads = 0;
for (let g = 0; g < FACE_GROUPS; g++) {
for (let i = 0; i < sections.length; i++) {
firsts[i * FACE_GROUPS + g] = quads;
quads += sections[i].meshes[layer]!.groups![g].count;
}
}
const buffer = quads > 0 ? this.buffers.create(quads * TERRAIN_QUAD_BYTES) : undefined;
// copies from the old buffer, one per run of quads that's together in both
const copies: number[] = [];
for (let g = 0; g < FACE_GROUPS && buffer; g++) {
for (let i = 0; i < sections.length; i++) {
const group = sections[i].meshes[layer]!.groups![g];
if (group.count === 0) continue;
const from = group.first * TERRAIN_QUAD_BYTES;
const to = firsts[i * FACE_GROUPS + g] * TERRAIN_QUAD_BYTES;
const size = group.count * TERRAIN_QUAD_BYTES;
const vertices = old.meshed.get(sections[i]);
if (vertices) {
this.buffers.write(buffer, to, vertices, from, size);
continue;
}
const last = copies.length - 3;
if (
last >= 0 && copies[last] + copies[last + 2] === from &&
copies[last + 1] + copies[last + 2] === to
) {
copies[last + 2] += size;
} else {
copies.push(from, to, size);
}
}
}
if (old.buffer) {
if (buffer) this.buffers.copy(old.buffer, buffer, copies);
this.buffers.destroy(old.buffer);
}
for (let i = 0; i < sections.length; i++) {
const mesh = sections[i].meshes[layer]!;
for (let g = 0; g < FACE_GROUPS; g++) mesh.groups![g].first = firsts[i * FACE_GROUPS + g];
mesh.slot = i;
}
this.layers[layer] = { buffer, sections, meshed: new Map(), changed: false };
}
}
dispose() {
for (const layer of REGION_LAYERS) {
if (this.layers[layer].buffer) this.buffers.destroy(this.layers[layer].buffer!);
this.layers[layer] = empty_layer();
}
}
}
+36 -6
View File
@@ -100,8 +100,9 @@ let pending_destroy: GPUBuffer[] = [];
// switches for finding out what a frame costs, see the f3 performance window. msaa is changed at the start of the next
// frame. split_passes gives each section (see gpu_section) passes of its own so the gpu times them apart, which costs
// a little since every pass loads and stores the render targets. uncapped starts frames back to back instead of with
// the display's refresh, see the game loop in main.ts
export const render_debug = { msaa: false, split_passes: false, uncapped: false };
// the display's refresh, see the game loop in main.ts. render_regions draws terrain by region, see
// ClientLevel.use_render_regions
export const render_debug = { msaa: false, split_passes: false, uncapped: false, render_regions: false };
// what was drawn, for the last whole frame
export interface RenderStats {
draw_calls: number;
@@ -539,7 +540,9 @@ export function flush_batch() {
// what's bound for terrain draws in the current pass, so drawing hundreds of chunks doesn't bind the same things
// again for each one. cleared whenever the pipeline changes
let terrain_binds: { slot: number; texture: GPUTexture; index_buffer: GPUBuffer } | undefined;
let terrain_binds:
| { slot: number; texture: GPUTexture; index_buffer: GPUBuffer; vertex_buffer: GPUBuffer }
| undefined;
// draws quads first to first + quad_count of a chunk mesh (4 vertices each). without an index buffer the quads are
// drawn in order
@@ -578,9 +581,11 @@ export function draw_terrain(
if (terrain_binds?.index_buffer !== index_buffer) {
render_pass.setIndexBuffer(index_buffer, "uint32");
}
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer };
if (terrain_binds?.vertex_buffer !== vertex_buffer) {
render_pass.setVertexBuffer(0, vertex_buffer);
}
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer, vertex_buffer };
render_pass.setVertexBuffer(0, vertex_buffer);
render_pass.drawIndexed(quad_count * 6, 1, first * 6);
frame_stats.draw_calls += 1;
frame_stats.quads[layer] += quad_count;
@@ -618,7 +623,13 @@ export function draw_instances(
}
// 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) {
export function write_buffer(
buffer: GPUBuffer,
byte_offset: number,
data: Float32Array | Uint8Array<ArrayBuffer>,
first: number,
count: number,
) {
device.queue.writeBuffer(buffer, byte_offset, data, first, count);
}
@@ -636,6 +647,25 @@ export function create_vertex_buffer(vertices: Float32Array<ArrayBuffer> | Uint8
return buffer;
}
// an empty vertex buffer of size bytes that copy_buffer can copy from and to
export function create_copyable_vertex_buffer(size: number): GPUBuffer {
return device.createBuffer({
size: Math.max(4, size),
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
});
}
// copies ranges of from into to on the gpu, as from offset, to offset and size in bytes, three numbers each. the copies
// happen before any later draw or write_buffer
export function copy_buffer(from: GPUBuffer, to: GPUBuffer, ranges: number[]) {
if (ranges.length === 0) return;
const copies = device.createCommandEncoder();
for (let i = 0; i < ranges.length; i += 3) {
copies.copyBufferToBuffer(from, ranges[i], to, ranges[i + 1], ranges[i + 2]);
}
device.queue.submit([copies.finish()]);
}
export function create_index_buffer(indices: Uint32Array): GPUBuffer {
const buffer = device.createBuffer({
size: Math.max(4, indices.byteLength),
+47 -16
View File
@@ -29,13 +29,14 @@ import {
flush_batch,
get_current_texture,
push_vertex,
render_debug,
set_current_texture,
Texture,
use_texture,
view_projection,
white_tex,
} from "@/client/renderer/mod.ts";
import { type BlockRegistry, EverythingRegistry, type RenderLayer } from "@/common/everything_registry.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { bake_block, type BakedQuad, FACE_INDEX, looks_by_state, type ModelJson } from "@/common/block_models.ts";
import { BREAK_STAGES, ID_MASK } from "@/common/constants.ts";
import { type Shape, shape_at } from "@/common/block_shapes.ts";
@@ -45,6 +46,7 @@ import { FACE_AXIS, FACE_NORMALS } from "@/client/workers/translucent_sort.ts";
import { Frustum } from "./frustum.ts";
import { draw_visuals } from "./visuals.ts";
import { reachable_sections } from "./occlusion.ts";
import { REGION_LAYERS, type RegionLayer, type RenderRegion } from "@/client/level/render_region.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
@@ -52,8 +54,9 @@ export class LevelRenderer {
frustum = new Frustum();
// sections in view this frame, near to far, worked out once for all the layers
#visible: RenderSection[] = [];
// the chunks they're in
// the chunks they're in, and the regions with the ones in each, the regions near to far too
#visible_chunks = new Set<Chunk>();
#visible_regions = new Map<RenderRegion, RenderSection[]>();
// what the camera could see the last time it was searched for, which only changes when it moves to another section
// or the sections change, see occlusion.ts
#reachable: { sections: RenderSection[] | undefined; level: ClientLevel; version: number; key: string } | undefined;
@@ -75,15 +78,14 @@ export class LevelRenderer {
render_opaque(level: ClientLevel, camera: Camera) {
profiler.section("chunk upkeep", () => this.#find_visible(level, camera));
set_current_texture(level.image.tex);
for (const layer of ["solid", "cutout"] as const) {
for (const layer of REGION_LAYERS) {
if (!this.draw[layer]) continue;
profiler.section(layer, () => {
for (const section of this.#visible) {
const mesh = section.meshes[layer];
if (mesh) {
draw_facing_camera(layer, mesh, camera);
}
if (mesh?.vertex_buffer) draw_facing_camera(layer, mesh.vertex_buffer, mesh, camera);
}
for (const [region, sections] of this.#visible_regions) draw_region(layer, region, sections, camera);
});
}
}
@@ -94,8 +96,11 @@ export class LevelRenderer {
level.request_meshes(camera);
level.update_translucent_sorting(camera);
level.use_render_regions(render_debug.render_regions);
level.update_regions();
this.frustum.update(view_projection());
this.#visible_chunks.clear();
this.#visible_regions.clear();
const reachable = this.#reachable_sections(level, camera);
if (reachable) {
this.#visible = reachable.filter((section) => this.#in_view(section));
@@ -106,7 +111,12 @@ export class LevelRenderer {
.sort((a, b) => a.distance - b.distance)
.map(({ section }) => section);
}
for (const section of this.#visible) this.#visible_chunks.add(section.chunk);
for (const section of this.#visible) {
this.#visible_chunks.add(section.chunk);
const in_region = this.#visible_regions.get(section.region);
if (in_region) in_region.push(section);
else this.#visible_regions.set(section.region, [section]);
}
}
#reachable_sections(level: ClientLevel, camera: Camera) {
@@ -133,7 +143,7 @@ export class LevelRenderer {
.sort((a, b) => b.distance - a.distance);
for (const { mesh } of sections) {
draw_terrain("translucent", mesh.vertex_buffer, 0, mesh.quad_count, mesh.index_buffer);
draw_terrain("translucent", mesh.vertex_buffer!, 0, mesh.quad_count, mesh.index_buffer);
}
}
@@ -412,12 +422,8 @@ function decal_uv(face: number, x: number, y: number, z: number): [number, numbe
// only the face groups that can face the camera: quads facing +x can only be seen from beyond the lowest x plane any
// of them lie on. neighboring groups that are both drawn go in one draw call
function draw_facing_camera(layer: RenderLayer, mesh: ChunkMesh, camera: Camera) {
const groups = mesh.groups;
if (!groups) {
draw_terrain(layer, mesh.vertex_buffer, 0, mesh.quad_count);
return;
}
function draw_facing_camera(layer: RegionLayer, buffer: GPUBuffer, mesh: ChunkMesh, camera: Camera) {
const groups = mesh.groups!;
let start = 0;
let end = 0;
for (let g = 0; g < FACE_GROUPS; g++) {
@@ -426,12 +432,37 @@ function draw_facing_camera(layer: RenderLayer, mesh: ChunkMesh, camera: Camera)
continue;
}
if (group.first !== end) {
draw_terrain(layer, mesh.vertex_buffer, start, end - start);
draw_terrain(layer, buffer, start, end - start);
start = group.first;
}
end = group.first + group.count;
}
draw_terrain(layer, mesh.vertex_buffer, start, end - start);
draw_terrain(layer, buffer, start, end - start);
}
// a region's sections in view, a face group at a time (see render_region.ts), only where the group can face the camera:
// quads facing +x can only be seen from beyond the lowest x plane any of them lie on. sections next to each other in the
// buffer that are both drawn go in one draw call
function draw_region(layer: RegionLayer, region: RenderRegion, in_view: RenderSection[], camera: Camera) {
const buffer = region.layers[layer].buffer;
if (!buffer) return;
// in the order they're in the buffer
const sections = in_view.filter((section) => section.meshes[layer]?.slot !== undefined)
.sort((a, b) => a.meshes[layer]!.slot! - b.meshes[layer]!.slot!);
for (let g = 0; g < FACE_GROUPS; g++) {
let start = 0;
let end = 0;
for (const section of sections) {
const group = section.meshes[layer]!.groups![g];
if (group.count === 0 || !group_faces_camera(g, group.min, group.max, camera)) continue;
if (group.first !== end) {
draw_terrain(layer, buffer, start, end - start);
start = group.first;
}
end = group.first + group.count;
}
draw_terrain(layer, buffer, start, end - start);
}
}
export function group_faces_camera(
+127
View File
@@ -0,0 +1,127 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// a render region keeps its sections' solid and cutout quads in one buffer per layer, by face group, and puts it
// together again when they change, see client/level/render_region.ts
import { assert, assertEquals } from "@std/assert";
import { type RegionBuffers, RenderRegion } from "@/client/level/render_region.ts";
import type { RenderSection } from "@/client/level/client_level.ts";
import { FACE_GROUPS, type FaceGroup, TERRAIN_QUAD_BYTES } from "@/client/workers/chunk_messages.ts";
// buffers in memory, keeping what was written to them
interface FakeBuffer {
bytes: Uint8Array;
destroyed: boolean;
}
function fake_buffers() {
const written = { bytes: 0 };
const buffers: RegionBuffers = {
create: (size) => ({ bytes: new Uint8Array(size), destroyed: false }) as unknown as GPUBuffer,
write: (buffer, offset, data, first, size) => {
written.bytes += size;
(buffer as unknown as FakeBuffer).bytes.set(data.subarray(first, first + size), offset);
},
copy: (from, to, ranges) => {
const source = from as unknown as FakeBuffer;
assert(!source.destroyed);
for (let i = 0; i < ranges.length; i += 3) {
(to as unknown as FakeBuffer).bytes.set(
source.bytes.subarray(ranges[i], ranges[i] + ranges[i + 2]),
ranges[i + 1],
);
}
},
destroy: (buffer) => (buffer as unknown as FakeBuffer).destroyed = true,
};
return { buffers, written };
}
// a section's solid quads as the chunk worker sends them, counts[g] in each group, each quad's bytes all a tag that
// says which mesh, group and quad it is
function mesh(region: RenderRegion, section: RenderSection, mesh: number, counts: number[]) {
const groups: FaceGroup[] = [];
const tags: number[][] = [];
let first = 0;
for (let g = 0; g < FACE_GROUPS; g++) {
groups.push({ first, count: counts[g], min: 0, max: 0 });
tags.push(Array.from({ length: counts[g] }, (_, q) => mesh * 40 + g * 5 + q));
first += counts[g];
}
const vertices = new Uint8Array(first * TERRAIN_QUAD_BYTES);
tags.flat().forEach((tag, q) => vertices.fill(tag, q * TERRAIN_QUAD_BYTES, (q + 1) * TERRAIN_QUAD_BYTES));
section.meshes = { solid: { quad_count: first, groups } };
region.meshed("solid", section, vertices);
return tags;
}
const new_section = () => ({ meshes: {} }) as RenderSection;
// the tags of a section's quads in each group, as they are in the region's buffer
function in_buffer(region: RenderRegion, section: RenderSection) {
const bytes = (region.layers.solid.buffer as unknown as FakeBuffer).bytes;
return section.meshes.solid!.groups!.map(({ first, count }) =>
Array.from({ length: count }, (_, q) => bytes[(first + q) * TERRAIN_QUAD_BYTES])
);
}
// each group's quads are the sections' one after another, so the ones drawn together are one draw call
function assert_by_group(region: RenderRegion) {
let end = 0;
for (let g = 0; g < FACE_GROUPS; g++) {
for (const section of region.layers.solid.sections) {
const group = section.meshes.solid!.groups![g];
assertEquals(group.first, end);
end += group.count;
}
}
}
Deno.test("a region's sections' quads are in its buffer group by group", () => {
const { buffers } = fake_buffers();
const region = new RenderRegion(buffers);
const sections = [new_section(), new_section(), new_section()];
const tags = [
mesh(region, sections[0], 0, [2, 0, 1, 3, 0, 0, 1]),
mesh(region, sections[1], 1, [0, 4, 1, 0, 2, 1, 0]),
mesh(region, sections[2], 2, [1, 1, 1, 1, 1, 1, 1]),
];
region.update();
assertEquals(sections.map((section) => in_buffer(region, section)), tags);
assert_by_group(region);
assertEquals(region.layers.cutout.buffer, undefined);
});
Deno.test("a region keeps what didn't change when its sections are meshed again, lose their quads or come", () => {
const { buffers, written } = fake_buffers();
const region = new RenderRegion(buffers);
const sections = [new_section(), new_section(), new_section(), new_section()];
const tags = [
mesh(region, sections[0], 0, [2, 0, 1, 3, 0, 0, 1]),
mesh(region, sections[1], 1, [0, 4, 1, 0, 2, 1, 0]),
mesh(region, sections[2], 2, [1, 1, 1, 1, 1, 1, 1]),
];
region.update();
const old = region.layers.solid.buffer as unknown as FakeBuffer;
// the first loses its quads, the second is meshed again, a fourth comes
region.removed("solid", sections[0]);
sections[0].meshes = {};
tags[1] = mesh(region, sections[1], 3, [1, 0, 0, 0, 0, 0, 2]);
tags[3] = mesh(region, sections[3], 4, [0, 0, 3, 0, 0, 0, 0]);
written.bytes = 0;
region.update();
assert(old.destroyed);
assertEquals(region.layers.solid.sections.length, 3);
assertEquals([1, 2, 3].map((i) => in_buffer(region, sections[i])), [tags[1], tags[2], tags[3]]);
assert_by_group(region);
assertEquals(written.bytes, 6 * TERRAIN_QUAD_BYTES, "only the new quads are written, the rest are copied");
// a layer that didn't change stays as it is
const solid = region.layers.solid.buffer;
region.update();
assertEquals(region.layers.solid.buffer, solid);
region.dispose();
assert((solid as unknown as FakeBuffer).destroyed);
});