From ea9329757917927656b1b51a5666828ccc1982a6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:05:51 +0200 Subject: [PATCH 1/2] Report the section arena and device memory in the control status The status reply's renderer block gains the section vertex arena's buffer bytes, the bytes resident sections use in it, and the backend allocator's allocated/reserved device memory (Vulkan), to measure terrain memory. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/control.rs | 7 +++++++ crates/horizon-client/src/gfx.rs | 11 +++++++++++ crates/horizon-client/src/gfx/arena.rs | 4 ++++ 3 files changed, 22 insertions(+) diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 2ab1245cf..2f4708692 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -572,6 +572,9 @@ impl Game<'_> { json!({ "pos": hit.pos, "block": &*self.res.facts.get(state).name }) }); let renderer = self.renderer.as_ref().map(|r| { + let [arena_bytes, section_vertex_bytes] = r.section_vertex_bytes(); + // Device memory by the backend's allocator (Vulkan; absent elsewhere). + let memory = r.device.generate_allocator_report(); json!({ "gpu": r.info.name, "backend": format!("{:?}", r.info.backend), @@ -580,6 +583,10 @@ impl Game<'_> { "drawn_sections": r.drawn_sections, "uploaded_bytes": r.uploaded_bytes, "resident_sections": r.resident_sections(), + "arena_bytes": arena_bytes, + "section_vertex_bytes": section_vertex_bytes, + "gpu_allocated_bytes": memory.as_ref().map(|m| m.total_allocated_bytes), + "gpu_reserved_bytes": memory.as_ref().map(|m| m.total_reserved_bytes), }) }); json!({ diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index dd4965782..78778d45c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -373,6 +373,17 @@ impl Renderer { pub fn resident_sections(&self) -> usize { self.sections.len() } + /// Bytes of the section vertex arena's buffers, and of the vertices + /// resident sections hold in them. + pub fn section_vertex_bytes(&self) -> [u64; 2] { + let stride = std::mem::size_of::() as u64; + let vertices: u64 = self + .sections + .values() + .map(|s| u64::from(s.solid + s.translucent) * 4) + .sum(); + [self.arena.bytes(), vertices * stride] + } } impl Renderer { pub async fn new( diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 1697d6b97..4793dab85 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -84,6 +84,10 @@ impl Arena { fn span(vertices: u64) -> u64 { vertices.max(1).next_multiple_of(GRAIN) } + /// Bytes of every page's buffer. + pub fn bytes(&self) -> u64 { + self.pages.iter().map(|p| p.capacity).sum::() * self.stride + } pub fn buffer(&self, page: u32) -> &wgpu::Buffer { &self.pages[page as usize].buffer } From 840e8ad4a865fd30f87e6a6e643a036327865ff3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:16:12 +0200 Subject: [PATCH 2/2] Give terrain its own 28-byte vertex without a normal Since #52 the shared vertex carried an RGBA8_SNORM face normal for entity.wgsl's directional light, so every section vertex grew from 32 to 36 bytes although vs_terrain never reads it. Vanilla's terrain uses DefaultVertexFormat.BLOCK (position, colour, UV0, UV2: 28 bytes): the face shade is baked into the colour by ModelBlockRenderer and terrain.vsh only multiplies it by the lightmap. Sections now mesh into TerrainVertex: position, UV, the sprite layer as a u16 (bit 15 marks opaque leaves), the two light bytes as a u16 and the RGBA8 colour, 28 bytes. Every value the shader reads is unchanged; entity vertices keep their normal. Co-Authored-By: Claude Opus 5.5 --- .../examples/section_mesh_fixture.rs | 12 ++-- crates/horizon-client/src/gfx.rs | 38 +++++++++--- crates/horizon-client/src/mesher.rs | 60 +++++++++++++------ crates/horizon-client/src/mesher/fluid.rs | 9 +-- crates/horizon-client/src/terrain.wgsl | 10 ++-- 5 files changed, 90 insertions(+), 39 deletions(-) diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index d17c33466..7d4f5547d 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -7,7 +7,7 @@ use horizon_client::{ biome::{BiomeInfo, Biomes, GrassModifier}, blocks::BlockFacts, chunk::{Chunk, Light, MIN_Y, index}, - mesher::{MeshTables, Mesher, OPAQUE_LAYER, Vertex}, + mesher::{MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex}, models, }; use horizon_core::biome::BiomeZoom; @@ -33,7 +33,8 @@ fn argb(color: u32) -> i32 { } /// Horizon keeps sky*16 in the low byte and block*16 above it; vanilla's light /// coords keep block in the low half-word and sky in the high one. -fn light_coords(light: u32) -> i32 { +fn light_coords(light: u16) -> i32 { + let light = u32::from(light); ((light & 0xFF) << 16 | (light >> 8 & 0xFF)) as i32 } /// Scenes cover the 3x3 chunk region around chunk (0, 0). @@ -146,9 +147,12 @@ fn scene( } for quad in vertices { let sprite = names - .get(&(quad[0].layer & !OPAQUE_LAYER)) + .get(&u32::from(quad[0].layer & !OPAQUE_LAYER)) .ok_or("unknown sprite layer")?; - if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) { + if quad + .iter() + .any(|v: &TerrainVertex| v.layer != quad[0].layer) + { return Err("quad mixes sprite layers".into()); } let vertices: Vec = quad diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 78778d45c..6d8e5384d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -5,7 +5,7 @@ use crate::{ Result, environment::Sky, hud::{HudBatch, HudRenderer}, - mesher::{SectionMesh, Vertex}, + mesher::{SectionMesh, TerrainVertex, Vertex}, sprites::SpriteAnimation, }; use glam::{DVec3, Mat4, Vec3, Vec4}; @@ -22,6 +22,9 @@ const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState { }, alpha: wgpu::BlendComponent::REPLACE, }; +/// `TerrainVertex` for `vs_terrain`: position, UV, layer, light, colour. +const TERRAIN_ATTRIBUTES: [wgpu::VertexAttribute; 5] = + wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint16,4=>Uint8x2,3=>Unorm8x4]; /// entity.wgsl after the OverlayTexture constants it reads. fn entity_shader() -> String { @@ -376,7 +379,7 @@ impl Renderer { /// Bytes of the section vertex arena's buffers, and of the vertices /// resident sections hold in them. pub fn section_vertex_bytes(&self) -> [u64; 2] { - let stride = std::mem::size_of::() as u64; + let stride = std::mem::size_of::() as u64; let vertices: u64 = self .sections .values() @@ -547,14 +550,12 @@ impl Renderer { bind_group_layouts: &[Some(&bindings)], ..Default::default() }); - let vertex_attributes = - wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4]; let instance_attributes = wgpu::vertex_attr_array![5=>Float32x4]; let terrain_buffers = [ Some(wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as u64, + array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, - attributes: &vertex_attributes, + attributes: &TERRAIN_ATTRIBUTES, }), Some(wgpu::VertexBufferLayout { array_stride: 16, @@ -1341,7 +1342,11 @@ impl Renderer { usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - let arena = arena::Arena::new(&device, std::mem::size_of::() as u64, 1 << 20); + let arena = arena::Arena::new( + &device, + std::mem::size_of::() as u64, + 1 << 20, + ); let indirect = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section draws"), size: 1024 * 20, @@ -1574,7 +1579,7 @@ impl Renderer { } let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64; let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices); - let stride = std::mem::size_of::() as u64; + let stride = std::mem::size_of::() as u64; for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] { if !part.is_empty() { let bytes: &[u8] = bytemuck::cast_slice(part); @@ -2599,6 +2604,23 @@ mod tests { .unwrap(); } #[test] + fn terrain_attributes_follow_the_terrain_vertex() { + use super::TerrainVertex; + use std::mem::offset_of; + let offsets = super::TERRAIN_ATTRIBUTES.map(|a| (a.shader_location, a.offset as usize)); + assert_eq!( + offsets, + [ + (0, offset_of!(TerrainVertex, pos)), + (1, offset_of!(TerrainVertex, uv)), + (2, offset_of!(TerrainVertex, layer)), + (4, offset_of!(TerrainVertex, light)), + (3, offset_of!(TerrainVertex, color)), + ] + ); + assert_eq!(std::mem::size_of::(), 28); + } + #[test] fn cracks_multiply_instead_of_covering_the_block() { let blend = super::CRUMBLING_BLEND; assert_eq!(blend.color.src_factor, wgpu::BlendFactor::Dst); diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 41c1ca4a0..d2770cc2b 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -22,10 +22,11 @@ use horizon_world::{ }; use std::sync::Arc; +/// An entity, item and effect vertex (the entity pipelines), with a face +/// normal for `entity.wgsl`'s directional light. #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct Vertex { - /// Section-relative position. pub pos: [f32; 3], pub uv: [f32; 2], pub layer: u32, @@ -36,9 +37,26 @@ pub struct Vertex { /// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour. pub normal: [i8; 4], } +/// A section vertex, 28 bytes like vanilla's `DefaultVertexFormat.BLOCK` +/// (position, colour, UV0, UV2) with the sprite's array layer beside the +/// light. Terrain has no normal: `ModelBlockRenderer` bakes the face shade +/// into the colour and `terrain.vsh` only multiplies it by the lightmap. +#[repr(C)] +#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] +pub struct TerrainVertex { + /// Section-relative position. + pub pos: [f32; 3], + pub uv: [f32; 2], + /// Sprite array layer, with `OPAQUE_LAYER` for opaque leaves. + pub layer: u16, + /// Smooth light, 16x fixed point: sky in the low byte, block in the high one. + pub light: u16, + /// RGBA8: tint multiplied by directional shade and ambient occlusion. + pub color: u32, +} pub struct SectionMesh { - pub solid: Vec, - pub translucent: Vec, + pub solid: Vec, + pub translucent: Vec, /// VisGraph: bit `a * 6 + b` is set when faces `a` and `b` (Direction /// order) are connected through non-opaque blocks. pub visibility: u64, @@ -192,11 +210,11 @@ pub struct MeshFacts { pub struct MeshTables { info: Vec, pub visibility: FaceVisibility, - water_still: u32, - water_flow: u32, - water_overlay: u32, - lava_still: u32, - lava_flow: u32, + water_still: u16, + water_flow: u16, + water_overlay: u16, + lava_still: u16, + lava_flow: u16, } fn redstone_color(power: u8) -> u32 { // RedstoneWireBlock.COLORS @@ -212,11 +230,18 @@ impl MeshTables { facts: &BlockFacts, visibility: FaceVisibility, ) -> crate::Result { - let layer = |name: &str| -> crate::Result { + // Terrain vertices keep the sprite layer below `OPAQUE_LAYER`. + let layers = assets.sprite_layers.values().max().map_or(0, |l| l + 1); + if layers > u32::from(OPAQUE_LAYER) { + return Err( + format!("{layers} block sprites, terrain vertices index {OPAQUE_LAYER}").into(), + ); + } + let layer = |name: &str| -> crate::Result { assets .sprite_layers .get(name) - .copied() + .map(|&l| l as u16) .ok_or_else(|| format!("missing fluid sprite {name}").into()) }; let mut covers = std::collections::HashMap::new(); @@ -416,8 +441,8 @@ impl Padded { Self { blocks, light } } } -/// Set on a vertex's sprite layer when its texture alpha must be ignored. -pub const OPAQUE_LAYER: u32 = 1 << 31; +/// Set on a terrain vertex's sprite layer when its texture alpha must be ignored. +pub const OPAQUE_LAYER: u16 = 1 << 15; const UNSET: u32 = u32::MAX; const NO_BIOME: u16 = u16::MAX; /// The `ColorResolver`s `ClientLevel` caches block tints for. @@ -530,8 +555,8 @@ fn pack_rgb([r, g, b]: [u32; 3]) -> u32 { } /// Vanilla light coords (block*16 in the low half, sky*16 in the high half) to /// the vertex layout (sky*16 in bits 0..8, block*16 in bits 8..16). -fn pack_coords(coords: u32) -> u32 { - (coords >> 16 & 0xFF) | (coords & 0xFF) << 8 +fn pack_coords(coords: u32) -> u16 { + ((coords >> 16 & 0xFF) | (coords & 0xFF) << 8) as u16 } pub struct Mesher<'a> { /// CardinalLighting.NETHER: brighter up/down faces. @@ -723,15 +748,14 @@ impl Mesher<'_> { None => [g; 3], }; let p = q.positions[i]; - target.push(Vertex { - normal: [0; 4], + target.push(TerrainVertex { pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]], uv: q.uv[i], // Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout. layer: if !self.cutout_leaves && state.leaves { - face.layer | OPAQUE_LAYER + face.layer as u16 | OPAQUE_LAYER } else { - face.layer + face.layer as u16 }, color: pack_rgb(rgb), light: pack_coords(lighting::with_emission(coords[i], q.light_emission)), diff --git a/crates/horizon-client/src/mesher/fluid.rs b/crates/horizon-client/src/mesher/fluid.rs index a1940bf4d..41b1e200e 100644 --- a/crates/horizon-client/src/mesher/fluid.rs +++ b/crates/horizon-client/src/mesher/fluid.rs @@ -2,7 +2,9 @@ //! occlusion against neighbour shapes, flow-rotated top UVs, the water overlay //! beside glass and leaves, back faces, cardinal shading and max(self, above) //! light. -use super::{Info, MeshTables, Padded, SectionMesh, Vertex, lighting, pack_coords, pack_rgb, pi}; +use super::{ + Info, MeshTables, Padded, SectionMesh, TerrainVertex, lighting, pack_coords, pack_rgb, pi, +}; use horizon_core::{ geometry::{Axis, Direction, VoxelShape, trig}, position::BlockPos, @@ -303,9 +305,8 @@ pub(super) fn tesselate( &mut out.solid }; let mut quad = - |v: [([f32; 3], [f32; 2]); 4], layer: u32, color: u32, light: u32, back: bool| { - let vertex = |(pos, uv): ([f32; 3], [f32; 2])| Vertex { - normal: [0; 4], + |v: [([f32; 3], [f32; 2]); 4], layer: u16, color: u32, light: u16, back: bool| { + let vertex = |(pos, uv): ([f32; 3], [f32; 2])| TerrainVertex { pos, uv, layer, diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index b128fa63f..26e32cb89 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -43,7 +43,7 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4 { } @vertex fn vs_terrain( @location(0) position: vec3, @location(1) uv: vec2, - @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec4, + @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec2, @location(5) origin: vec4) -> TerrainOut { let pos = position + origin.xyz; var out: TerrainOut; @@ -66,13 +66,13 @@ fn apply_fog(color: vec4, spherical: f32, cylindrical: f32) -> vec4 { return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); } @fragment fn fs_solid(in: TerrainOut) -> @location(0) vec4 { - // Bit 31 of the layer marks opaque leaves (forceOpaque): no alpha cutout. - let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color; - if color.a < 0.5 && (in.layer & 0x80000000u) == 0u { discard; } + // Bit 15 of the layer marks opaque leaves (forceOpaque): no alpha cutout. + let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffu)) * in.color; + if color.a < 0.5 && (in.layer & 0x8000u) == 0u { discard; } return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical); } @fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4 { - let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color; + let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffu)) * in.color; if color.a < 0.01 { discard; } return apply_fog(color, in.spherical, in.cylindrical); }