From b726ce9695e394b47a4ab56fad73e7c336158582 Mon Sep 17 00:00:00 2001 From: Paula Date: Sat, 7 Nov 2026 11:41:21 -0300 Subject: [PATCH] Meshing and lighting per section --- client/benchmark/benchmark.ts | 2 +- client/benchmark/report.ts | 4 +- client/gui/debug_overlay.ts | 15 +- client/level/client_level.ts | 347 +++++++++++++++-------------- client/rendering/level_renderer.ts | 76 ++++--- client/rendering/visuals.ts | 57 +++-- client/workers/chunk_messages.ts | 62 ++++-- client/workers/chunk_worker.ts | 142 ++++++------ client/workers/lighting.ts | 58 ++--- common/everything_registry.ts | 13 ++ server/game/world.ts | 16 +- tests/benchmark_test.ts | 2 +- tests/client_level_test.ts | 104 +++++++++ tests/entity_light_test.ts | 58 ++--- tests/fluid_test.ts | 28 +-- tests/helpers.ts | 107 ++++++++- tests/juice_test.ts | 4 +- tests/natural_spawn_test.ts | 27 +-- tests/terrain_culling_test.ts | 64 ++---- tests/tint_test.ts | 28 +-- tests/visuals_test.ts | 66 +++--- 21 files changed, 736 insertions(+), 544 deletions(-) create mode 100644 tests/client_level_test.ts diff --git a/client/benchmark/benchmark.ts b/client/benchmark/benchmark.ts index 34cc775..1fc54ff 100644 --- a/client/benchmark/benchmark.ts +++ b/client/benchmark/benchmark.ts @@ -334,7 +334,7 @@ export class RenderBenchmark { return { draw_calls, quads: RENDER_LAYERS.reduce((sum, layer) => sum + quads[layer], 0), - chunks_in_view: level_renderer.visible_chunks, + sections_in_view: level_renderer.visible_sections, entities_in_view: level_renderer.drawn_entities, }; } diff --git a/client/benchmark/report.ts b/client/benchmark/report.ts index 3bc02f2..4d1c351 100644 --- a/client/benchmark/report.ts +++ b/client/benchmark/report.ts @@ -5,7 +5,7 @@ // tools/compare_benchmarks.ts reads to put runs side by side // changes when the scenes or the level change, since runs of different versions don't compare -export const BENCHMARK_VERSION = 1; +export const BENCHMARK_VERSION = 2; // how fast and how smooth frames were, from the time between them. the lows are the fps of the frame that 99% (and // 99.9%) of the others were faster than @@ -36,7 +36,7 @@ export interface SceneResult { // what the first paced frame drew, which runs of the same version should about agree on draw_calls: number; quads: number; - chunks_in_view: number; + sections_in_view: number; entities_in_view: number; } diff --git a/client/gui/debug_overlay.ts b/client/gui/debug_overlay.ts index 8a10024..bc48297 100644 --- a/client/gui/debug_overlay.ts +++ b/client/gui/debug_overlay.ts @@ -98,8 +98,9 @@ export class DebugOverlay { const level = client.level; const level_renderer = client.game_renderer.level_renderer; const { meshed, bytes } = this.#count_chunks(client); - text(`chunks: ${level.chunks.size} loaded, ${meshed} meshed, ${level_renderer.visible_chunks} in view`); - text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} meshing`); + text(`chunks: ${level.chunks.size} loaded`); + text(` sections: ${meshed} with meshes, ${level_renderer.visible_sections} in view`); + text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} requests meshing`); text(` meshes: ${(bytes / 1024 / 1024).toFixed(1)} MB`); text(`entities: ${level.entities.size} loaded, ${level_renderer.drawn_entities} in view`); separator(); @@ -142,7 +143,7 @@ export class DebugOverlay { ); } - // meshed chunks and what their meshes take on the gpu, once a second + // sections with meshes and what their meshes take on the gpu, once a second #count_chunks(client: Client) { const now = performance.now(); if (now - this.#chunk_stats_time < CHUNK_STATS_MS) return this.#chunk_stats; @@ -150,9 +151,11 @@ export class DebugOverlay { let meshed = 0; let bytes = 0; for (const chunk of client.level.chunks.values()) { - const meshes = Object.values(chunk.meshes); - if (meshes.length > 0) meshed += 1; - for (const mesh of meshes) bytes += mesh.vertex_buffer.size + (mesh.index_buffer?.size ?? 0); + 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); + } } this.#chunk_stats = { meshed, bytes }; return this.#chunk_stats; diff --git a/client/level/client_level.ts b/client/level/client_level.ts index 5afd241..72d2487 100644 --- a/client/level/client_level.ts +++ b/client/level/client_level.ts @@ -13,17 +13,16 @@ import { AIR_ID } from "@/common/protocol.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts"; import { DEFAULT_WATER_COLOR, foliage_color, grass_color, water_color } from "@/common/worldgen/biome_colors.ts"; import { - block_light_emission, - block_light_opacity, BlockRegistry, 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"; -import type { WorldShape } from "@/common/world_shape.ts"; -import { ChunkColumn, section_index, type SectionData } from "@/common/section.ts"; +import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts"; +import { ChunkColumn, column_heights, section_index, type SectionData } from "@/common/section.ts"; import { AssetManager } from "../assets.ts"; import { ChunkWorkerPool } from "../chunk_workers.ts"; import type { FaceGroup, FromChunkWorker, SectionLight } from "../workers/chunk_messages.ts"; @@ -50,19 +49,29 @@ export interface Chunk { z: number; // its blocks and each column's biome, as the server sent them column: ChunkColumn; - dirty: boolean; + // each column's lowest y that sees the sky, see column_heights in common/section.ts. kept up to date with its blocks + sky: Int16Array; + // one for each of its sections, from the bottom of the world up + sections: RenderSection[]; + // each column's biome grass color, x then z, then each column's foliage color, then water color + biome_colors: Uint32Array; +} + +// a chunk's section as it's drawn, like sodium's RenderSection. each is meshed and lit on its own +export interface RenderSection { + chunk: Chunk; + // in its chunk, from the bottom of the world up + index: number; // bumped on every mesh request so late results from older requests get ignored mesh_version: number; meshes: Partial>; - // the lowest and highest y of its meshes, for frustum culling + // the lowest and highest y of its quads and visuals, for frustum culling. Infinity and -Infinity when it has none min_y: number; max_y: number; // only for translucent meshes that have to be sorted again as the camera moves translucent_sort?: TranslucentSort; - // each column's biome grass color, x then z, then each column's foliage color, then water color - biome_colors: Uint32Array; - // from its last mesh by section, see get_light. undefined until it's been meshed - light?: SectionLight[]; + // from its last mesh, see get_light. undefined until it's been meshed + light?: SectionLight; } export interface ChunkMesh { @@ -107,9 +116,10 @@ export interface BlockData { data: Record; } -const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1]] as const; -// light spreads diagonally too, so meshing and lighting need all 8 -const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [1, 1]] as const; +// light spreads diagonally too, so meshing and lighting need all 8 neighbors +const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]] as const; +// how far a change in light reaches, and one more for the faces at its edge, whose corners are lit from beyond them +const LIGHT_REACH = 16; // how far past the view distance chunks are kept, like minecraft's ClientChunkCache. the server tells the client // which ones to forget, this only catches the ones it didn't const STORAGE_MARGIN = 3; @@ -119,9 +129,12 @@ const STORAGE_MARGIN = 3; export class ClientLevel { image: Texture = AssetManager.instance.get("cubi:textures"); chunks = new Map(); - // the chunks request_meshes and update_translucent_sorting look at, so they don't go through every chunk each frame - #dirty = new Set(); - #sorted = new Set(); + // the sections request_meshes and update_translucent_sorting look at, so they don't go through every one each + // frame. dirty ones by chunk, since a chunk's go in one request + #dirty = new Map>(); + #sorted = new Set(); + // the sections with quads or visuals, the only ones there are to draw + drawn = new Set(); second_timer = 0; tick_timer = 0; // world time in ticks, counted here between the server's updates. see common/time.ts @@ -139,6 +152,7 @@ export class ClientLevel { workers: ChunkWorkerPool; #blocks = EverythingRegistry.get_registry("blocks"); + #light = light_tables(this.#blocks); // the server's numeric block ids to this client's #to_local: Uint32Array; @@ -219,34 +233,23 @@ export class ClientLevel { biome_colors[CHUNK_AREA * 2 + column] = water_color(biome); }); + const sky = column_heights(column, this.#light.opacity).slice(CHUNK_AREA); + const chunk = this.get_chunk(x, z); if (chunk) { - // its old mesh stays up until the new one is ready + // its old meshes stay up until the new ones are ready chunk.column = column; + chunk.sky = sky; chunk.biome_colors = biome_colors; - this.#mark_dirty(chunk); } else { - const chunk: Chunk = { - x, - z, - column, - biome_colors, - dirty: true, - mesh_version: 0, - meshes: {}, - min_y: 0, - max_y: 0, - }; - this.chunks.set(chunk_key(x, z), chunk); - this.#dirty.add(chunk); - } - // their border faces and light depend on this one - for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { - const neighbor = this.get_chunk(x + dx, z + dz); - if (neighbor) { - this.#mark_dirty(neighbor); + const chunk: Chunk = { x, z, column, sky, biome_colors, sections: [] }; + for (let index = 0; index < column.sections.length; index++) { + chunk.sections.push({ chunk, index, mesh_version: 0, meshes: {}, min_y: Infinity, max_y: -Infinity }); } + this.chunks.set(chunk_key(x, z), chunk); } + // and its neighbors, whose border faces and light depend on it + this.#mark_dirty_around(x, z, this.shape.min_y, this.shape.max_y); } // the server moved the player's view, chunks far outside it go even if the server didn't say @@ -269,11 +272,12 @@ export class ClientLevel { dispose() { this.workers.terminate(); for (const chunk of this.chunks.values()) { - this.delete_chunk_mesh(chunk); + for (const section of chunk.sections) this.#delete_mesh(section); } this.visuals.dispose(); this.chunks.clear(); this.#dirty.clear(); + this.drawn.clear(); } get_chunk(x: number, z: number) { @@ -296,29 +300,23 @@ export class ClientLevel { const [nid, info] = EverythingRegistry.get_full("blocks", block.id)!; this.#retain(block.x, block.y, block.z); - const lx = block.x - block_chunk_x * CHUNK_SIZE; - const lz = block.z - block_chunk_z * CHUNK_SIZE; - const old_nid = chunk.column.get(block.x, block.y, block.z) & ID_MASK; const value = state === undefined ? default_block_value(nid, info) : block_value(nid, state); chunk.column.set(block.x, block.y, block.z, value); - this.#mark_dirty(chunk); - this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid); + this.#block_changed(chunk, block.x, block.y, block.z, old_nid, nid); } - // block light << 4 | sky light there, as of its chunk's last mesh. the shape's open light (full sky light, unless + // block light << 4 | sky light there, as of its section's last mesh. the shape's open light (full sky light, unless // the dimension has none) above the world and where it isn't known yet, so entities don't go dark while their // chunk loads get_light(x: number, y: number, z: number): number { const block_y = Math.floor(y); if (block_y >= this.shape.max_y) return this.shape.open_light; if (block_y < this.shape.min_y) return 0; - const chunk_x = Math.floor(x / CHUNK_SIZE); - const chunk_z = Math.floor(z / CHUNK_SIZE); - const light = this.get_chunk(chunk_x, chunk_z)?.light; - if (!light) return this.shape.open_light; - const section = light[(block_y - this.shape.min_y) >> 4]; - return typeof section === "number" ? section : section[section_index(Math.floor(x), block_y, Math.floor(z))]; + const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)); + const light = chunk?.sections[(block_y - this.shape.min_y) >> 4].light; + if (light === undefined) return this.shape.open_light; + return typeof light === "number" ? light : light[section_index(Math.floor(x), block_y, Math.floor(z))]; } // the id with its state bits, VOID outside loaded chunks @@ -403,8 +401,6 @@ export class ClientLevel { this.#retain(x, y, z); - const lx = x - block_chunk_x * CHUNK_SIZE; - const lz = z - block_chunk_z * CHUNK_SIZE; const old_value = chunk.column.get(x, y, z); const old_nid = old_value & ID_MASK; const old_block = this.#blocks[old_nid]; @@ -413,56 +409,53 @@ export class ClientLevel { ? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR : AIR; chunk.column.set(x, y, z, fluid); - this.#mark_dirty(chunk); - this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, fluid); + this.#block_changed(chunk, x, y, z, old_nid, fluid); } - // a block that lets through or gives off a different amount of light changes the light up to 15 blocks - // away, so in every neighbor. otherwise only a block on a chunk's edge matters, for its neighbor's faces - #mark_neighbors_dirty( - block_chunk_x: number, - block_chunk_z: number, - lx: number, - lz: number, - old_nid: number, - new_nid: number, - ) { - const old_block = this.#blocks[old_nid]; - const new_block = this.#blocks[new_nid]; - if ( - block_light_opacity(old_block) !== block_light_opacity(new_block) || - block_light_emission(old_block) !== block_light_emission(new_block) - ) { - for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { - const n = this.get_chunk(block_chunk_x + dx, block_chunk_z + dz); - if (n) { - this.#mark_dirty(n); - } - } + // what a block changing remeshes: its section, and the ones beside it when it's on their border. a block that lets + // through or gives off a different amount of light changes the light up to 15 blocks away, so in every section + // around it, and when it moves its column's sky height, from the old height to the new one in the columns around + #block_changed(chunk: Chunk, x: number, y: number, z: number, old_nid: number, new_nid: number) { + const { opacity, emission } = this.#light; + if (opacity[old_nid] !== opacity[new_nid] || emission[old_nid] !== emission[new_nid]) { + const column = (z & 15) * CHUNK_SIZE + (x & 15); + const old_sky = chunk.sky[column]; + chunk.sky = column_heights(chunk.column, opacity).slice(CHUNK_AREA); + const new_sky = chunk.sky[column]; + const changed = old_sky === new_sky ? [y] : [y, old_sky, new_sky]; + this.#mark_dirty_around( + chunk.x, + chunk.z, + Math.min(...changed) - LIGHT_REACH, + Math.max(...changed) + LIGHT_REACH, + ); return; } - if (lx === 0) { - const n = this.get_chunk(block_chunk_x - 1, block_chunk_z); - if (n) { - this.#mark_dirty(n); - } - } else if (lx === CHUNK_SIZE - 1) { - const n = this.get_chunk(block_chunk_x + 1, block_chunk_z); - if (n) { - this.#mark_dirty(n); + // the way to the neighbor on each axis whose faces it's next to, 0 for none + const side = (local: number) => local === 0 ? -1 : local === CHUNK_SIZE - 1 ? 1 : 0; + const sx = side(x & 15); + const sy = side((y - this.shape.min_y) & 15); + const sz = side(z & 15); + const index = (y - this.shape.min_y) >> 4; + for (const dx of new Set([0, sx])) { + for (const dz of new Set([0, sz])) { + const sections = this.get_chunk(chunk.x + dx, chunk.z + dz)?.sections; + for (const dy of new Set([0, sy])) { + const section = sections?.[index + dy]; + if (section) this.#mark_dirty(section); + } } } - if (lz === 0) { - const n = this.get_chunk(block_chunk_x, block_chunk_z - 1); - if (n) { - this.#mark_dirty(n); - } - } else if (lz === CHUNK_SIZE - 1) { - const n = this.get_chunk(block_chunk_x, block_chunk_z + 1); - if (n) { - this.#mark_dirty(n); - } + } + + // the sections from from_y to to_y of a chunk and the 8 around it + #mark_dirty_around(chunk_x: number, chunk_z: number, from_y: number, to_y: number) { + const lowest = Math.max(0, (from_y - this.shape.min_y) >> 4); + for (const [dx, dz] of [[0, 0], ...NEIGHBOR_OFFSETS]) { + const sections = this.get_chunk(chunk_x + dx, chunk_z + dz)?.sections ?? []; + const highest = Math.min(sections.length - 1, (to_y - this.shape.min_y) >> 4); + for (let i = lowest; i <= highest; i++) this.#mark_dirty(sections[i]); } } @@ -520,9 +513,12 @@ export class ClientLevel { if (!chunk) { return; } - this.delete_chunk_mesh(chunk); - this.chunks.delete(key); + for (const section of chunk.sections) { + this.#delete_mesh(section); + this.drawn.delete(section); + } this.#dirty.delete(chunk); + this.chunks.delete(key); this.block_data.delete(key); this.visuals.unload(cx, cz); for (const [position, { x, z }] of this.break_progress) { @@ -566,10 +562,10 @@ export class ClientLevel { return this.block_data.get(key)?.get(`${x},${y},${z}`)?.data; } - // a chunk is only meshed once all its neighbors exist, otherwise its border faces and light would be - // wrong and it would have to be meshed again as each neighbor loads + // a chunk's sections are only meshed once all its neighbors exist, otherwise their border faces and light would be + // wrong and they would have to be meshed again as each neighbor loads can_mesh(chunk: Chunk) { - for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { + for (const [dx, dz] of NEIGHBOR_OFFSETS) { if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) { return false; } @@ -577,46 +573,59 @@ export class ClientLevel { return true; } - // meshes asked of the workers that haven't come back, for the f3 performance window + // mesh requests sent to the workers that haven't come back, for the f3 performance window. each is some sections of + // a chunk meshes_in_flight = 0; // the rest wait for the next frame. chunks from the server come a few at a time, but the benchmark's level has every - // chunk at once, and each request copies its 3x3 chunks + // chunk at once, and each request copies the sections around the ones it's for max_meshes_in_flight = Infinity; - // dirty chunks that can be meshed and the meshes the workers are on, 0 once every chunk that can be is meshed + // requests for chunks with dirty sections that can be meshed, and the ones the workers are on. 0 once every + // section that can be is meshed get meshes_pending() { let pending = this.meshes_in_flight; - for (const chunk of this.#dirty) { + for (const chunk of this.#dirty.keys()) { if (this.can_mesh(chunk)) pending += 1; } return pending; } - // meshes every chunk again, for the benchmark to time + // meshes every section again, for the benchmark to time remesh_all() { - for (const chunk of this.chunks.values()) this.#mark_dirty(chunk); + for (const chunk of this.chunks.values()) { + for (const section of chunk.sections) this.#mark_dirty(section); + } } - // sends every dirty chunk that can be meshed to the workers + // sends every dirty section that can be meshed to the workers, a request per chunk request_meshes(camera: Camera) { - for (const chunk of this.#dirty) { + for (const [chunk, sections] of this.#dirty) { if (this.meshes_in_flight >= this.max_meshes_in_flight) { break; } if (!this.can_mesh(chunk)) { continue; } - chunk.dirty = false; this.#dirty.delete(chunk); - chunk.mesh_version += 1; - // the worker lights the whole 3x3 area. posting copies the sections' blocks, only of the ones that aren't all - // one block + let lowest = Infinity; + let highest = -Infinity; + for (const section of sections) { + section.mesh_version += 1; + lowest = Math.min(lowest, section.index); + highest = Math.max(highest, section.index); + } + // they're lit with the 3x3 chunks' sections from the one below them to the one above. posting copies the + // blocks, of only the sections that aren't all one block + const first = Math.max(0, lowest - 1); + const end = Math.min(chunk.sections.length, highest + 2); const chunks: (SectionData[] | null)[] = []; + const sky: (Int16Array | null)[] = []; const biome_colors: (Uint32Array | null)[] = []; for (let dz = -1; dz <= 1; dz++) { for (let dx = -1; dx <= 1; dx++) { const neighbor = this.get_chunk(chunk.x + dx, chunk.z + dz); - chunks.push(neighbor?.column.sections.map((section) => section.data) ?? null); + chunks.push(neighbor?.column.sections.slice(first, end).map((section) => section.data) ?? null); + sky.push(neighbor?.sky ?? null); biome_colors.push(neighbor?.biome_colors ?? null); } } @@ -625,20 +634,22 @@ export class ClientLevel { type: "mesh", chunk_x: chunk.x, chunk_z: chunk.z, - version: chunk.mesh_version, + sections: [...sections].map((section) => ({ index: section.index, version: section.mesh_version })), + first, chunks, + sky, biome_colors, camera: [camera.x, camera.y, camera.z], }); } } - // like sodium, a chunk's translucent quads only change order when the camera crosses one of the - // planes they lie on, so that's the only time they get sorted again + // like sodium, a section's translucent quads only change order when the camera crosses one of the planes they lie + // on, so that's the only time they get sorted again update_translucent_sorting(camera: Camera) { const position = [camera.x, camera.y, camera.z]; - for (const chunk of this.#sorted) { - const sort = chunk.translucent_sort!; + for (const section of this.#sorted) { + const sort = section.translucent_sort!; if (!crosses_planes(sort.planes, sort.camera, position)) { continue; } @@ -646,8 +657,9 @@ export class ClientLevel { sort.requested += 1; this.workers.post({ type: "sort", - chunk_x: chunk.x, - chunk_z: chunk.z, + chunk_x: section.chunk.x, + chunk_z: section.chunk.z, + index: section.index, version: sort.mesh_version, sort_version: sort.requested, centers: sort.centers, @@ -667,47 +679,55 @@ export class ClientLevel { #on_meshed(message: Extract) { this.meshes_in_flight -= 1; const chunk = this.get_chunk(message.chunk_x, message.chunk_z); - // unloaded, or remeshed again since this was requested - if (!chunk || chunk.mesh_version !== message.version) { + if (!chunk) { return; } - - this.delete_chunk_mesh(chunk); - chunk.light = message.light; - chunk.min_y = message.min_y; - chunk.max_y = message.max_y; - this.visuals.meshed(chunk.x, chunk.z, this.shape.min_y, message.visuals); - - for (const layer of RENDER_LAYERS) { - const { vertices, quad_count, groups } = message[layer]; - if (quad_count === 0) { + for (const mesh of message.sections) { + const section = chunk.sections[mesh.index]; + // remeshed again since this was requested + if (section.mesh_version !== mesh.version) { continue; } - chunk.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups }; - } + this.#delete_mesh(section); + section.light = mesh.light; + section.min_y = mesh.min_y; + section.max_y = mesh.max_y; + // with no quads or visuals its bounds are empty + if (mesh.min_y <= mesh.max_y) this.drawn.add(section); + else this.drawn.delete(section); + this.visuals.meshed(chunk.x, chunk.z, this.shape.min_y + section.index * SECTION_HEIGHT, mesh.visuals); - const translucent = message.translucent; - if (translucent.quad_count === 0) { - return; - } - chunk.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices); - if (translucent.sort_type === "dynamic") { - this.#sorted.add(chunk); - chunk.translucent_sort = { - mesh_version: message.version, - centers: translucent.centers, - planes: translucent.planes, - camera: message.camera, - requested: 0, - applied: 0, - }; + for (const layer of RENDER_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 }; + } + + const translucent = mesh.translucent; + if (translucent.quad_count === 0) { + continue; + } + section.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices); + if (translucent.sort_type === "dynamic") { + this.#sorted.add(section); + section.translucent_sort = { + mesh_version: mesh.version, + centers: translucent.centers, + planes: translucent.planes, + camera: message.camera, + requested: 0, + applied: 0, + }; + } } } #on_sorted(message: Extract) { - const chunk = this.get_chunk(message.chunk_x, message.chunk_z); - const sort = chunk?.translucent_sort; - const mesh = chunk?.meshes.translucent; + const section = this.get_chunk(message.chunk_x, message.chunk_z)?.sections[message.index]; + const sort = section?.translucent_sort; + const mesh = section?.meshes.translucent; // remeshed since, or a newer sort already came back if (!sort || !mesh || sort.mesh_version !== message.version || message.sort_version <= sort.applied) { return; @@ -719,26 +739,29 @@ export class ClientLevel { mesh.index_buffer = create_index_buffer(message.indices); } - delete_chunk_mesh(chunk: Chunk) { - for (const mesh of Object.values(chunk.meshes)) { + #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); } } - chunk.meshes = {}; - chunk.translucent_sort = undefined; - this.#sorted.delete(chunk); + section.meshes = {}; + section.translucent_sort = undefined; + this.#sorted.delete(section); } - // chunks that need meshing, some waiting on their neighbors to load + // sections that need meshing, some waiting on their chunk's neighbors to load get dirty_count() { - return this.#dirty.size; + let count = 0; + for (const sections of this.#dirty.values()) count += sections.size; + return count; } - #mark_dirty(chunk: Chunk) { - chunk.dirty = true; - this.#dirty.add(chunk); + #mark_dirty(section: RenderSection) { + const sections = this.#dirty.get(section.chunk); + if (sections) sections.add(section); + else this.#dirty.set(section.chunk, new Set([section])); } // the closest entity whose box is along the view of something at x/y/z looking at yaw/pitch, within max_distance. diff --git a/client/rendering/level_renderer.ts b/client/rendering/level_renderer.ts index 2a79d36..cd61d33 100644 --- a/client/rendering/level_renderer.ts +++ b/client/rendering/level_renderer.ts @@ -1,7 +1,13 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel } from "@/client/level/client_level.ts"; +import { + type Chunk, + CHUNK_SIZE, + type ChunkMesh, + ClientLevel, + type RenderSection, +} from "@/client/level/client_level.ts"; import { profiler } from "@/client/profiler.ts"; import { Camera } from "@/client/camera.ts"; import { AssetManager } from "@/client/assets.ts"; @@ -42,15 +48,17 @@ import { draw_visuals } from "./visuals.ts"; // draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities export class LevelRenderer { frustum = new Frustum(); - // chunks in view this frame, worked out once for all the layers - #visible: Chunk[] = []; + // sections in view this frame, near to far, worked out once for all the layers + #visible: RenderSection[] = []; + // the chunks they're in + #visible_chunks = new Set(); // what to draw, switched off in the f3 performance window to see what each costs draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true }; // entities drawn this frame, for the f3 performance window #drawn_entities = 0; - get visible_chunks() { + get visible_sections() { return this.#visible.length; } @@ -65,8 +73,8 @@ export class LevelRenderer { for (const layer of ["solid", "cutout"] as const) { if (!this.draw[layer]) continue; profiler.section(layer, () => { - for (const chunk of this.#visible) { - const mesh = chunk.meshes[layer]; + for (const section of this.#visible) { + const mesh = section.meshes[layer]; if (mesh) { draw_facing_camera(layer, mesh, camera); } @@ -75,52 +83,44 @@ export class LevelRenderer { } } - // asks for meshes and sorting, then works out which chunks are in view, near to far + // asks for meshes and sorting, then works out which sections are in view, near to far #find_visible(level: ClientLevel, camera: Camera) { level.request_meshes(camera); level.update_translucent_sorting(camera); this.frustum.update(view_projection()); - this.#visible.length = 0; - for (const chunk of level.chunks.values()) { - const drawn = Object.keys(chunk.meshes).length > 0 || level.visuals.has(chunk.x, chunk.z); - if (drawn && this.#in_view(chunk)) { - this.#visible.push(chunk); + const visible: { section: RenderSection; distance: number }[] = []; + this.#visible_chunks.clear(); + for (const section of level.drawn) { + if (this.#in_view(section)) { + visible.push({ section, distance: distance_sq(section, camera) }); + this.#visible_chunks.add(section.chunk); } } // near to far, like sodium, so what's in front fills the depth buffer first and the gpu can skip shading what's // behind it - const distance_sq = (chunk: Chunk) => { - const dx = (chunk.x + 0.5) * CHUNK_SIZE - camera.x; - const dz = (chunk.z + 0.5) * CHUNK_SIZE - camera.z; - return dx * dx + dz * dz; - }; - this.#visible.sort((a, b) => distance_sq(a) - distance_sq(b)); + visible.sort((a, b) => a.distance - b.distance); + this.#visible = visible.map(({ section }) => section); } - // translucent terrain, drawn after entities so they show through water and glass. - // chunks go back to front, and each chunk's quads are already sorted back to front + // translucent terrain, drawn after entities so they show through water and glass. sections go back to front, and + // each section's quads are already sorted back to front render_translucent(_level: ClientLevel, camera: Camera) { if (!this.draw.translucent) return; - const distance_sq = (x: number, z: number) => { - const dx = (x + 0.5) * CHUNK_SIZE - camera.x; - const dz = (z + 0.5) * CHUNK_SIZE - camera.z; - return dx * dx + dz * dz; - }; - const chunks = this.#visible - .filter((chunk) => chunk.meshes.translucent) - .map((chunk) => ({ mesh: chunk.meshes.translucent!, distance: distance_sq(chunk.x, chunk.z) })) + const sections = this.#visible + .filter((section) => section.meshes.translucent) + .map((section) => ({ mesh: section.meshes.translucent!, distance: distance_sq(section, camera) })) .sort((a, b) => b.distance - a.distance); - for (const { mesh } of chunks) { + for (const { mesh } of sections) { draw_terrain("translucent", mesh.vertex_buffer, 0, mesh.quad_count, mesh.index_buffer); } } - #in_view(chunk: Chunk) { - const x = chunk.x * CHUNK_SIZE; - const z = chunk.z * CHUNK_SIZE; - return this.frustum.intersects_box(x, chunk.min_y, z, x + CHUNK_SIZE, chunk.max_y, z + CHUNK_SIZE); + #in_view(section: RenderSection) { + const x = section.chunk.x * CHUNK_SIZE; + const z = section.chunk.z * CHUNK_SIZE; + return this.frustum.intersects_box(x, section.min_y, z, x + CHUNK_SIZE, section.max_y, z + CHUNK_SIZE); } // every entity in view but the one the camera is in @@ -178,7 +178,7 @@ export class LevelRenderer { // blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) { if (!this.draw.visuals) return; - level.visuals.frame(this.#visible, level.ticks + partial_tick); + level.visuals.frame(this.#visible_chunks, level.ticks + partial_tick); flush_batch(); set_current_texture(level.image.tex); draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]); @@ -251,6 +251,14 @@ export class LevelRenderer { #baked = new Map(); } +// from the camera to the middle of the section's bounds, squared +function distance_sq(section: RenderSection, camera: Camera) { + const dx = (section.chunk.x + 0.5) * CHUNK_SIZE - camera.x; + const dy = (section.min_y + section.max_y) / 2 - camera.y; + const dz = (section.chunk.z + 0.5) * CHUNK_SIZE - camera.z; + return dx * dx + dy * dy + dz * dz; +} + // how far models can stick out of their entity's box, like a swinging arm or a dropped item bobbing const ENTITY_CULL_MARGIN = 0.5; diff --git a/client/rendering/visuals.ts b/client/rendering/visuals.ts index 11eed0f..944a9ef 100644 --- a/client/rendering/visuals.ts +++ b/client/rendering/visuals.ts @@ -2,8 +2,8 @@ // 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 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 +// block, made when its section 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. an item is a model too, one per way an item can look, and a fluid's box is a model of its own import { mat4, vec3 } from "gl-matrix"; @@ -29,6 +29,7 @@ import { states_of, } from "@/common/block_models.ts"; import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; +import { SECTION_HEIGHT } from "@/common/world_shape.ts"; import type { ModelFace } from "@/common/mod_data.ts"; import { ItemStack } from "@/common/inventory.ts"; import { chunk_key, item_texture } from "@/common/utils.ts"; @@ -186,7 +187,7 @@ interface Entry { // a level's visuals export class Visuals { - // by chunk_key, then the block's index in its chunk counted from y 0, see #entry + // by chunk_key, then the block's index in its chunk counted from y 0, see #index #chunks = new Map>(); #level: VisualsLevel; // baked once per level, since a level's mods don't change @@ -213,32 +214,41 @@ export class Visuals { yield* this.#fluid_groups; } - // the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk (from min_y, the - // bottom of the world) and its value. visuals 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, min_y: number, found: Uint32Array) { + // the blocks with visuals a chunk's section was meshed with, as pairs of the block's index in the section (see + // section_index) and its value. bottom is the section's lowest y. visuals in it for blocks that are gone or + // changed go, and new ones are made. the section's light came with its mesh, so the ones that stay take it + meshed(chunk_x: number, chunk_z: number, bottom: number, found: Uint32Array) { const key = chunk_key(chunk_x, chunk_z); - const old = this.#chunks.get(key) ?? new Map(); - const kept = new Map(); + const entries = this.#chunks.get(key) ?? new Map(); + const old = new Map(); + for (const [index, entry] of entries) { + if (entry.y >= bottom && entry.y < bottom + SECTION_HEIGHT) old.set(index, entry); + } for (let i = 0; i < found.length; i += 2) { const local = found[i]; - const index = local + min_y * CHUNK_AREA; + const x = chunk_x * CHUNK_SIZE + (local & 15); + const y = bottom + (local >> 8); + const z = chunk_z * CHUNK_SIZE + ((local >> 4) & 15); + const index = this.#index(x, y, z); const value = found[i + 1]; const entry = old.get(index); old.delete(index); if (entry?.value === value) { this.#relight(entry); - kept.set(index, entry); continue; } - if (entry) this.#delete(entry); - const x = chunk_x * CHUNK_SIZE + (local % CHUNK_SIZE); - const z = chunk_z * CHUNK_SIZE + Math.floor(local / CHUNK_SIZE) % CHUNK_SIZE; - const made = this.#create(x, min_y + Math.floor(local / CHUNK_AREA), z, value); - if (made) kept.set(index, made); + if (entry) { + this.#delete(entry); + entries.delete(index); + } + const made = this.#create(x, y, z, value); + if (made) entries.set(index, made); } - for (const entry of old.values()) this.#delete(entry); - if (kept.size > 0) this.#chunks.set(key, kept); + for (const [index, entry] of old) { + this.#delete(entry); + entries.delete(index); + } + if (entries.size > 0) this.#chunks.set(key, entries); else this.#chunks.delete(key); } @@ -280,10 +290,13 @@ export class Visuals { } #entry(x: number, y: number, z: number) { - const chunk_x = Math.floor(x / CHUNK_SIZE); - const chunk_z = Math.floor(z / CHUNK_SIZE); - const index = y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE); - return this.#chunks.get(chunk_key(chunk_x, chunk_z))?.get(index); + const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)); + return this.#chunks.get(key)?.get(this.#index(x, y, z)); + } + + // a block's place in its chunk's map + #index(x: number, y: number, z: number) { + return y * CHUNK_AREA + (z & 15) * CHUNK_SIZE + (x & 15); } #create(x: number, y: number, z: number, value: number): Entry | undefined { diff --git a/client/workers/chunk_messages.ts b/client/workers/chunk_messages.ts index fe031db..90f3750 100644 --- a/client/workers/chunk_messages.ts +++ b/client/workers/chunk_messages.ts @@ -40,17 +40,24 @@ export type ToChunkWorker = // the numeric ids of blocks with visuals, and whether each visual replaces the block's model, see // ctx.render.register_visual visuals: [number, boolean][]; - // the dimension's height and sky light. the chunks meshed hold all of its height + // the dimension's height and sky light shape: WorldShapeJson; } + // sections of one chunk to mesh, sent together so they're lit together | { type: "mesh"; chunk_x: number; chunk_z: number; - version: number; + // the sections to mesh, by index from the bottom of the world, and the mesh_version each is meshed for + sections: { index: number; version: number }[]; + // the index of the lowest section in chunks + first: number; // the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting. each one's sections from the - // bottom of the world up, null for a chunk that isn't loaded + // one below the lowest to mesh to the one above the highest, as far as the world goes. null for a chunk that + // isn't loaded chunks: (SectionData[] | null)[]; + // the same chunks' sky heights, see column_heights in common/section.ts + sky: (Int16Array | null)[]; // the same chunks' biome colors (see Chunk.biome_colors in client_level.ts), blended across their edges biome_colors: (Uint32Array | null)[]; // where the camera is, to sort the translucent quads @@ -60,6 +67,8 @@ export type ToChunkWorker = type: "sort"; chunk_x: number; chunk_z: number; + // the section's index in its chunk + index: number; version: number; sort_version: number; centers: Float32Array; @@ -78,36 +87,45 @@ export interface LayerMesh { groups?: FaceGroup[]; } +// a section the worker meshed +export interface SectionMesh { + index: number; + version: number; + // the lowest and highest y of the section's quads and visuals in the world, for frustum culling. Infinity and + // -Infinity when it has none + min_y: number; + max_y: number; + solid: LayerMesh; + cutout: LayerMesh; + translucent: LayerMesh & { + // sorted back to front for the camera the mesh was requested with + indices: Uint32Array; + sort_type: SortType; + // what resorting needs, see translucent_sort.ts + centers: Float32Array; + planes: [Float32Array, Float32Array, Float32Array]; + }; + // entities are lit from it + light: SectionLight; + // the blocks in it with visuals, as pairs of the block's index in the section (see section_index) and its value + visuals: Uint32Array; +} + export type FromChunkWorker = | { type: "meshed"; chunk_x: number; chunk_z: number; - version: number; - // the lowest and highest y of the chunk's quads in the world, for frustum culling - min_y: number; - max_y: number; - solid: LayerMesh; - cutout: LayerMesh; - translucent: LayerMesh & { - // sorted back to front for the camera the mesh was requested with - indices: Uint32Array; - sort_type: SortType; - // what resorting needs, see translucent_sort.ts - centers: Float32Array; - planes: [Float32Array, Float32Array, Float32Array]; - }; + // the sections asked for, in the same order + sections: SectionMesh[]; + // what the translucent quads were sorted for camera: number[]; - // the chunk's light by section, from the bottom of the world up, see SectionLight. entities are lit from it - light: SectionLight[]; - // the blocks in it with visuals, as pairs of the block's index in the chunk (y from the bottom of the world, then - // z, then x) and its value - visuals: Uint32Array; } | { type: "sorted"; chunk_x: number; chunk_z: number; + index: number; version: number; sort_version: number; indices: Uint32Array; diff --git a/client/workers/chunk_worker.ts b/client/workers/chunk_worker.ts index 20643ea..687a7bc 100644 --- a/client/workers/chunk_worker.ts +++ b/client/workers/chunk_worker.ts @@ -16,6 +16,7 @@ import { type FaceGroup, type FromChunkWorker, type SectionLight, + type SectionMesh, TERRAIN_QUAD_BYTES, TERRAIN_VERTEX_BYTES, type ToChunkWorker, @@ -99,8 +100,7 @@ const waterlogged_shift = new Uint8Array(TABLE_SIZE); const block_visual = new Uint8Array(TABLE_SIZE); const HAS_VISUAL = 1; const REPLACED_MODEL = 2; -// the 3x3 chunks being meshed, made for the dimension's height by "init". its y, like the mesher's, counts from the -// bottom of the world +// the sections being meshed and the ones around them, made for the dimension's height by "init" let region: LightRegion; // the dimension's min_y, which quads are moved up by to be where they are in the world let world_min_y = 0; @@ -149,33 +149,31 @@ self.onmessage = (event: MessageEvent) => { break; case "mesh": { const chunks = message.chunks.map((data) => data?.map((section) => new Section(section)) ?? null); - region.fill(chunks); + // the region's bottom in the world + const bottom = world_min_y + message.first * SECTION_HEIGHT; + region.fill(chunks, message.sky, bottom); region.compute(light_tables); blend_biome_colors(message.biome_colors); - const { solid, cutout, translucent, min_y, max_y, visuals } = make_chunk_mesh( - message.chunk_x, - message.chunk_z, - chunks, - message.camera, - ); - const light = chunk_light(); + const sections: SectionMesh[] = message.sections.map(({ index, version }) => { + // the section's bottom in the region + const from = (index - message.first) * SECTION_HEIGHT; + return { + index, + version, + ...make_section_mesh(message.chunk_x, message.chunk_z, chunks, from, bottom, message.camera), + light: section_light(from), + }; + }); post( { type: "meshed", chunk_x: message.chunk_x, chunk_z: message.chunk_z, - version: message.version, - min_y, - max_y, - solid, - cutout, - translucent, + sections, camera: message.camera, - light, - visuals, }, - [ - ...light.filter((section) => typeof section !== "number").map((section) => section.buffer), + sections.flatMap(({ light, visuals, solid, cutout, translucent }) => [ + ...typeof light === "number" ? [] : [light.buffer], visuals.buffer, solid.vertices.buffer, cutout.vertices.buffer, @@ -183,7 +181,7 @@ self.onmessage = (event: MessageEvent) => { translucent.indices.buffer, translucent.centers.buffer, ...translucent.planes.map((planes) => planes.buffer), - ], + ]), ); break; } @@ -194,6 +192,7 @@ self.onmessage = (event: MessageEvent) => { type: "sorted", chunk_x: message.chunk_x, chunk_z: message.chunk_z, + index: message.index, version: message.version, sort_version: message.sort_version, indices, @@ -203,27 +202,23 @@ self.onmessage = (event: MessageEvent) => { } }; -// the middle chunk of the light region, packed for the main thread by section, see "meshed" -const section_light = new Uint8Array(SECTION_VOLUME); +// the light of the middle chunk's section from this y in the region, packed for the main thread, see SectionLight +const packed_light = new Uint8Array(SECTION_VOLUME); -function chunk_light(): SectionLight[] { - const sections: SectionLight[] = []; - for (let bottom = 0; bottom < region.height; bottom += SECTION_HEIGHT) { - let same = true; - for (let y = 0; y < SECTION_HEIGHT; y++) { - for (let z = 0; z < CHUNK_SIZE; z++) { - const from = (bottom + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE; - const to = (y << 8) | (z << 4); - for (let x = 0; x < CHUNK_SIZE; x++) { - const light = (region.block_light[from + x] << 4) | region.sky[from + x]; - section_light[to + x] = light; - if (light !== section_light[0]) same = false; - } +function section_light(from: number): SectionLight { + let same = true; + for (let y = 0; y < SECTION_HEIGHT; y++) { + for (let z = 0; z < CHUNK_SIZE; z++) { + const at = (from + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE; + const to = (y << 8) | (z << 4); + for (let x = 0; x < CHUNK_SIZE; x++) { + const light = (region.block_light[at + x] << 4) | region.sky[at + x]; + packed_light[to + x] = light; + if (light !== packed_light[0]) same = false; } } - sections.push(same ? section_light[0] : section_light.slice()); } - return sections; + return same ? packed_light[0] : packed_light.slice(); } function post(message: FromChunkWorker, transfer: Transferable[]) { @@ -553,8 +548,8 @@ function hides_fluid(nid: number) { return nid !== AIR && block_layers[nid] === SOLID; } -// a cell's block with its states, from the 3x3 chunks the region was filled from. 0 (air) above the world and for -// chunks that aren't there +// a cell's block with its states, from the 3x3 chunks' sections the region was filled from. 0 (air) outside them and +// for chunks that aren't there function region_value(chunks: (Section[] | null)[], index: number, y: number) { if (y < 0 || y >= region.height) return AIR; const x = index % REGION_SIZE; @@ -649,22 +644,39 @@ function underside(top: MeshQuad): MeshQuad { }; } -// region has to be filled and lit first -// chunks are the 3x3 chunks' blocks with their states, the middle one's for models that change with them and the -// ones around it for fluids, whose surface follows their neighbors' -function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] | null)[], camera: number[]) { - const middle = chunks[4]!; - // solid and cutout get a buffer per face group, translucent one for everything since it's sorted instead - const opaque = [SOLID, CUTOUT].map(() => - Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity })) - ); - const translucent_quads = new QuadBuffer(); +// quads being built, kept from one section to the next. solid and cutout get a buffer per face group, translucent one +// for everything since it's sorted instead +const opaque = [SOLID, CUTOUT].map(() => + Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity })) +); +const translucent_quads = new QuadBuffer(); +// for sorting the translucent quads +let centers = new Float32Array(256); +let faces = new Uint8Array(256); + +// the middle chunk's section from y from in the region, which has to be filled and lit first. bottom is the region's +// bottom in the world. chunks are the region's sections with their blocks' states, the middle one's for models that +// change with them and the ones around it for fluids, whose surface follows their neighbors' +function make_section_mesh( + chunk_x: number, + chunk_z: number, + chunks: (Section[] | null)[], + from: number, + bottom: number, + camera: number[], +) { + const section = chunks[4]![from >> 4]; + for (const groups of opaque) { + for (const group of groups) { + group.buffer.count = 0; + group.min = Infinity; + group.max = -Infinity; + } + } + translucent_quads.count = 0; mesh_min_y = Infinity; mesh_max_y = -Infinity; - // for sorting the translucent quads - let centers = new Float32Array(256); - let faces = new Uint8Array(256); - // the blocks with visuals, see "meshed" + // the blocks with visuals, see SectionMesh const visuals: number[] = []; // where the neighbor on each face is, same order as FACE_NORMALS @@ -673,7 +685,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] | // adds a lit quad of the block at x y z in the chunk to its layer const emit = (quad: MeshQuad, layer_id: number, x: number, y: number, z: number, alpha: number) => { const wx = chunk_x * CHUNK_SIZE + x; - const wy = world_min_y + y; + const wy = bottom + y; const wz = chunk_z * CHUNK_SIZE + z; const tint = quad.tint === GRASS ? blended[z * CHUNK_SIZE + x] @@ -706,13 +718,9 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] | } }; - for (let y = 0; y < region.height; y++) { - const section = middle[y >> 4]; - // nothing to mesh in a section of air - if (section.blocks === null && section.value === AIR) { - y |= 15; - continue; - } + // nothing to mesh in a section of air + const air = section.blocks === null && section.value === AIR; + for (let y = from; y < from + SECTION_HEIGHT && !air; y++) { for (let z = 0; z < CHUNK_SIZE; z++) { for (let x = 0; x < CHUNK_SIZE; x++) { // the middle chunk of the region @@ -758,10 +766,10 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] | const value = section.get(section_index(x, y, z)); if (block_visual[block_nid]) { - visuals.push(y * CHUNK_AREA + z * CHUNK_SIZE + x, value); + visuals.push(section_index(x, y, z), value); // with the block above and below, since a visual can reach past its block, like a large cog - if (world_min_y + y - 1 < mesh_min_y) mesh_min_y = world_min_y + y - 1; - if (world_min_y + y + 2 > mesh_max_y) mesh_max_y = world_min_y + y + 2; + if (bottom + y - 1 < mesh_min_y) mesh_min_y = bottom + y - 1; + if (bottom + y + 2 > mesh_max_y) mesh_max_y = bottom + y + 2; if (block_visual[block_nid] === REPLACED_MODEL) continue; } @@ -805,8 +813,8 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] | const [camera_x, camera_y, camera_z] = camera; return { - min_y: mesh_min_y === Infinity ? 0 : mesh_min_y, - max_y: mesh_max_y === -Infinity ? 0 : mesh_max_y, + min_y: mesh_min_y, + max_y: mesh_max_y, solid, cutout, translucent: { diff --git a/client/workers/lighting.ts b/client/workers/lighting.ts index 87f47b3..2ba97bd 100644 --- a/client/workers/lighting.ts +++ b/client/workers/lighting.ts @@ -6,16 +6,18 @@ // something that isn't fully clear, block light starts at blocks that give off light. both spread to // neighbors losing max(1, the neighbor's opacity) per step. // -// minecraft stores light and updates it as blocks change. here it's worked out from scratch for the -// 3x3 chunks around the chunk being meshed, which gives the same result: light reaches at most 15 -// blocks, so nothing outside those chunks can light the middle one or its border +// minecraft stores light and updates it as blocks change. here it's worked out from scratch around the sections being +// meshed: the 3x3 chunks around theirs, from the section below them to the one above. that gives the same result, since +// light reaches at most 15 blocks, so nothing outside can light them or their border. the only light that comes from +// further is the sky's straight down, which starts where each column's sky height says (see column_heights in +// common/section.ts) instead of being followed down from the top. // -// y in a region counts from the bottom of the world, 0 is the dimension's min_y. in a dimension without sky light -// there's only block light +// y in a region counts from its bottom, which is a section's. in a dimension without sky light there's only block +// light import { AIR, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; import type { Section } from "@/common/section.ts"; -import type { WorldShapeJson } from "@/common/world_shape.ts"; +import { SECTION_HEIGHT, type WorldShapeJson } from "@/common/world_shape.ts"; export const REGION_SIZE = CHUNK_SIZE * 3; export const REGION_LAYER = REGION_SIZE * REGION_SIZE; @@ -29,34 +31,42 @@ export interface LightTables { } export class LightRegion { - // the dimension's, in blocks - readonly height: number; + // in blocks, of the sections last filled in + height = 0; readonly sky_light: boolean; // block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x blocks: Uint16Array; sky: Uint8Array; block_light: Uint8Array; - // the lowest y that still sees the sky, per column + // the lowest y that still sees the sky, per column. the region's height when that's above it #heights = new Int32Array(REGION_LAYER); #queue = new Int32Array(1 << 18); #queue_length = 0; + // room for the dimension's whole height constructor(shape: WorldShapeJson) { - this.height = shape.max_y - shape.min_y; this.sky_light = shape.sky_light; - const volume = REGION_LAYER * this.height; + const volume = REGION_LAYER * (shape.max_y - shape.min_y); this.blocks = new Uint16Array(volume); this.sky = new Uint8Array(volume); this.block_light = new Uint8Array(volume); } - // the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z, by section. missing ones are - // void - fill(chunks: (Section[] | null)[]) { + // the same sections of the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing + // chunks are void. sky is each chunk's sky height by column (see column_heights), and bottom the y of the region's + // bottom in the world + fill(chunks: (Section[] | null)[], sky: (ArrayLike | null)[], bottom: number) { + this.height = chunks[4]!.length * SECTION_HEIGHT; for (let i = 0; i < 9; i++) { const source = chunks[i]; const origin = Math.floor(i / 3) * CHUNK_SIZE * REGION_SIZE + (i % 3) * CHUNK_SIZE; + for (let z = 0; z < CHUNK_SIZE; z++) { + for (let x = 0; x < CHUNK_SIZE; x++) { + const height = sky[i] ? sky[i]![z * CHUNK_SIZE + x] - bottom : this.height; + this.#heights[origin + z * REGION_SIZE + x] = Math.min(Math.max(height, 0), this.height); + } + } for (let y = 0; y < this.height; y++) { const section = source?.[y >> 4]; for (let z = 0; z < CHUNK_SIZE; z++) { @@ -80,19 +90,14 @@ export class LightRegion { } #compute_sky({ opacity }: LightTables) { - const { blocks, sky, height: world_height } = this; - sky.fill(0); + const { sky, height: region_height } = this; + sky.fill(0, 0, REGION_LAYER * region_height); this.#queue_length = 0; if (!this.sky_light) return; - // straight down from the top, until something isn't fully clear + // straight down from the top, to the sky height for (let column = 0; column < REGION_LAYER; column++) { - let y = world_height - 1; - while (y >= 0 && opacity[blocks[y * REGION_LAYER + column]] === 0) { - sky[y * REGION_LAYER + column] = 15; - y--; - } - this.#heights[column] = y + 1; + for (let y = this.#heights[column]; y < region_height; y++) sky[y * REGION_LAYER + column] = 15; } // only the lit cells next to a darker one can spread: the bottom of each column's sunlight, @@ -108,7 +113,7 @@ export class LightRegion { if (z < REGION_SIZE - 1) { highest_neighbor = Math.max(highest_neighbor, this.#heights[column + REGION_SIZE]); } - const top = Math.min(world_height - 1, Math.max(height, highest_neighbor - 1)); + const top = Math.min(region_height - 1, Math.max(height, highest_neighbor - 1)); for (let y = height; y <= top; y++) { this.#push(y * REGION_LAYER + column); } @@ -120,10 +125,11 @@ export class LightRegion { #compute_block_light({ opacity, emission }: LightTables) { const { blocks, block_light } = this; - block_light.fill(0); + const volume = REGION_LAYER * this.height; + block_light.fill(0, 0, volume); this.#queue_length = 0; - for (let i = 0; i < blocks.length; i++) { + for (let i = 0; i < volume; i++) { const level = emission[blocks[i]]; if (level > 0) { block_light[i] = level; diff --git a/common/everything_registry.ts b/common/everything_registry.ts index 0e2976a..7e4af76 100644 --- a/common/everything_registry.ts +++ b/common/everything_registry.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import type { TintColor } from "./worldgen/biome_colors.ts"; +import { ID_MASK } from "./constants.ts"; import type { ItemStack } from "./inventory.ts"; import type { BlockPart, BlockVariant } from "./block_models.ts"; @@ -101,6 +102,18 @@ export function block_light_emission(block: BlockRegistry | undefined): number { return block?.light_emission ?? 0; } +// every block's light opacity and emission by numeric id, for lighting a lot of blocks at once. blocks is the blocks +// registry, with its gaps +export function light_tables(blocks: readonly (BlockRegistry | undefined)[]) { + const opacity = new Uint8Array(ID_MASK + 1); + const emission = new Uint8Array(ID_MASK + 1); + blocks.forEach((block, nid) => { + opacity[nid] = block_light_opacity(block); + emission[nid] = block_light_emission(block); + }); + return { opacity, emission }; +} + export interface BlockRegistry { id: string; // what players see, like "Iron Ore". made from the id when not set, see display_name in common/utils.ts diff --git a/server/game/world.ts b/server/game/world.ts index d05a1fd..ab81aa8 100644 --- a/server/game/world.ts +++ b/server/game/world.ts @@ -4,12 +4,7 @@ import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts"; import { ChunkColumn, column_heights, Section, SECTION_VOLUME } from "@/common/section.ts"; -import { - block_light_emission, - block_light_opacity, - BlockRegistry, - EverythingRegistry, -} from "@/common/everything_registry.ts"; +import { BlockRegistry, EverythingRegistry, light_tables } from "@/common/everything_registry.ts"; import { generate_raw_chunk, RawChunk, WorldgenSetup } from "@/common/generation.ts"; import { AIR_ID } from "@/common/protocol.ts"; import { block_value, chunk_key } from "@/common/utils.ts"; @@ -165,12 +160,9 @@ export class ServerWorld { const { block_ids, default_values } = block_numbering(); Object.assign(this.block_ids, block_ids); this.default_values.push(...default_values); - this.#opacity = new Uint8Array(ID_MASK + 1); - this.#emission = new Uint8Array(ID_MASK + 1); - EverythingRegistry.get_registry("blocks").forEach((block, nid) => { - this.#opacity[nid] = block_light_opacity(block); - this.#emission[nid] = block_light_emission(block); - }); + const tables = light_tables(EverythingRegistry.get_registry("blocks")); + this.#opacity = tables.opacity; + this.#emission = tables.emission; } #spawn: { x: number; y: number; z: number } | undefined; diff --git a/tests/benchmark_test.ts b/tests/benchmark_test.ts index 958a549..830cacc 100644 --- a/tests/benchmark_test.ts +++ b/tests/benchmark_test.ts @@ -22,7 +22,7 @@ Deno.test("the lows are the fps of the slowest frames", () => { }); Deno.test("a report reads back from what was copied", () => { - const scene = { draw_calls: 10, quads: 1000, chunks_in_view: 4, entities_in_view: 0 }; + const scene = { draw_calls: 10, quads: 1000, sections_in_view: 4, entities_in_view: 0 }; const report: BenchmarkReport = { version: 1, date: "2026-01-01T00:00:00.000Z", diff --git a/tests/client_level_test.ts b/tests/client_level_test.ts new file mode 100644 index 0000000..7a8ecd6 --- /dev/null +++ b/tests/client_level_test.ts @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the client meshes a section at a time, and a block changing only meshes again the sections it can change the look +// or the light of, see ClientLevel's #block_changed +import { assertEquals } from "@std/assert"; +import { ClientLevel } from "@/client/level/client_level.ts"; +import { AssetManager } from "@/client/assets.ts"; +import { Camera } from "@/client/camera.ts"; +import type { ToChunkWorker } from "@/client/workers/chunk_messages.ts"; +import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; +import { CHUNK_AREA } from "@/common/constants.ts"; +import { ChunkColumn } from "@/common/section.ts"; +import { DEFAULT_SHAPE } from "@/common/world_shape.ts"; +import { test_game } from "./helpers.ts"; + +const GROUND_TOP = 63; +const ROOF = 200; + +// a level of 5x5 chunks of stone up to GROUND_TOP, with a stone roof at ROOF over chunk 0, 0, all meshed. what it asks +// its chunk workers is kept in requests instead of being sent +async function meshed_level() { + await test_game("mods"); + AssetManager.instance.assets["cubi:textures"] = { width: 16, height: 16 }; + AssetManager.instance.assets["cubi:textures_info"] = {}; + const requests: Extract[] = []; + const real = globalThis.Worker; + globalThis.Worker = class { + postMessage(message: ToChunkWorker) { + if (message.type === "mesh") requests.push(message); + } + terminate() {} + } as unknown as typeof Worker; + const blocks = EverythingRegistry.get_registry("blocks"); + let level: ClientLevel; + try { + level = new ClientLevel(Array.from(blocks, (block) => block?.id), DEFAULT_SHAPE, 2); + } finally { + globalThis.Worker = real; + } + + const stone = EverythingRegistry.get_id("blocks", "bworld:stone")!; + for (let x = -2; x <= 2; x++) { + for (let z = -2; z <= 2; z++) { + const flat = new Uint32Array(DEFAULT_SHAPE.volume).fill(stone, 0, (GROUND_TOP + 1) * CHUNK_AREA); + if (x === 0 && z === 0) flat.fill(stone, ROOF * CHUNK_AREA, (ROOF + 1) * CHUNK_AREA); + const biomes = new Array(CHUNK_AREA).fill("bworld:plains"); + level.set_chunk(ChunkColumn.from_flat(x, z, DEFAULT_SHAPE, flat, biomes)); + } + } + const camera = new Camera(); + level.request_meshes(camera); + requests.length = 0; + + // the sections asked for since the last call, as "chunk x,chunk z: indexes" + const remeshed = () => { + level.request_meshes(camera); + const asked = requests.map(({ chunk_x, chunk_z, sections }) => + `${chunk_x},${chunk_z}: ${sections.map(({ index }) => index).sort((a, b) => a - b).join(" ")}` + ).sort(); + requests.length = 0; + return asked; + }; + return { level, requests, remeshed }; +} + +Deno.test("a block that doesn't change the light remeshes its section, and the ones whose border it's on", async () => { + const { level, remeshed } = await meshed_level(); + level.add_block({ id: "bworld:cobblestone", x: 8, y: 40, z: 8 }); + assertEquals(remeshed(), ["0,0: 2"]); + + // at x 0, z 15 and y 32 of its chunk, so next to the chunks to -x and +z and the section below + level.add_block({ id: "bworld:cobblestone", x: 0, y: 32, z: 15 }); + assertEquals(remeshed(), ["-1,0: 1 2", "-1,1: 1 2", "0,0: 1 2", "0,1: 1 2"]); +}); + +Deno.test("a request sends the sections around the ones it's for, and their columns' sky heights", async () => { + const { level, requests } = await meshed_level(); + level.add_block({ id: "bworld:cobblestone", x: 8, y: 40, z: 8 }); + level.request_meshes(new Camera()); + const [request] = requests; + assertEquals(request.first, 1); + assertEquals(request.chunks.map((chunk) => chunk?.length), new Array(9).fill(3)); + assertEquals(request.sky[4]![8 * 16 + 8], ROOF + 1); + assertEquals(request.sky[0]![0], GROUND_TOP + 1); +}); + +Deno.test("opening a hole to the sky remeshes the columns around it from the old sky height to the new", async () => { + const { level, remeshed } = await meshed_level(); + level.break_block(8, ROOF, 8); + // the light reaches 15 blocks past where it changes, and a section's faces are lit from the block past them + const from = (GROUND_TOP + 1 - 16) >> 4; + const to = (ROOF + 1 + 16) >> 4; + const sections = Array.from({ length: to - from + 1 }, (_, i) => from + i).join(" "); + const chunks = []; + for (let x = -1; x <= 1; x++) { + for (let z = -1; z <= 1; z++) chunks.push(`${x},${z}: ${sections}`); + } + assertEquals(remeshed(), chunks.sort()); + + // a light block under the roof changes the light around it, in the sections next to its own + level.add_block({ id: "bworld:light", x: 4, y: 100, z: 4 }); + assertEquals(remeshed(), chunks.map((chunk) => chunk.replace(sections, "5 6 7"))); +}); diff --git a/tests/entity_light_test.ts b/tests/entity_light_test.ts index ca8b7c7..8aff0ac 100644 --- a/tests/entity_light_test.ts +++ b/tests/entity_light_test.ts @@ -7,8 +7,7 @@ import { assertEquals } from "@std/assert"; import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; import { DEFAULT_SHAPE, type WorldShapeJson } from "@/common/world_shape.ts"; -import { section_data, test_game } from "./helpers.ts"; -import type { SectionLight } from "@/client/workers/chunk_messages.ts"; +import { chunk_worker, mesh_column, test_game } from "./helpers.ts"; import { section_index } from "@/common/section.ts"; // the middle chunk's light, with a stone roof at y 20 over x 0-7 and a light block at 12, 5, 8. y counts from the @@ -18,17 +17,7 @@ async function mesh_light(shape: WorldShapeJson = DEFAULT_SHAPE) { await test_game("mods"); const blocks = EverythingRegistry.get_registry("blocks"); const nid = (id: string) => blocks.findIndex((b) => b?.id === id); - const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); - worker.postMessage({ - type: "init", - shape, - blocks_registry: JSON.parse(JSON.stringify(blocks)), - models: {}, - textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } }, - image: { width: 1024, height: 1024 }, - visuals: [], - }); - + const worker = chunk_worker(shape); const chunk = new Uint32Array(volume); const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x; for (let x = 0; x < 8; x++) { @@ -38,18 +27,7 @@ async function mesh_light(shape: WorldShapeJson = DEFAULT_SHAPE) { const empty = () => new Uint32Array(volume); const chunks = [empty(), empty(), empty(), empty(), chunk, empty(), empty(), empty(), empty()]; - const meshed = await new Promise<{ light: SectionLight[]; max_y: number }>((resolve) => { - worker.onmessage = (e) => resolve(e.data); - worker.postMessage({ - type: "mesh", - chunk_x: 0, - chunk_z: 0, - version: 1, - chunks: chunks.map(section_data), - biome_colors: chunks.map(() => null), - camera: [0, 0, 0], - }); - }); + const meshed = await mesh_column(worker, shape, chunks); worker.terminate(); const light = (x: number, y: number, z: number) => { const section = meshed.light[y >> 4]; @@ -85,3 +63,33 @@ Deno.test("a dimension that starts below 0 is lit the same, and meshed where its assertEquals(light(4, 10, 8).sky, 11); assertEquals(max_y, -64 + 21, "the top of the roof"); }); + +Deno.test("a section meshed on its own is lit and drawn the same as when its whole column is", async () => { + await test_game("mods"); + const blocks = EverythingRegistry.get_registry("blocks"); + const nid = (id: string) => blocks.findIndex((b) => b?.id === id); + const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x; + // ground up to 40 everywhere, and in the middle chunk a roof far above it over x 0-7, which shades sections well + // below it, and a light just under a section's top, which lights the one above + const ground = () => new Uint32Array(DEFAULT_SHAPE.volume).fill(nid("bworld:stone"), 0, at(0, 41, 0)); + const chunks = Array.from({ length: 9 }, ground); + for (let x = 0; x < 8; x++) { + for (let z = 0; z < CHUNK_SIZE; z++) chunks[4][at(x, 200, z)] = nid("bworld:stone"); + } + chunks[4][at(12, 47, 8)] = nid("bworld:light"); + chunks[4][at(3, 41, 3)] = nid("bworld:glass"); + + const worker = chunk_worker(DEFAULT_SHAPE); + const whole = await mesh_column(worker, DEFAULT_SHAPE, chunks); + for (const [index, expected] of whole.sections.entries()) { + const [alone] = (await mesh_column(worker, DEFAULT_SHAPE, chunks, { sections: [index] })).sections; + assertEquals(alone.light, expected.light, `section ${index}'s light`); + for (const layer of ["solid", "cutout", "translucent"] as const) { + assertEquals(alone[layer].vertices, expected[layer].vertices, `section ${index}'s ${layer} quads`); + } + } + worker.terminate(); + // the roof's shade and the light are in the sections looked at + assertEquals(typeof whole.light[2], "object"); + assertEquals(typeof whole.light[3], "object"); +}); diff --git a/tests/fluid_test.ts b/tests/fluid_test.ts index 86bb5a4..9c2c111 100644 --- a/tests/fluid_test.ts +++ b/tests/fluid_test.ts @@ -17,7 +17,7 @@ import { DEFAULT_SHAPE } from "@/common/world_shape.ts"; import { get_state_value, set_state_value } from "@/common/utils.ts"; import { cell_index, corner_height, fluid_quads, type FluidCell } from "@/client/workers/fluid_mesh.ts"; import { TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; -import { section_data, test_game } from "./helpers.ts"; +import { chunk_worker, mesh_column, test_game } from "./helpers.ts"; const OIL: BlockJson = { id: "oily:oil", @@ -170,35 +170,13 @@ async function mesh(blocks: [number, number, number, string, number?][]) { const registry = EverythingRegistry.get_registry("blocks"); const ids: Record = {}; registry.forEach((b, nid) => ids[b.id] = nid); - const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); - worker.postMessage({ - type: "init", - shape: DEFAULT_SHAPE, - // with the registry's gaps, like the client sends it - blocks_registry: registry.map((block) => JSON.parse(JSON.stringify(block))), - models: {}, - textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } }, - image: { width: 1024, height: 1024 }, - visuals: [], - }); + const worker = chunk_worker(DEFAULT_SHAPE); const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume)); for (const [x, y, z, id, level] of blocks) { const chunk = x < 0 ? chunks[3] : chunks[4]; chunk[y * CHUNK_AREA + z * CHUNK_SIZE + ((x + CHUNK_SIZE) % CHUNK_SIZE)] = ids[id] | ((level ?? 0) << 16); } - // deno-lint-ignore no-explicit-any - const meshed = await new Promise((resolve) => { - worker.onmessage = (e) => resolve(e.data); - worker.postMessage({ - type: "mesh", - chunk_x: 0, - chunk_z: 0, - version: 1, - chunks: chunks.map(section_data), - biome_colors: chunks.map(() => null), - camera: [0, 0, 0], - }); - }); + const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks); worker.terminate(); const f32 = new Float32Array(meshed.translucent.vertices.buffer); const quads: number[][][] = []; diff --git a/tests/helpers.ts b/tests/helpers.ts index 231a084..fc52822 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -2,7 +2,12 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import { resolve, toFileUrl } from "@std/path"; -import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; +import { + type BlockRegistry, + EverythingRegistry, + light_tables, + type RenderLayer, +} from "@/common/everything_registry.ts"; import { load_and_check, load_order } from "@/tools/check_mods.ts"; import { mod_data } from "@/common/mod_check.ts"; import type { ServerModSource } from "@/server/game/load_mods.ts"; @@ -11,8 +16,11 @@ import { start_game } from "@/server/game/load_mods.ts"; import { apply_config } from "@/server/load_mods.ts"; import { AIR_ID, PROTOCOL_VERSION } from "@/common/protocol.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts"; -import { CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; -import { Section, section_index, SECTION_VOLUME, type SectionData } from "@/common/section.ts"; +import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; +import { ChunkColumn, column_heights, section_index, SECTION_VOLUME } from "@/common/section.ts"; +import { WorldShape, type WorldShapeJson } from "@/common/world_shape.ts"; +import type { LayerMesh, SectionMesh, ToChunkWorker } from "@/client/workers/chunk_messages.ts"; +import type { ModelJson } from "@/common/block_models.ts"; import type { SavedChunk, SavedChunks, WorldSave } from "@/server/game/saves.ts"; import { FluidRules } from "@/common/fluids.ts"; import { BlockRules } from "@/common/block_rules.ts"; @@ -166,12 +174,95 @@ export function sent_block( return [join.blocks[value & ID_MASK], value >>> 16]; } -// a chunk's blocks in one array, y from the bottom of the world then z then x, as the sections a mesh request sends -export function section_data(blocks: Uint32Array): SectionData[] { - return Array.from( - { length: blocks.length / SECTION_VOLUME }, - (_, i) => Section.of(blocks.subarray(i * SECTION_VOLUME, (i + 1) * SECTION_VOLUME)).data, +// a chunk worker set up the way the client sets one up, with the loaded mods' blocks. models are the mods' block models +// and visuals the blocks with them, see ToChunkWorker's init +export function chunk_worker( + shape: WorldShapeJson, + models: Record = {}, + visuals: [number, boolean][] = [], +): Worker { + const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); + worker.postMessage({ + type: "init", + shape, + // with the registry's gaps, like the client sends it + blocks_registry: EverythingRegistry.get_registry("blocks").map((block) => + JSON.parse(JSON.stringify(block)) + ), + models, + textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } }, + image: { width: 1024, height: 1024 }, + visuals, + }); + return worker; +} + +// the sections of the middle one of 3x3 chunks meshed by a chunk worker, asked for the way the client asks: all of +// them, or the indexes in options.sections. the chunks are each block's value in one array, y from the bottom of the +// world then z then x, null where there's none. what comes back is each section's mesh, and all of them put together: +// their layers' quads one after another, their light, their visuals with indexes in the whole chunk (like an array's) +// and the bounds of them all +export async function mesh_column( + worker: Worker, + shape: WorldShapeJson, + chunks: (Uint32Array | null)[], + options: { + chunk_x?: number; + chunk_z?: number; + biome_colors?: (Uint32Array | null)[]; + camera?: number[]; + sections?: number[]; + } = {}, +) { + const { opacity } = light_tables(EverythingRegistry.get_registry("blocks")); + const columns = chunks.map((blocks) => + blocks && ChunkColumn.from_flat(0, 0, new WorldShape(shape), blocks, new Array(CHUNK_AREA).fill("")) ); + const count = columns[4]!.sections.length; + const indexes = options.sections ?? Array.from({ length: count }, (_, index) => index); + // with the section below and above them, like ClientLevel.request_meshes + const first = Math.max(0, Math.min(...indexes) - 1); + const end = Math.min(count, Math.max(...indexes) + 2); + const message: ToChunkWorker = { + type: "mesh", + chunk_x: options.chunk_x ?? 0, + chunk_z: options.chunk_z ?? 0, + sections: indexes.map((index) => ({ index, version: 1 })), + first, + chunks: columns.map((column) => column?.sections.slice(first, end).map((section) => section.data) ?? null), + sky: columns.map((column) => column && column_heights(column, opacity).slice(CHUNK_AREA)), + biome_colors: options.biome_colors ?? chunks.map(() => null), + camera: options.camera ?? [0, 0, 0], + }; + const sections = await new Promise((resolve) => { + worker.onmessage = (e) => resolve(e.data.sections); + worker.postMessage(message); + }); + + const layer = (name: RenderLayer): LayerMesh => { + const meshes = sections.map((section) => section[name]); + const vertices = new Uint8Array(meshes.reduce((sum, mesh) => sum + mesh.vertices.length, 0)); + let at = 0; + for (const mesh of meshes) { + vertices.set(mesh.vertices, at); + at += mesh.vertices.length; + } + return { vertices, quad_count: meshes.reduce((sum, mesh) => sum + mesh.quad_count, 0) }; + }; + return { + sections, + solid: layer("solid"), + cutout: layer("cutout"), + translucent: layer("translucent"), + light: sections.map((section) => section.light), + visuals: Uint32Array.from( + sections.flatMap(({ index, visuals }) => + [...visuals].map((value, i) => i % 2 === 0 ? index * SECTION_VOLUME + value : value) + ), + ), + min_y: Math.min(...sections.map((section) => section.min_y)), + max_y: Math.max(...sections.map((section) => section.max_y)), + }; } // a stone floor at y 99 from -radius to radius on x and z, high above the terrain, for players to stand on at y 100 diff --git a/tests/juice_test.ts b/tests/juice_test.ts index 761f3fd..e0050fd 100644 --- a/tests/juice_test.ts +++ b/tests/juice_test.ts @@ -6,7 +6,7 @@ import { assert, assertEquals, assertRejects } from "@std/assert"; import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import type { FluidJson } from "@/common/mod_data.ts"; import type { ClientContext, Instances, Visual, VisualBlock } from "@/common/mod_api/client.ts"; -import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; +import { section_index } from "@/common/section.ts"; import { block_value, display_name } from "@/common/utils.ts"; import { sell_value } from "@/common/inventory.ts"; import { block_visuals, Visuals } from "@/client/rendering/visuals.ts"; @@ -295,7 +295,7 @@ async function drawn_juicer() { block_visuals.set(juicer, { mod: "bworld", replaces_model: false, create: made.get("bworld:juicer")! }); const data: Record = {}; const visuals = new Visuals({ get_block_data: () => data, get_light: () => 0 }); - visuals.meshed(0, 0, 0, Uint32Array.of(100 * CHUNK_AREA + 1 * CHUNK_SIZE + 1, block_value(juicer, 0))); + visuals.meshed(0, 0, 96, Uint32Array.of(section_index(1, 100, 1), block_value(juicer, 0))); const set = (field: string, value: unknown) => { data[field] = value; visuals.data_changed(1, 100, 1); diff --git a/tests/natural_spawn_test.ts b/tests/natural_spawn_test.ts index 869d532..640eaee 100644 --- a/tests/natural_spawn_test.ts +++ b/tests/natural_spawn_test.ts @@ -4,14 +4,10 @@ // monsters spawning on their own in the dark near players, like undergarden's rotwalkers, see natural_spawner.ts and // mods/undergarden/worldgen/spawns.json import { assert, assertEquals } from "@std/assert"; -import { CHUNK_SIZE } from "@/common/constants.ts"; +import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts"; -import { - block_light_emission, - block_light_opacity, - BlockRegistry, - EverythingRegistry, -} from "@/common/everything_registry.ts"; +import { BlockRegistry, EverythingRegistry, light_tables } from "@/common/everything_registry.ts"; +import { ChunkColumn, column_heights } from "@/common/section.ts"; import { LightRegion, REGION_LAYER, REGION_SIZE, REGION_VOID } from "@/client/workers/lighting.ts"; import { create_entity } from "@/server/game/entity/entity_types.ts"; import { Mob } from "@/server/game/entity/mob.ts"; @@ -78,22 +74,21 @@ Deno.test("the server's light is the same as what clients work out", async () => world.set_block(x0 + 3, FLOOR + 1, x0 + 3, "bworld:light"); world.set_block(x0 + 12, ROOF, x0 + 12, "cubi:air"); - const blocks = EverythingRegistry.get_registry("blocks"); - const opacity = new Uint8Array(REGION_VOID + 1); - const emission = new Uint8Array(REGION_VOID + 1); - blocks.forEach((block, nid) => { - opacity[nid] = block_light_opacity(block); - emission[nid] = block_light_emission(block); - }); + // the 3x3 chunks lit whole, like the client lights sections + const { opacity, emission } = light_tables(EverythingRegistry.get_registry("blocks")); opacity[REGION_VOID] = 15; const region = new LightRegion(world.shape); const chunks = []; + const sky = []; for (let dz = -1; dz <= 1; dz++) { for (let dx = -1; dx <= 1; dx++) { - chunks.push(decode_level_chunk(world.level_chunk(CHUNK + dx, CHUNK + dz)).sections); + const { sections, biomes } = decode_level_chunk(world.level_chunk(CHUNK + dx, CHUNK + dz)); + chunks.push(sections); + const column = new ChunkColumn(CHUNK + dx, CHUNK + dz, world.shape, sections, biomes); + sky.push(column_heights(column, opacity).slice(CHUNK_AREA)); } } - region.fill(chunks); + region.fill(chunks, sky, world.shape.min_y); region.compute({ opacity, emission }); const check = (x: number, y: number, z: number) => { diff --git a/tests/terrain_culling_test.ts b/tests/terrain_culling_test.ts index dfc9ecd..b98d281 100644 --- a/tests/terrain_culling_test.ts +++ b/tests/terrain_culling_test.ts @@ -5,13 +5,17 @@ // would have shown import { assert, assertEquals } from "@std/assert"; import { mat4 } from "gl-matrix"; -import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; import { Frustum } from "@/client/rendering/frustum.ts"; import { group_faces_camera } from "@/client/rendering/level_renderer.ts"; -import { FACE_GROUPS, type LayerMesh, TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; +import { + FACE_GROUPS, + type LayerMesh, + type SectionMesh, + TERRAIN_VERTEX_BYTES, +} from "@/client/workers/chunk_messages.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts"; -import type { Section } from "@/common/section.ts"; -import { test_game } from "./helpers.ts"; +import { to_flat } from "@/common/section.ts"; +import { chunk_worker, mesh_column, test_game } from "./helpers.ts"; // the matrix the renderer makes for a camera, see update_camera in client/renderer/core.ts function camera_matrix(x: number, y: number, z: number, yaw: number, pitch: number) { @@ -34,61 +38,25 @@ Deno.test("the frustum keeps what's in front of the camera and drops what's behi assert(!frustum.intersects_box(-8, 60, -1100, 8, 80, -1090), "past the far plane"); }); -// real chunks as the server sends them, meshed the way the client does it +// real chunks as the server sends them, meshed the way the client does it. each section's mesh async function mesh_chunks(radius: number) { const { game } = await test_game("mods", undefined, "culling-seed"); - const blocks = EverythingRegistry.get_registry("blocks"); - const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); - // deno-lint-ignore no-explicit-any - const replies = new Map void>(); - worker.onmessage = (e) => { - const key = `${e.data.type} ${e.data.chunk_x} ${e.data.chunk_z}`; - replies.get(key)?.(e.data); - replies.delete(key); - }; - // deno-lint-ignore no-explicit-any - const ask = (message: any, reply: string) => - // deno-lint-ignore no-explicit-any - new Promise((resolve) => { - replies.set(`${reply} ${message.chunk_x} ${message.chunk_z}`, resolve); - worker.postMessage(message); - }); - worker.postMessage({ - type: "init", - shape: game.world.shape, - blocks_registry: JSON.parse(JSON.stringify(blocks)), - models: {}, - textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } }, - image: { width: 1024, height: 1024 }, - visuals: [], - }); - - const generated = new Map(); + const worker = chunk_worker(game.world.shape); + const generated = new Map(); for (let x = -radius - 1; x <= radius + 1; x++) { for (let z = -radius - 1; z <= radius + 1; z++) { - generated.set(`${x},${z}`, decode_level_chunk(game.world.level_chunk(x, z)).sections); + generated.set(`${x},${z}`, to_flat(decode_level_chunk(game.world.level_chunk(x, z)).sections)); } } - const meshes = []; + const meshes: SectionMesh[] = []; for (let x = -radius; x <= radius; x++) { for (let z = -radius; z <= radius; z++) { const chunks = []; for (let dz = -1; dz <= 1; dz++) { - for (let dx = -1; dx <= 1; dx++) { - chunks.push(generated.get(`${x + dx},${z + dz}`)!.map((section) => section.data)); - } + for (let dx = -1; dx <= 1; dx++) chunks.push(generated.get(`${x + dx},${z + dz}`)!); } - meshes.push( - await ask({ - type: "mesh", - chunk_x: x, - chunk_z: z, - version: 1, - chunks, - biome_colors: chunks.map(() => null), - camera: [0, 0, 0], - }, "meshed"), - ); + const { sections } = await mesh_column(worker, game.world.shape, chunks, { chunk_x: x, chunk_z: z }); + meshes.push(...sections); } } worker.terminate(); diff --git a/tests/tint_test.ts b/tests/tint_test.ts index 345cf0a..183666f 100644 --- a/tests/tint_test.ts +++ b/tests/tint_test.ts @@ -8,8 +8,8 @@ import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; import { DEFAULT_SHAPE } from "@/common/world_shape.ts"; import { generate_raw_chunk } from "@/common/generation.ts"; import { get_biome } from "@/common/worldgen/biomes.ts"; -import { type LayerMesh, TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; -import { section_data, test_game } from "./helpers.ts"; +import { TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; +import { chunk_worker, mesh_column, test_game } from "./helpers.ts"; type Colors = { grass: number; foliage: number; water?: number }; @@ -20,16 +20,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors | const blocks = EverythingRegistry.get_registry("blocks"); const block_ids: Record = {}; blocks.forEach((b, nid) => block_ids[b.id] = nid); - const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); - worker.postMessage({ - type: "init", - shape: DEFAULT_SHAPE, - blocks_registry: JSON.parse(JSON.stringify(blocks)), - models: {}, - textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } }, - image: { width: 1024, height: 1024 }, - visuals: [], - }); + const worker = chunk_worker(DEFAULT_SHAPE); const chunk = new Uint32Array(DEFAULT_SHAPE.volume); chunk[10 * CHUNK_AREA + 8 * CHUNK_SIZE + x] = block_ids[id]; @@ -46,18 +37,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors | colors[4] = biome_colors(middle); if (west) colors[3] = biome_colors(west); - const meshed = await new Promise<{ solid: LayerMesh; cutout: LayerMesh; translucent: LayerMesh }>((resolve) => { - worker.onmessage = (e) => resolve(e.data); - worker.postMessage({ - type: "mesh", - chunk_x: 0, - chunk_z: 0, - version: 1, - chunks: chunks.map(section_data), - biome_colors: colors, - camera: [0, 0, 0], - }); - }); + const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks, { biome_colors: colors }); worker.terminate(); const top: number[][] = []; diff --git a/tests/visuals_test.ts b/tests/visuals_test.ts index 71872e3..0bfb83d 100644 --- a/tests/visuals_test.ts +++ b/tests/visuals_test.ts @@ -5,7 +5,7 @@ // draws their instances, placed and turned by the time import { assert, assertEquals, assertRejects, assertThrows } from "@std/assert"; import { mat4 } from "gl-matrix"; -import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; +import { EverythingRegistry } from "@/common/everything_registry.ts"; import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; import { DEFAULT_SHAPE } from "@/common/world_shape.ts"; import { block_value } from "@/common/utils.ts"; @@ -19,7 +19,8 @@ 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"; -import { copy_dir, section_data, test_game } from "./helpers.ts"; +import { chunk_worker, copy_dir, mesh_column, test_game } from "./helpers.ts"; +import { section_index } from "@/common/section.ts"; const HALF = { textures: { "0": "testmod:shaft" }, @@ -85,34 +86,16 @@ const index_of = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models they replace", async () => { const { nid, value } = await registries(); - const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); - worker.postMessage({ - type: "init", - shape: DEFAULT_SHAPE, - blocks_registry: JSON.parse(JSON.stringify(EverythingRegistry.get_registry("blocks"))), - models: Object.fromEntries(EverythingRegistry.entries("models")), - textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } }, - image: { width: 1024, height: 1024 }, - visuals: [[nid("bworld:stone"), true], [nid("bworld:cobblestone"), false]], - }); + const worker = chunk_worker(DEFAULT_SHAPE, Object.fromEntries(EverythingRegistry.entries("models")), [ + [nid("bworld:stone"), true], + [nid("bworld:cobblestone"), false], + ]); const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume)); const middle = chunks[4]; middle[index_of(1, 64, 1)] = value("bworld:stone"); middle[index_of(4, 64, 1)] = value("bworld:cobblestone"); middle[index_of(7, 64, 1)] = value("bworld:dirt"); - // deno-lint-ignore no-explicit-any - const meshed = await new Promise((resolve) => { - worker.onmessage = (e) => resolve(e.data); - worker.postMessage({ - type: "mesh", - chunk_x: 0, - chunk_z: 0, - version: 1, - chunks: chunks.map(section_data), - biome_colors: chunks.map(() => null), - camera: [0, 0, 0], - }); - }); + const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks); worker.terminate(); assertEquals([...meshed.visuals], [ @@ -155,14 +138,14 @@ Deno.test("a visual is made with its block, told when its client data changes, a }; }, }); - const shaft = (axis: number) => Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", axis)); + const shaft = (axis: number) => Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", axis)); - visuals.meshed(0, 0, 0, shaft(1)); + visuals.meshed(0, 0, 64, 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, 0, shaft(1)); + visuals.meshed(0, 0, 64, shaft(1)); assertEquals(log.splice(0), []); data.speed = 32; @@ -177,15 +160,15 @@ Deno.test("a visual is made with its block, told when its client data changes, a assertEquals(log.splice(0), ["frame 10.5"]); // its states changing makes it again - visuals.meshed(0, 0, 0, shaft(2)); + visuals.meshed(0, 0, 64, shaft(2)); assertEquals(log.splice(0), ["delete 1 64 1", "create testmod:shaft 1 64 1 axis 2"]); 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, 0, new Uint32Array()); + visuals.meshed(0, 0, 64, new Uint32Array()); assertEquals(log.splice(0), ["delete 1 64 1"]); assert(!visuals.has(0, 0)); assertEquals(drawn(visuals), []); - visuals.meshed(0, 0, 0, shaft(1)); + visuals.meshed(0, 0, 64, shaft(1)); visuals.unload(0, 0); assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1", "delete 1 64 1"]); assertEquals(drawn(visuals), []); @@ -216,13 +199,13 @@ Deno.test("a visual that throws is logged and left out, and not made again until const console_error = console.error; console.error = (...args) => errors.push(args); try { - visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1))); - visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1))); + visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 1))); + visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 1))); assertEquals([made, errors.length], [1, 1]); assertEquals(drawn(visuals), []); // an on_frame that throws isn't called again - visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 2))); + visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 2))); for (let frame = 0; frame < 3; frame++) visuals.frame([{ x: 0, z: 0 }], frame); assertEquals([made, errors.length], [3, 2]); } finally { @@ -248,9 +231,9 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl }, }); const shafts = Uint32Array.of( - ...[1, 2, 3].flatMap((x) => [index_of(x, 64, 1), value("testmod:shaft")]), + ...[1, 2, 3].flatMap((x) => [section_index(x, 64, 1), value("testmod:shaft")]), ); - visuals.meshed(0, 0, 0, shafts); + visuals.meshed(0, 0, 64, 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 = () => { @@ -275,13 +258,14 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl // a new light comes with the chunk's mesh light = 0x0f; - visuals.meshed(0, 0, 0, shafts); + visuals.meshed(0, 0, 64, shafts); assertEquals([at(0)[21], at(0)[22]], [0.5 / 16, 15.5 / 16]); assertEquals(sent(), [0, 1]); block_visuals.clear(); }); -// a visual on one shaft, at 1 64 1, that makes what make does +// a visual on one shaft, at 1 64 1, that makes what make does. mesh meshes the section from y 64 with blocks at their +// indexes in it function one_visual(nid: (id: string) => number, value: (id: string) => number, make: (instances: Instances) => void) { const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => 0 }); block_visuals.clear(); @@ -293,8 +277,8 @@ function one_visual(nid: (id: string) => number, value: (id: string) => number, return {}; }, }); - const mesh = (blocks: number[]) => visuals.meshed(0, 0, 0, Uint32Array.from(blocks)); - mesh([index_of(1, 64, 1), value("testmod:shaft")]); + const mesh = (blocks: number[]) => visuals.meshed(0, 0, 64, Uint32Array.from(blocks)); + mesh([section_index(1, 64, 1), value("testmod:shaft")]); return { visuals, mesh }; } @@ -378,7 +362,7 @@ Deno.test("a fluid's box is its texture cut to fit and tinted in its color, a mo box!.delete(); assertEquals(boxes(), []); mesh([]); - mesh([index_of(1, 64, 1), value("testmod:shaft")]); + mesh([section_index(1, 64, 1), value("testmod:shaft")]); assertEquals(boxes().length, 1); visuals.unload(0, 0); assertEquals(boxes(), []);