Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.
Rust differential-testinggame-enginegamedevlinuxminecraftminecraft-javareimplementationrustvoxelvulkanwgpu
Metal: each solid pass draws only its own quads
Ludovic Mariede59ab97c568
diff --git a/crates/horizon-client-render/src/gfx.rs b/crates/horizon-client-render/src/gfx.rsindex 15c2895cc..40dc7c5aa 100644--- a/crates/horizon-client-render/src/gfx.rs+++ b/crates/horizon-client-render/src/gfx.rs@@ -6,7 +6,7 @@ use crate::{environment::Sky,graphics::GraphicsApi,hud::{HudBatch, HudRenderer},- mesher::{SectionMesh, Sides, TerrainVertex, Vertex},+ mesher::{Part as Quads, SectionMesh, Sides, TerrainVertex, Vertex},section_mask::SectionMask,sprites::SpriteAnimation,};@@ -2128,7 +2128,7 @@ impl Renderer {true,None,);- // `solid` in two passes over the same draws (terrain.wgsl's `opaque_quad`), for the+ // `solid` in two passes (terrain.wgsl's `opaque_quad`, `mesher::Part`), for the// world pass without a shader pack: no cutout first, through a shader that never// discards, then the rest.let solid_opaque = pipeline(@@ -3408,6 +3408,9 @@ impl Renderer {mapped_at_creation: false,});let flat_wanted = flat::wanted(&adapter, &device);+ // Metal draws solid terrain in two passes (`split_solid`): meshes put all+ // their opaque quads first, so each pass draws its part in a run or two.+ crate::mesher::group_parts(adapter.get_info().backend == wgpu::Backend::Metal);// Readable as storage where flat draws run: a shader pack's terrain program reads them.let arena = arena::Arena::new(&device,@@ -5887,6 +5890,18 @@ impl Renderer {self.phase2_pages.clear();self.solid_runs.clear();self.phase2_runs.clear();+ // On Metal, phase 1 goes the opaque quads of every list, then the cutout+ // ones (`Part`), each solid pass drawing its own: `[..opaque_draws]`,+ // then the rest. A fading list's quads all draw in the cutout pass.+ let split_solid = self.info.backend == wgpu::Backend::Metal;+ let parts = |fading: bool| -> &'static [(u8, Quads)] {+ match (split_solid, fading) {+ (false, _) => &[(0, Quads::All)],+ (true, false) => &[(0, Quads::Opaque), (1, Quads::Cutout)],+ (true, true) => &[(1, Quads::All)],+ }+ };+ let mut opaque_draws = 0;for (i, v) in visible.iter().enumerate() {let s = self.sections.get(v.slot);let first_phase = cull.as_ref().is_none_or(|c| c.first(v.slot));@@ -5895,35 +5910,47 @@ impl Renderer {} else {(&mut self.phase2_draws, &mut self.phase2_pages)};- let start = draws.len();let instances = u32::from(first_phase);let mut indices = 0;- facing_runs_from(&s.sides, eye, mirror_low, v.origin, |first, quads| {- indices += quads * 6;- let base = s.start as u32 + first * 4;- draws.push([quads * 6, instances, 0, base, i as u32]);- pages.push((s.page, None));- });- let runs = if first_phase {- &mut self.solid_runs+ // Phase 2 draws every quad, in both passes.+ let parts = if first_phase {+ parts(fade_code(s, &v.key) != 0)} else {- &mut self.phase2_runs+ &[(0, Quads::All)]};- runs.push(- v.distance,- s.page,- start,- draws.len() - start,- [i as u32, v.slot, indices],- );+ let whole = draws.len();+ for &(group, part) in parts {+ let start = draws.len();+ facing_runs_from(&s.sides, eye, mirror_low, v.origin, part, |first, quads| {+ indices += quads * 6;+ let base = s.start as u32 + first * 4;+ draws.push([quads * 6, instances, 0, base, i as u32]);+ pages.push((s.page, None));+ });+ let len = draws.len() - start;+ if first_phase {+ if group == 0 {+ opaque_draws += len;+ }+ self.solid_runs+ .push_in(group, v.distance, s.page, start, len, [0; 3]);+ }+ }+ if !first_phase {+ self.phase2_runs.push(+ v.distance,+ s.page,+ whole,+ draws.len() - whole,+ [i as u32, v.slot, indices],+ );+ }if let Some(c) = &mut cull&& first_phase{c.drawn(i, v.slot, indices);}}- self.solid_runs- .regroup(&mut self.draws, &mut self.draw_pages, 0);// Phase 2's draws are tested where grouping left them.let runs = self.phase2_runs@@ -5935,23 +5962,33 @@ impl Renderer {}}// Distant terrain tiles are never occlusion tested: phase 1.- let tiles = self.draws.len();- self.solid_runs.clear();for (i, v) in visible_lods.iter().enumerate() {let s = self.lods[&v.key].drawn();- let start = self.draws.len();let instance = (visible.len() + i) as u32;- facing_runs_from(&s.sides, eye, mirror_low, v.origin, |first, quads| {- let base = s.start as u32 + first * 4;- self.draws.push([quads * 6, 1, 0, base, instance]);- self.draw_pages.push((s.page, None));- });- self.solid_runs- .push(v.distance, s.page, start, self.draws.len() - start, [0; 3]);+ for &(group, part) in parts(v.fade != 0) {+ let start = self.draws.len();+ facing_runs_from(&s.sides, eye, mirror_low, v.origin, part, |first, quads| {+ let base = s.start as u32 + first * 4;+ self.draws.push([quads * 6, 1, 0, base, instance]);+ self.draw_pages.push((s.page, None));+ });+ let len = self.draws.len() - start;+ if group == 0 {+ opaque_draws += len;+ }+ self.solid_runs+ .push_in(group, v.distance, s.page, start, len, [0; 3]);+ }}self.solid_runs- .regroup(&mut self.draws, &mut self.draw_pages, tiles);+ .regroup(&mut self.draws, &mut self.draw_pages, 0);let phase1_draws = self.draws.len() as u32;+ // Draws `[..opaque_end]` hold opaque quads, `[cutout_start..phase1_draws]` cutout ones.+ let (opaque_end, cutout_start) = if split_solid {+ (opaque_draws, opaque_draws)+ } else {+ (phase1_draws as usize, 0)+ };self.draws.extend_from_slice(&self.phase2_draws);self.draw_pages.extend_from_slice(&self.phase2_pages);let culling = cull.is_some();@@ -6487,6 +6524,7 @@ impl Renderer {phase1_draws as usize,solid_draws as usize,[shadow_first, shadow_first + shadow_solid].map(|d| d as usize),+ [opaque_end, cutout_start],phase2,visible.iter()@@ -7105,24 +7143,30 @@ impl Renderer {}Some(flat) => {let vertices = |p| self.arena.buffer(p);- // Without a pack, on Metal, each list draws twice: the opaque- // pass, then the cutout one (terrain.wgsl's `opaque_quad`).- let passes: &[&wgpu::RenderPipeline] = match pack_flat {- Some(p) => &[&p.0],- None if split_solid => &[&flat.solid_opaque, &flat.solid_cutout],- None => &[&flat.solid],+ // Without a pack, on Metal, the opaque pass, then the cutout one+ // (terrain.wgsl's `opaque_quad`), each over phase 1's lists with+ // quads for it, and over all of phase 2's.+ let [opaque, cutout] = flat.pass_calls;+ let passes: &[(&wgpu::RenderPipeline, std::ops::Range<usize>)] = match pack_flat+ {+ Some(p) => &[(&p.0, 0..flat.phase1_calls)],+ None if split_solid => &[+ (&flat.solid_opaque, 0..opaque),+ (&flat.solid_cutout, cutout..flat.phase1_calls),+ ],+ None => &[(&flat.solid, 0..flat.phase1_calls)],};- let draw = |pass: &mut wgpu::RenderPass<'_>, calls: &[flat::Call]| {- for &pipeline in passes {+ let draw = |pass: &mut wgpu::RenderPass<'_>| {+ for (pipeline, calls) in passes {pass.set_pipeline(pipeline);- flat.draw(pass, calls, vertices);+ flat.draw(pass, &flat.calls[calls.clone()], vertices);}};match cull {// As below: phase 1, the test, then phase 2's draws// that the test saw, copied after it.Some(cull) => {- draw(&mut pass, &flat.calls[..flat.phase1_calls]);+ draw(&mut pass);if surface.is_some() {drop(pass);pass = plain_pass(&mut encoder);@@ -7144,22 +7188,28 @@ impl Renderer {};pass.set_bind_group(0, &self.group, &[]);pack_frame(&mut pass);- for &pipeline in passes {+ for (pipeline, _) in passes {pass.set_pipeline(pipeline);flat.draw_phase2(&mut pass, vertices);}}- None => draw(&mut pass, &flat.calls[..flat.solid_calls]),+ // Without culling, phase 1 is all the solid calls.+ None => draw(&mut pass),}pass.set_bind_group(0, &self.group, &[]);pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);}None => {- // Without a native material, on Metal, each list draws twice:- // the opaque pass, then the cutout one (terrain.wgsl's `opaque_quad`).- let passes: &[&wgpu::RenderPipeline] = match material {- None if split_solid => &[&self.solid_opaque, &self.solid_cutout],- _ => &[solid_pipeline],+ // Without a native material, on Metal, the opaque pass, then the+ // cutout one (terrain.wgsl's `opaque_quad`), each over phase 1's+ // lists with quads for it, and over all of phase 2's.+ let (opaque, cutout) = (opaque_end as u32, cutout_start as u32);+ let passes: &[(&wgpu::RenderPipeline, std::ops::Range<u32>)] = match material {+ None if split_solid => &[+ (&self.solid_opaque, 0..opaque),+ (&self.solid_cutout, cutout..phase1_draws),+ ],+ _ => &[(solid_pipeline, 0..phase1_draws)],};pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);pass.set_vertex_buffer(1, self.instances.slice(..));@@ -7169,9 +7219,15 @@ impl Renderer {// its pass, or one of their own on Metal), then// what they found in sight, in a pass that loads// both targets (it reads the test's results).- for &pipeline in passes {+ for (pipeline, draws) in passes {pass.set_pipeline(pipeline);- self.draw_sections(&mut pass, &self.indirect, 0, 0, phase1_draws);+ self.draw_sections(+ &mut pass,+ &self.indirect,+ 0,+ draws.start,+ draws.len() as u32,+ );}if surface.is_some() {drop(pass);@@ -7198,7 +7254,7 @@ impl Renderer {wgpu::IndexFormat::Uint32,);pass.set_vertex_buffer(1, self.instances.slice(..));- for &pipeline in passes {+ for (pipeline, _) in passes {pass.set_pipeline(pipeline);self.draw_sections(&mut pass,@@ -7209,10 +7265,17 @@ impl Renderer {);}}+ // Without culling, phase 1 is all the solid draws.None => {- for &pipeline in passes {+ for (pipeline, draws) in passes {pass.set_pipeline(pipeline);- self.draw_sections(&mut pass, &self.indirect, 0, 0, solid_draws);+ self.draw_sections(+ &mut pass,+ &self.indirect,+ 0,+ draws.start,+ draws.len() as u32,+ );}}}@@ -8678,7 +8741,7 @@ fn projection_center(view_proj: Mat4) -> Option<Vec3> {/// face `eye` (`projection_center`), the mesh at the camera-relative/// `origin`; all of them when there is no eye.fn facing_runs(sides: &Sides, eye: Option<Vec3>, origin: [f32; 3], draw: impl FnMut(u32, u32)) {- facing_runs_from(sides, eye, None, origin, draw)+ facing_runs_from(sides, eye, None, origin, Quads::All, draw)}/// `facing_runs` for the eye and, with `low`, every eye straight below it down to that/// camera-relative height (the water mirror's eye).@@ -8687,16 +8750,16 @@ fn facing_runs_from(eye: Option<Vec3>,low: Option<f32>,origin: [f32; 3],- mut draw: impl FnMut(u32, u32),+ part: Quads,+ draw: impl FnMut(u32, u32),) {match eye {Some(eye) => {let eye = eye - Vec3::from(origin);let low = low.map_or(eye.y, |y| (y - origin[1]).min(eye.y));- sides.visible_from(eye.to_array(), low, draw)+ sides.visible_from(eye.to_array(), low, part, draw)}- None if sides.quads() > 0 => draw(0, sides.quads()),- None => {}+ None => sides.every(part, draw),}}fn frustum(m: Mat4) -> [Vec4; 6] {diff --git a/crates/horizon-client-render/src/gfx/flat.rs b/crates/horizon-client-render/src/gfx/flat.rsindex 76f02cb9e..2a87c1129 100644--- a/crates/horizon-client-render/src/gfx/flat.rs+++ b/crates/horizon-client-render/src/gfx/flat.rs@@ -42,6 +42,8 @@ struct Plan {solid_calls: usize,/// Where the shadow camera's solid and translucent calls begin.shadow_calls: [usize; 2],+ /// Where Metal's opaque pass ends and its cutout pass begins in phase 1's calls.+ pass_calls: [usize; 2],total: u64,}const QUADS: u32 = u32::MAX;@@ -107,6 +109,9 @@ pub struct Flat {pub calls: Vec<Call>,pub phase1_calls: usize,pub solid_calls: usize,+ /// Metal's two solid passes over phase 1: the opaque one draws+ /// `calls[..pass_calls[0]]`, the cutout one `calls[pass_calls[1]..phase1_calls]`.+ pub pass_calls: [usize; 2],/// Where a shader pack's shadow camera's solid and translucent calls/// begin (`calls.len()` without them): the camera's translucent calls/// end at the first.@@ -216,7 +221,8 @@ fn buffer(/// apart. A phase 2 range names its draw in phase 2 and its call in phase 2/// instead of a destination: the call's room holds all of its draws. Draws/// from `shadow[0]` (solid) and `shadow[1]` (translucent) on are a shader-/// pack's shadow camera's, with calls of their own.+/// pack's shadow camera's, with calls of their own. Phase 1's draws before+/// `passes[0]` and from `passes[1]` on, the two solid passes' on Metal, too.#[allow(clippy::too_many_arguments)]fn plan(draws: &[[u32; 5]],@@ -224,6 +230,7 @@ fn plan(phase1_draws: usize,solid_draws: usize,shadow: [usize; 2],+ passes: [usize; 2],align: u64,calls: &mut Vec<Call>,ranges: &mut Vec<Range>,@@ -234,6 +241,7 @@ fn plan(segments.clear();let (mut phase1_calls, mut solid_calls) = (None, None);let mut shadow_calls = [None; 2];+ let mut pass_calls = [None; 2];let mut total = 0u64;let mut by_source: Vec<(Source, Vec<Range>)> = Vec::new();for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() {@@ -248,7 +256,13 @@ fn plan(shadow_calls[k].get_or_insert(calls.len());}}- let starts = i == phase1_draws || i == solid_draws || shadow.contains(&i);+ for (k, &from) in passes.iter().enumerate() {+ if i == from {+ pass_calls[k].get_or_insert(calls.len());+ }+ }+ let starts =+ i == phase1_draws || i == solid_draws || shadow.contains(&i) || passes.contains(&i);match calls.last_mut() {Some(last) if last.page == page && !starts => last.count += d[0],_ => calls.push(Call {@@ -283,10 +297,12 @@ fn plan(ranges.resize(padded as usize, [0; 4]);}let solid_calls = solid_calls.unwrap_or(calls.len());+ let phase1_calls = phase1_calls.unwrap_or(calls.len()).min(solid_calls);Plan {- phase1_calls: phase1_calls.unwrap_or(calls.len()).min(solid_calls),+ phase1_calls,solid_calls,shadow_calls: shadow_calls.map(|c| c.unwrap_or(calls.len())),+ pass_calls: pass_calls.map(|c| c.unwrap_or(calls.len()).min(phase1_calls)),total,}}@@ -438,6 +454,7 @@ impl Flat {calls: Vec::new(),phase1_calls: 0,solid_calls: 0,+ pass_calls: [0; 2],shadow_calls: [0; 2],min_sections,range_align: (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16)@@ -519,6 +536,7 @@ impl Flat {phase1_draws: usize,solid_draws: usize,shadow: [usize; 2],+ passes: [usize; 2],phase2: Option<&wgpu::Buffer>,origins: impl Iterator<Item = (u32, [f32; 4])>,sorted_page: impl Fn(u32) -> wgpu::Buffer,@@ -563,6 +581,7 @@ impl Flat {phase1_calls,solid_calls,shadow_calls,+ pass_calls,total,} = plan(draws,@@ -570,6 +589,7 @@ impl Flat {phase1_draws,solid_draws,shadow,+ passes,self.range_align,&mut self.calls,&mut self.range_data,@@ -578,11 +598,13 @@ impl Flat {self.phase1_calls = phase1_calls;self.solid_calls = solid_calls;self.shadow_calls = shadow_calls;+ self.pass_calls = pass_calls;if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {self.calls.clear();self.phase1_calls = 0;self.solid_calls = 0;self.shadow_calls = [0; 2];+ self.pass_calls = [0; 2];return false;}if self.range_data.len() as u64 > self.range_capacity {@@ -870,6 +892,7 @@ mod tests {solid,solid,[draws.len(); 2],+ [draws.len(), 0],4,&mut calls,&mut ranges,@@ -904,6 +927,39 @@ mod tests {assert_eq!(ranges.len(), 12);}+ /// Metal's opaque pass draws the lists before `passes[0]`, its cutout+ /// pass those from `passes[1]`: each bound starts a call of its own,+ /// though its page goes on.+ #[test]+ fn plan_splits_calls_where_the_solid_passes_end_and_begin() {+ let (draws, pages, solid) = sample();+ let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());+ let plan = plan(+ &draws,+ &pages,+ solid,+ solid,+ [draws.len(); 2],+ [3, 1],+ 4,+ &mut calls,+ &mut ranges,+ &mut segments,+ );+ assert_eq!((plan.pass_calls, plan.solid_calls), ([3, 1], 4));+ let call = |page, first, count| Call { page, first, count };+ assert_eq!(+ calls,+ [+ call(0, 0, 18),+ call(0, 18, 12),+ call(1, 30, 6),+ call(0, 36, 24),+ call(0, 60, 18)+ ]+ );+ }+/// A shader pack's shadow draws follow the camera's, in calls of their/// own even from the same page: solid ones, then translucent ones.#[test]@@ -919,6 +975,7 @@ mod tests {solid,solid,[camera, camera + 2],+ [camera, 0],4,&mut calls,&mut ranges,@@ -946,6 +1003,7 @@ mod tests {2,solid,[draws.len(); 2],+ [draws.len(), 0],4,&mut calls,&mut ranges,@@ -957,6 +1015,7 @@ mod tests {phase1_calls: 1,solid_calls: 3,shadow_calls: [4, 4],+ pass_calls: [1, 0],total: 6 * 13});@@ -1061,6 +1120,7 @@ mod tests {phase1,solid,[draws.len(); 2],+ [draws.len(), 0],align,&mut calls,&mut ranges,diff --git a/crates/horizon-client-render/src/gfx/page_runs.rs b/crates/horizon-client-render/src/gfx/page_runs.rsindex 3ada45737..b7b04f14b 100644--- a/crates/horizon-client-render/src/gfx/page_runs.rs+++ b/crates/horizon-client-render/src/gfx/page_runs.rs@@ -16,6 +16,8 @@/// The width of a band, in blocks.const BAND: f64 = 64.0;+/// Where a run's group sits in its sort key, above band and page.+const GROUP_SHIFT: u32 = 62;/// One section's draws: `start..start + len` of the list.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -41,10 +43,24 @@ impl PageRuns {/// The draws `start..start + len` of a section `distance` from the/// camera (squared, as bits) in arena `page`; runs come nearest first.pub fn push(&mut self, distance: u64, page: u32, start: usize, len: usize, tag: [u32; 3]) {+ self.push_in(0, distance, page, start, len, tag);+ }++ /// As `push`, in `group` (0 to 3): regrouping puts each group's runs+ /// before the next group's, then bands and pages within it.+ pub fn push_in(+ &mut self,+ group: u8,+ distance: u64,+ page: u32,+ start: usize,+ len: usize,+ tag: [u32; 3],+ ) {if len > 0 {let band = (f64::from_bits(distance).sqrt() / BAND) as u64;self.runs.push(Run {- key: band << 32 | u64::from(page),+ key: u64::from(group) << GROUP_SHIFT | band << 32 | u64::from(page),start: start as u32,len: len as u32,tag,@@ -61,7 +77,8 @@ impl PageRuns {pages: &mut [(u32, Option<u32>)],base: usize,) -> &[Run] {- let page = |r: &Run| r.key as u32;+ // Group and page: one of each needs no reordering.+ let page = |r: &Run| r.key & (3 << GROUP_SHIFT | u64::from(u32::MAX));if self.runs.windows(2).all(|w| page(&w[0]) == page(&w[1])) {return &self.runs;}@@ -157,6 +174,24 @@ mod tests {assert_eq!(order, [0, 1, 2]);}+ /// Metal's two solid passes draw a prefix and a suffix of the list:+ /// groups come whole and in order, whatever their distance and page.+ #[test]+ fn groups_come_before_bands_and_pages() {+ let mut grouped = PageRuns::default();+ let mut draws: Vec<_> = (0..5).map(|n| [n, 0, 0, 0, 0]).collect();+ let mut pages = vec![(0, None); 5];+ for (n, (group, distance)) in [(2, 10.0), (0, 300.0), (1, 20.0), (0, 30.0), (2, 5.0)]+ .into_iter()+ .enumerate()+ {+ grouped.push_in(group, bits(distance), 0, n, 1, [0; 3]);+ }+ grouped.regroup(&mut draws, &mut pages, 0);+ let order: Vec<_> = draws.iter().map(|d| d[0]).collect();+ assert_eq!(order, [3, 1, 2, 0, 4]);+ }+#[test]fn one_page_and_an_offset_list() {let (mut grouped, mut draws, mut pages) = list(&[(10.0, 3, 2), (90.0, 3, 1)]);diff --git a/crates/horizon-client-render/src/mesher.rs b/crates/horizon-client-render/src/mesher.rsindex 8b1531a71..d3b85c45c 100644--- a/crates/horizon-client-render/src/mesher.rs+++ b/crates/horizon-client-render/src/mesher.rs@@ -25,7 +25,7 @@ use horizon_world::{fluid::{FluidKind, FluidState},registry::BlockStateId,};-pub use sides::Sides;+pub use sides::{Part, Sides, group_parts};use std::sync::Arc;/// An entity, item and effect vertex (the entity pipelines), with a facediff --git a/crates/horizon-client-render/src/mesher/sides.rs b/crates/horizon-client-render/src/mesher/sides.rsindex 4e04ca234..d7a5fbc43 100644--- a/crates/horizon-client-render/src/mesher/sides.rs+++ b/crates/horizon-client-render/src/mesher/sides.rs@@ -16,6 +16,15 @@//! each. Coplanar quads facing one way keep their model order, so an overlay//! on its base still draws in that order. Solid cutout quads are otherwise//! ordered from the outside toward the section interior to reduce overdraw.+//!+//! The opaque quads (`OPAQUE_LAYER`) and the cutout ones of each bucket are+//! apart, so that each of Metal's two solid passes draws only its own quads+//! (`Part`). Where the renderer draws them in two passes (`group_parts`), all+//! the opaque buckets come first, then all the cutout ones, so each part is+//! one or two runs; elsewhere each bucket holds its opaque quads, then its+//! cutout ones, so one pass over all of them draws the runs it drew before.+use std::sync::atomic::{AtomicBool, Ordering};+use super::{OPAQUE_LAYER, TerrainVertex};/// The buckets in mesh order: +X, +Z, other, +Y, -Z, -X, -Y. Seen from@@ -44,12 +53,37 @@ enum Bucket {Other,}-/// Where each bucket of a mesh's solid quads ends, and the planes that tell-/// whether it can face the eye.+/// Whether meshes sorted from now on put every bucket's opaque quads before+/// any cutout ones: set by the renderer when it draws them in two passes.+static GROUPED: AtomicBool = AtomicBool::new(false);++/// Sorts later meshes for two solid passes (`true`) or one.+pub fn group_parts(on: bool) {+ GROUPED.store(on, Ordering::Relaxed);+}++/// The bucket and whether it holds cutout quads of the `n`th part of a+/// mesh, in mesh order.+fn slot(grouped: bool, n: usize) -> (usize, bool) {+ if grouped {+ (n % 7, n >= 7)+ } else {+ (n / 2, n % 2 == 1)+ }+}++/// Where each part of each bucket of a mesh's solid quads ends, and the+/// planes that tell whether a bucket can face the eye.#[derive(Clone, Copy, Debug, Default, PartialEq)]pub struct Sides {- /// The solid quads up to the end of each bucket, in `BUCKETS` order.- ends: [u32; 7],+ /// The solid quads up to the end of each part of each bucket, in mesh+ /// order (`slot`).+ ends: [u32; 14],+ /// Whether all the opaque parts come first (`group_parts`).+ grouped: bool,+ /// Whether opaque and cutout quads are apart; else either part is every+ /// quad.+ split: bool,/// Per bucket facing a positive direction, its lowest plane; facing a/// negative one, its highest (unused for the other bucket).planes: [f32; 7],@@ -59,43 +93,62 @@ impl Sides {/// `quads` solid quads in one bucket drawn from everywhere: for meshes/// that were not sorted.pub fn unsorted(quads: u32) -> Self {- let mut ends = [0; 7];- ends[OTHER..].fill(quads);+ let mut ends = [0; 14];+ ends[OTHER * 2..].fill(quads);Self {ends,+ grouped: false,+ split: false,planes: [0.0; 7],}}/// The number of solid quads the buckets hold.pub fn quads(&self) -> u32 {- self.ends[6]+ self.ends[13]}/// Calls `draw(first, count)` for each run of quads an eye at `eye`/// (relative to the mesh's origin) can see the front of, nearest the/// start first. Empty buckets do not break a run.pub fn visible(&self, eye: [f32; 3], draw: impl FnMut(u32, u32)) {- self.visible_from(eye, eye[1], draw);+ self.visible_from(eye, eye[1], Part::All, draw);}/// `visible` for every eye from `eye` straight down to the height `low`: the camera and- /// its water mirror's eye below the plane, which differ only in y.- pub fn visible_from(&self, eye: [f32; 3], low: f32, mut draw: impl FnMut(u32, u32)) {+ /// its water mirror's eye below the plane, which differ only in y. Only the quads of+ /// `part`, but every quad of a mesh whose parts are not split.+ pub fn visible_from(&self, eye: [f32; 3], low: f32, part: Part, draw: impl FnMut(u32, u32)) {+ let seen = |i: usize| match BUCKETS[i] {+ Bucket::Side(axis, true) => eye[axis] > self.planes[i] - MARGIN,+ Bucket::Side(1, false) => low < self.planes[i] + MARGIN,+ Bucket::Side(axis, false) => eye[axis] < self.planes[i] + MARGIN,+ Bucket::Other => true,+ };+ self.runs(seen, part, draw);+ }++ /// The runs of `part`'s quads facing every way.+ pub fn every(&self, part: Part, draw: impl FnMut(u32, u32)) {+ self.runs(|_| true, part, draw);+ }++ /// Calls `draw` for each run of `part`'s quads in the buckets `seen` keeps.+ fn runs(&self, seen: impl Fn(usize) -> bool, part: Part, mut draw: impl FnMut(u32, u32)) {let mut start = 0;let mut run: Option<u32> = None;- for (i, bucket) in BUCKETS.iter().enumerate() {- let end = self.ends[i];+ for (n, &end) in self.ends.iter().enumerate() {if end == start {continue;}- let seen = match *bucket {- Bucket::Side(axis, true) => eye[axis] > self.planes[i] - MARGIN,- Bucket::Side(1, false) => low < self.planes[i] + MARGIN,- Bucket::Side(axis, false) => eye[axis] < self.planes[i] + MARGIN,- Bucket::Other => true,+ let (bucket, cutout) = slot(self.grouped, n);+ let wanted = match part {+ Part::All => true,+ _ if !self.split => true,+ Part::Opaque => !cutout,+ Part::Cutout => cutout,};- match (seen, run) {+ match (wanted && seen(bucket), run) {(true, None) => run = Some(start),(false, Some(first)) => {draw(first, start - first);@@ -111,6 +164,15 @@ impl Sides {}}+/// The quads `Sides::visible_from` draws: all of them, or those of one of+/// Metal's two solid passes (terrain.wgsl's `opaque_quad`).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Part {+ All,+ Opaque,+ Cutout,+}+/// The bucket of a quad: the axis plane it lies in and the side its/// triangles (corners 0, 1, 2 and 0, 2, 3, as the renderer draws them) face.fn bucket(quad: &[TerrainVertex; 4]) -> usize {@@ -139,18 +201,34 @@ fn bucket(quad: &[TerrainVertex; 4]) -> usize {OTHER}-/// Reorders `solid`'s quads by bucket. Solid cutout quads are also ordered-/// front to back within each axis-facing bucket; stable sorting preserves the-/// mesher's order for coplanar overlays.+/// Reorders `solid`'s quads by bucket, opaque ones first in each. Solid+/// cutout quads are also ordered front to back within each axis-facing+/// bucket; stable sorting preserves the mesher's order for coplanar overlays.pub fn sort(solid: &mut Vec<TerrainVertex>) -> Sides {+ sort_parts(solid, GROUPED.load(Ordering::Relaxed))+}++/// `sort`, with all the opaque parts first when `grouped`.+fn sort_parts(solid: &mut Vec<TerrainVertex>, grouped: bool) -> Sides {let (quads, rest) = solid.as_chunks::<4>();debug_assert!(rest.is_empty(), "solid vertices come in quads");- let buckets: Vec<u8> = quads.iter().map(|q| bucket(q) as u8).collect();- let has_cutout = quads.iter().any(|q| q[0].layer & OPAQUE_LAYER == 0);+ let cutout = |q: &[TerrainVertex; 4]| q[0].layer & OPAQUE_LAYER == 0;+ // Each quad's part, by its place in mesh order (`slot`).+ let position = |b: usize, cutout: bool| match grouped {+ true => b + 7 * usize::from(cutout),+ false => b * 2 + usize::from(cutout),+ };+ let slots: Vec<u8> = quads+ .iter()+ .map(|q| position(bucket(q), cutout(q)) as u8)+ .collect();+ let has_cutout = quads.iter().any(cutout);let mut counts = [0u32; 7];+ let mut slot_counts = [0u32; 14];let mut planes = [0f32; 7];- for (quad, &b) in quads.iter().zip(&buckets) {- let b = usize::from(b);+ for (quad, &part) in quads.iter().zip(&slots) {+ slot_counts[usize::from(part)] += 1;+ let b = slot(grouped, usize::from(part)).0;if let Bucket::Side(axis, positive) = BUCKETS[b] {let p = quad[0].pos[axis];planes[b] = match (counts[b], positive) {@@ -161,26 +239,26 @@ pub fn sort(solid: &mut Vec<TerrainVertex>) -> Sides {}counts[b] += 1;}- let mut ends = [0u32; 7];+ let mut slot_ends = [0u32; 14];let mut total = 0;- for (end, count) in ends.iter_mut().zip(counts) {+ for (end, count) in slot_ends.iter_mut().zip(slot_counts) {total += count;*end = total;}if has_cutout || counts.iter().filter(|&&c| c > 0).count() > 1 {- let mut next: [u32; 7] = std::array::from_fn(|b| ends[b] - counts[b]);+ let mut next: [u32; 14] = std::array::from_fn(|s| slot_ends[s] - slot_counts[s]);let mut sorted = vec![quads[0]; quads.len()];- for (quad, &b) in quads.iter().zip(&buckets) {- let slot = &mut next[usize::from(b)];- sorted[*slot as usize] = *quad;- *slot += 1;+ for (quad, &part) in quads.iter().zip(&slots) {+ let at = &mut next[usize::from(part)];+ sorted[*at as usize] = *quad;+ *at += 1;}if has_cutout {let mut start = 0;- for (i, bucket) in BUCKETS.iter().enumerate() {- let end = ends[i] as usize;+ for (s, &end) in slot_ends.iter().enumerate() {+ let end = end as usize;let slice = &mut sorted[start..end];- if let Bucket::Side(axis, positive) = *bucket {+ if let Bucket::Side(axis, positive) = BUCKETS[slot(grouped, s).0] {slice.sort_by(|a, b| {let a = a[0].pos[axis];let b = b[0].pos[axis];@@ -196,7 +274,12 @@ pub fn sort(solid: &mut Vec<TerrainVertex>) -> Sides {}*solid = sorted.into_flattened();}- Sides { ends, planes }+ Sides {+ ends: slot_ends,+ grouped,+ split: true,+ planes,+ }}#[cfg(test)]@@ -225,6 +308,12 @@ mod tests {.collect()}+ /// Where each bucket ends, in a mesh sorted for one pass.+ fn bucket_ends(sides: &Sides) -> [u32; 7] {+ assert!(!sides.grouped);+ std::array::from_fn(|b| sides.ends[b * 2 + 1])+ }+fn runs(sides: &Sides, eye: [f32; 3]) -> Vec<(u32, u32)> {let mut out = Vec::new();sides.visible(eye, |first, count| out.push((first, count)));@@ -261,7 +350,7 @@ mod tests {v.layer = (i / 4) as u16;}let sides = sort(&mut solid);- assert_eq!(sides.ends, [1, 2, 2, 3, 4, 5, 6]);+ assert_eq!(bucket_ends(&sides), [1, 2, 2, 3, 4, 5, 6]);let layers: Vec<u16> = solid.iter().step_by(4).map(|v| v.layer).collect();// +X, +Z, +Y, -Z, -X, -Y.assert_eq!(layers, [0, 4, 2, 5, 1, 3]);@@ -348,7 +437,7 @@ mod tests {let sides = sort(&mut solid);let both = |eye: [f32; 3], low: f32| {let mut out = Vec::new();- sides.visible_from(eye, low, |first, count| out.push((first, count)));+ sides.visible_from(eye, low, Part::All, |first, count| out.push((first, count)));out};// Above the block: +X, +Z and +Y; with the mirror's eye below it, -Y too.@@ -360,6 +449,98 @@ mod tests {assert_eq!(both([-8.0, 8.0, -8.0], -8.0), [(2, 4)]);}+ /// Opaque and cutout quads of each bucket split: each pass's runs hold+ /// exactly its own quads facing the eye, and all of them together the+ /// same runs as one pass.+ #[test]+ fn each_part_draws_its_own_quads_facing_the_eye() {+ // Two blocks: one opaque, one cutout, then an opaque one again, so+ // every bucket holds both kinds out of order.+ let mut solid = Vec::new();+ let mut id = 0u16;+ for (origin, opaque) in [+ ([0.0, 0.0, 0.0], true),+ ([4.0, 2.0, 6.0], false),+ ([9.0, 5.0, 3.0], true),+ ] {+ for q in cube(origin, 0).chunks(4) {+ let layer = id | if opaque { OPAQUE_LAYER } else { 0 };+ solid.extend(q.iter().map(|v| TerrainVertex { layer, ..*v }));+ id += 1;+ }+ }+ let unsorted = solid;+ for grouped in [false, true] {+ let mut solid = unsorted.clone();+ let sides = sort_parts(&mut solid, grouped);+ let layers: Vec<u16> = solid+ .as_chunks::<4>()+ .0+ .iter()+ .map(|q| q[0].layer)+ .collect();+ for eye in [[20.0, 30.0, -10.0], [-5.0, 1.0, 4.0], [5.0, 3.0, 7.0]] {+ let quads = |part| {+ let mut out = Vec::new();+ sides.visible_from(eye, eye[1], part, |first, count| {+ out.extend(+ layers[first as usize..(first + count) as usize]+ .iter()+ .copied(),+ )+ });+ out.sort_unstable();+ out+ };+ let mut facing = front_facing(&solid, eye);+ facing.sort_unstable();+ let opaque = quads(Part::Opaque);+ let cutout = quads(Part::Cutout);+ assert!(opaque.iter().all(|l| l & OPAQUE_LAYER != 0), "{eye:?}");+ assert!(cutout.iter().all(|l| l & OPAQUE_LAYER == 0), "{eye:?}");+ for l in &facing {+ let mine = if l & OPAQUE_LAYER != 0 {+ &opaque+ } else {+ &cutout+ };+ assert!(+ mine.contains(l),+ "{eye:?}: quad {l} facing the eye left out"+ );+ }+ let mut both = [opaque, cutout].concat();+ both.sort_unstable();+ assert_eq!(both, quads(Part::All), "{eye:?}");+ }+ // Every way: each part once, whole.+ let mut every = Vec::new();+ sides.every(Part::Opaque, |first, count| every.push((first, count)));+ sides.every(Part::Cutout, |first, count| every.push((first, count)));+ let total: u32 = every.iter().map(|r| r.1).sum();+ assert_eq!(total, sides.quads());++ // Two passes: from above a corner, each part is one or two runs.+ if grouped {+ let mut count = 0;+ sides.visible_from([20.0, 30.0, -10.0], 30.0, Part::Opaque, |_, _| count += 1);+ assert_eq!(count, 2);+ }+ }+ }++ /// A mesh that was not sorted has no parts: each pass draws all of it+ /// (the shader leaves out the other pass's quads).+ #[test]+ fn unsorted_meshes_draw_everything_in_each_part() {+ let sides = Sides::unsorted(9);+ for part in [Part::Opaque, Part::Cutout] {+ let mut out = Vec::new();+ sides.every(part, |first, count| out.push((first, count)));+ assert_eq!(out, [(0, 9)]);+ }+ }+#[test]fn unsorted_meshes_draw_everything() {let sides = Sides::unsorted(9);@@ -385,7 +566,7 @@ mod tests {.collect();let before = solid.clone();let sides = sort(&mut solid);- assert_eq!(sides.ends, [3; 7]);+ assert_eq!(bucket_ends(&sides), [3; 7]);assert_eq!(solid.iter().map(|v| v.layer).collect::<Vec<_>>(),before.iter().map(|v| v.layer).collect::<Vec<_>>()diff --git a/crates/horizon-client-render/src/terrain.wgsl b/crates/horizon-client-render/src/terrain.wgslindex 6fb445891..343e1cf54 100644--- a/crates/horizon-client-render/src/terrain.wgsl+++ b/crates/horizon-client-render/src/terrain.wgsl@@ -311,10 +311,10 @@ fn fade_code(w: f32) -> u32 {return terrain_vertex(position, terrain_uv(uv, origin.w), layer, color, light, origin.xyz,origin.w);}-// Solid terrain draws in two passes from the same draws: first the quads with no-// cutout that are not fading, through `fs_opaque`, which never discards, so a tiled-// GPU (Apple's) keeps hiding the pixels behind them; then the rest through-// `fs_solid`. One discard anywhere in a pipeline's shader turned that hiding off for+// Solid terrain draws in two passes, each over its own part of every mesh's quads+// (`mesher::Part`): first the quads with no cutout that are not fading, through+// `fs_opaque`, which never discards, so a tiled GPU (Apple's) keeps hiding the pixels+// behind them; then the rest through `fs_solid`. One discard anywhere in a pipeline's shader turned that hiding off for// all the terrain it drew. A quad the pass leaves out is decided before any of the// vertex's work and lies outside the clip volume: it makes no pixel.fn opaque_quad(layer: u32, w: f32) -> bool {