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 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-14 17:16:12 +02:00
parent ea93297579
commit 840e8ad4a8
5 changed files with 90 additions and 39 deletions
@@ -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<Value> = quad
+30 -8
View File
@@ -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::<Vertex>() as u64;
let stride = std::mem::size_of::<TerrainVertex>() 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::<Vertex>() as u64,
array_stride: std::mem::size_of::<TerrainVertex>() 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::<Vertex>() as u64, 1 << 20);
let arena = arena::Arena::new(
&device,
std::mem::size_of::<TerrainVertex>() 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::<Vertex>() as u64;
let stride = std::mem::size_of::<TerrainVertex>() 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::<TerrainVertex>(), 28);
}
#[test]
fn cracks_multiply_instead_of_covering_the_block() {
let blend = super::CRUMBLING_BLEND;
assert_eq!(blend.color.src_factor, wgpu::BlendFactor::Dst);
+42 -18
View File
@@ -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<Vertex>,
pub translucent: Vec<Vertex>,
pub solid: Vec<TerrainVertex>,
pub translucent: Vec<TerrainVertex>,
/// 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<Info>,
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<Self> {
let layer = |name: &str| -> crate::Result<u32> {
// 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<u16> {
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)),
+5 -4
View File
@@ -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,
+5 -5
View File
@@ -43,7 +43,7 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> {
}
@vertex fn vs_terrain(
@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>,
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>,
@location(5) origin: vec4<f32>) -> TerrainOut {
let pos = position + origin.xyz;
var out: TerrainOut;
@@ -66,13 +66,13 @@ fn apply_fog(color: vec4<f32>, spherical: f32, cylindrical: f32) -> vec4<f32> {
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<f32> {
// 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<f32> {
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);
}