Merge pull request #128 from ludovic111/perf/terrain-vertex-32
Terrain gets its own 28-byte vertex without a normal (was 36)
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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!({
|
||||
|
||||
@@ -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 {
|
||||
@@ -373,6 +376,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::<TerrainVertex>() 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(
|
||||
@@ -536,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,
|
||||
@@ -1330,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,
|
||||
@@ -1563,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);
|
||||
@@ -2588,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);
|
||||
|
||||
@@ -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::<u64>() * self.stride
|
||||
}
|
||||
pub fn buffer(&self, page: u32) -> &wgpu::Buffer {
|
||||
&self.pages[page as usize].buffer
|
||||
}
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user