diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 0183559ef..3e0711aeb 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -197,6 +197,16 @@ impl Game<'_> { } Ok(Some(json!({ "ok": true, "flat": r.flat_draws() }))) } + "section-cull" => { + let r = self.renderer.as_mut().ok_or("no renderer")?; + match words.get(1).copied() { + None => {} + Some("on") => r.set_section_cull(true)?, + Some("off") => r.set_section_cull(false)?, + Some(other) => return Err(format!("unknown section cull mode {other}").into()), + } + Ok(Some(json!({ "ok": true, "cull": r.section_cull() }))) + } "sculk" => Ok(Some(self.sculk_command(&words)?)), "status" => Ok(Some(self.control_status())), "pad" => Ok(Some(self.pad_command(&words)?)), @@ -714,6 +724,7 @@ impl Game<'_> { "drawn_sections": r.drawn_sections, "section_draws": r.section_draws, "section_draw_calls": r.section_draw_calls, + "culled_sections": r.culled_sections(), "uploaded_bytes": r.uploaded_bytes, "resident_sections": r.resident_sections(), "arena_bytes": arena_bytes, diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index c8355a395..31a7a33a0 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -12,6 +12,7 @@ pub const HELP: &[&str] = &[ "particle NAME X Y Z [DX DY DZ] [COUNT] spawn particles (vanilla /particle spread)", "signedit X Y Z [front|back] open the sign editor for the sign at X Y Z", "section-draws [flat|indirect] how terrain sections are drawn (A/B checks); replies the mode", + "section-cull [on|off] occlusion culling of solid sections (A/B checks); replies the mode", ]; impl Game<'_> { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index d3b71bc60..8481fdcab 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -58,6 +58,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] } mod arena; +mod cull; mod flat; mod java_stages; mod occlusion; @@ -270,6 +271,9 @@ pub struct Renderer { flat: Option, /// `flat` draws this frame's sections (off: the per-section draws). flat_on: bool, + /// Occlusion culling of solid section draws, where multi-draw is native. + cull: Option, + cull_on: bool, sky: wgpu::RenderPipeline, dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, @@ -365,6 +369,10 @@ pub struct Renderer { draws: Vec<[u32; 5]>, /// Vertex arena page and optional sorted index arena page of each draw. draw_pages: Vec<(u32, Option)>, + /// Solid draws left to occlusion culling's phase 2, while the list is + /// built, and their pages. + phase2_draws: Vec<[u32; 5]>, + phase2_pages: Vec<(u32, Option)>, /// Block-entity blocks per meshed section (world position, state id). block_entities: HashMap>, /// Changes whenever `block_entities` does (unique across renderers). @@ -654,6 +662,7 @@ impl Renderer { // Mappable primary buffers: section pages that no // longer fit in video memory go to system memory. required_features: timing::GpuTimer::features(&adapter) + | cull::Cull::features(&adapter) | (adapter.features() & (wgpu::Features::INDIRECT_FIRST_INSTANCE | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)), @@ -1100,7 +1109,9 @@ impl Renderer { let instances = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section origins"), size: instance_capacity * 16, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::STORAGE, mapped_at_creation: false, }); let outline = device.create_buffer(&wgpu::BufferDescriptor { @@ -1745,6 +1756,15 @@ impl Renderer { let multi_draw = device .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); + // HORIZON_GPU_CULL=0 turns occlusion culling off, `all` culls every + // frame however little it hides (A/B checks). + let cull_env = std::env::var("HORIZON_GPU_CULL"); + let cull = (cull_env.as_deref() != Ok("0") && cull::Cull::supported(&adapter, &device)) + .then(|| { + let mut cull = cull::Cull::new(&device, config.format.remove_srgb_suffix()); + cull.always = cull_env.as_deref() == Ok("all"); + cull + }); let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix()); let uploads = upload::Uploads::new(&device); let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK); @@ -1772,6 +1792,8 @@ impl Renderer { solid, translucent, flat_on: flat.is_some(), + cull_on: cull.is_some(), + cull, flat, sky, dark_disc, @@ -1845,6 +1867,8 @@ impl Renderer { origins: Vec::new(), draws: Vec::new(), draw_pages: Vec::new(), + phase2_draws: Vec::new(), + phase2_pages: Vec::new(), block_entities: HashMap::new(), block_entity_revision: next_block_entity_revision(), occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16), @@ -1998,6 +2022,27 @@ impl Renderer { self.flat_on = on; Ok(()) } + /// Whether solid sections are occlusion culled (`cull`). + pub fn section_cull(&self) -> bool { + self.cull_on + } + /// Switches occlusion culling, for A/B checks. + pub fn set_section_cull(&mut self, on: bool) -> Result<()> { + if on && self.cull.is_none() { + return Err("occlusion culling is off on this device".into()); + } + self.cull_on = on; + Ok(()) + } + /// Of the boxes occlusion culling's last test read back drew, how many + /// it did not see and how many it drew, and the share of solid indices + /// it hid. + pub fn culled_sections(&self) -> Option<([usize; 2], f32)> { + self.cull + .as_ref() + .filter(|_| self.cull_on) + .map(|c| c.hidden) + } pub fn section_count(&self) -> usize { self.sections.len() } @@ -2117,7 +2162,15 @@ impl Renderer { /// origins bound: one indirect multi-draw, or a loop without it. /// Consecutive draws in one arena page share a vertex buffer binding, /// keeping the list's order (translucent sections go back to front). - fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) { + /// `indirect` holds the list's draws from `base`. + fn draw_sections( + &self, + pass: &mut wgpu::RenderPass<'_>, + indirect: &wgpu::Buffer, + base: u32, + first: u32, + count: u32, + ) { let (mut i, end) = (first as usize, (first + count) as usize); while i < end { let (page, index_page) = self.draw_pages[i]; @@ -2129,7 +2182,8 @@ impl Renderer { let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p)); pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); if self.multi_draw { - pass.multi_draw_indexed_indirect(&self.indirect, i as u64 * 20, run as u32); + let offset = (i - base as usize) as u64 * 20; + pass.multi_draw_indexed_indirect(indirect, offset, run as u32); } else { for d in &self.draws[i..i + run] { pass.draw_indexed(d[2]..d[2] + d[0], d[3] as i32, d[4]..d[4] + 1); @@ -2574,7 +2628,9 @@ impl Renderer { self.instances = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section origins"), size: self.instance_capacity * 16, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::STORAGE, mapped_at_creation: false, }); } @@ -2603,15 +2659,48 @@ impl Renderer { let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch)) .inverse() .transform_point3(Vec3::ZERO); + // Occlusion culling leaves the sections its last result did not see + // to phase 2, after the others, with instance counts of 0. + let mut cull = self + .cull + .as_mut() + .filter(|_| { + self.cull_on + && !frame.title + && self.multi_draw + && !(self.flat_on && self.flat.is_some()) + }) + .and_then(|cull| cull.begin(&self.device).then_some(cull)); + self.phase2_draws.clear(); + self.phase2_pages.clear(); 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)); + let (draws, pages) = if first_phase { + (&mut self.draws, &mut self.draw_pages) + } else { + (&mut self.phase2_draws, &mut self.phase2_pages) + }; + let start = draws.len(); + let instances = u32::from(first_phase); + let mut indices = 0; // Only the solid groups that can face the eye. s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| { let first = s.start + u64::from(first) * 4; - self.draws.push([quads * 6, 1, 0, first as u32, i as u32]); - self.draw_pages.push((s.page, None)); + draws.push([quads * 6, instances, 0, first as u32, i as u32]); + pages.push((s.page, None)); + indices += quads * 6; }); + match &mut cull { + Some(c) if first_phase => c.drawn(i, v.slot, indices), + Some(c) => c.deferred(i, v.slot, start, draws.len() - start, indices), + None => {} + } } + let phase1_draws = self.draws.len() as u32; + self.draws.extend_from_slice(&self.phase2_draws); + self.draw_pages.extend_from_slice(&self.phase2_pages); + let culling = cull.is_some(); let solid_draws = self.draws.len() as u32; // LevelRenderer: nearby sections each frame, plus a rotating eighth // (at least 15) of the visible list. Cached views avoid needless sorts. @@ -2661,6 +2750,7 @@ impl Renderer { (0..self.draws.len()) .filter(|&i| { i == 0 + || i == phase1_draws as usize || i == solid_draws as usize || self.draw_pages[i] != self.draw_pages[i - 1] }) @@ -2874,6 +2964,16 @@ impl Renderer { 0, bytemuck::cast_slice(&self.draws), ); + if culling && let Some(cull) = &mut self.cull { + cull.upload( + &self.device, + &mut self.uploads, + &mut encoder, + &self.draws[phase1_draws as usize..solid_draws as usize], + &self.instances, + &self.globals, + ); + } } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), @@ -2891,6 +2991,7 @@ impl Renderer { Some((color, depth)) => (color, depth), None => (&view_target, &self.depth), }; + let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0); { let attachments = [Some(wgpu::RenderPassColorAttachment { view: world_view, @@ -2919,8 +3020,9 @@ impl Renderer { view: world_depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0.0), - // A shader pack reads the world's depth. - store: if pack { + // A shader pack reads the world's depth, and + // phase 2 of occlusion culling draws over it. + store: if pack || cull.is_some() { wgpu::StoreOp::Store } else { wgpu::StoreOp::Discard @@ -2970,7 +3072,59 @@ impl Renderer { pass.set_pipeline(&self.solid); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(1, self.instances.slice(..)); - self.draw_sections(&mut pass, 0, solid_draws); + match cull { + Some(cull) => { + // Phase 1 and the boxes against its depth, then + // what they found in sight, in a pass that loads + // both targets (it reads the test's results). + self.draw_sections(&mut pass, &self.indirect, 0, 0, phase1_draws); + cull.test(&mut pass); + drop(pass); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: world_view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })]; + pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon world, after culling"), + color_attachments: &attachments, + depth_stencil_attachment: Some( + wgpu::RenderPassDepthStencilAttachment { + view: world_depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: if pack { + wgpu::StoreOp::Store + } else { + wgpu::StoreOp::Discard + }, + }), + stencil_ops: None, + }, + ), + ..Default::default() + }); + pass.set_bind_group(0, &self.group, &[]); + pass.set_pipeline(&self.solid); + pass.set_index_buffer( + self.indices.slice(..), + wgpu::IndexFormat::Uint32, + ); + pass.set_vertex_buffer(1, self.instances.slice(..)); + self.draw_sections( + &mut pass, + &cull.phase2, + phase1_draws, + phase1_draws, + solid_draws - phase1_draws, + ); + } + None => self.draw_sections(&mut pass, &self.indirect, 0, 0, solid_draws), + } } } if entity_quads > 0 { @@ -3022,7 +3176,13 @@ impl Renderer { pass.set_pipeline(&self.translucent); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(1, self.instances.slice(..)); - self.draw_sections(&mut pass, solid_draws, translucent_draws); + self.draw_sections( + &mut pass, + &self.indirect, + 0, + solid_draws, + translucent_draws, + ); } } // LevelRenderer.executeClassicTransparency: translucent targets' @@ -3236,6 +3396,9 @@ impl Renderer { frame.hud, [self.config.width, self.config.height], ); + if culling && let Some(cull) = &mut self.cull { + cull.end(&self.device, &mut encoder); + } if let Some(timer) = &mut self.gpu_timer { timer.end(&mut encoder); } @@ -3250,6 +3413,9 @@ impl Renderer { } let commands = crate::spans::time("encode", || encoder.finish()); let submission = crate::spans::time("submit", || self.queue.submit([commands])); + if let Some(cull) = &mut self.cull { + cull.submitted(); + } if let Some(timer) = &mut self.gpu_timer { timer.submitted(); timer.collect(&self.device, &mut self.gpu_times); diff --git a/crates/horizon-client/src/gfx/cull.rs b/crates/horizon-client/src/gfx/cull.rs new file mode 100644 index 000000000..6926aab70 --- /dev/null +++ b/crates/horizon-client/src/gfx/cull.rs @@ -0,0 +1,511 @@ +//! Occlusion culling of solid section draws, in two phases. +//! +//! Frustum and cave culling leave many sections that terrain in front hides +//! entirely (about half of the solid vertices drawn from the ground at render +//! distance 16, more at 32), and drawing fewer vertices is what helps an +//! integrated GPU. Phase 1 draws the sections that the last test read back +//! saw. Then, in the same pass, the box of every other section (and of a +//! share of phase 1's, to notice when they go out of sight) is drawn against +//! phase 1's depth with no writes but to the test's results. Phase 2, in a +//! second pass, draws the sections whose box was seen; the others' draws have +//! an instance count of 0. +//! +//! The picture stays the one without culling: the boxes (grown by a block, +//! the farthest a block model reaches out of its cell) are drawn front faces +//! only, so a fragment is the box's nearest point on its pixel, and the +//! fragment shader runs only where the depth test passes (forced early), so a +//! section is left out only where all of its fragments would fail the depth +//! test against the final depth, which is only nearer. What the CPU knows of +//! the results only sorts sections between the phases: a stale result draws +//! a hidden section in phase 1, or tests a section that is in sight. +//! +//! Every solid draw is an entry of one of the two lists, so the CPU records +//! as many draws as without culling: drivers that unroll an indirect +//! multi-draw on the CPU (Mesa's on Intel Gen9) pay per entry. Phase 2's +//! counts come from the GPU, which needs a native multi-draw and forced +//! early depth tests: Vulkan. Translucent draws are not culled. +use std::num::NonZeroU64; +use std::sync::{ + Arc, + atomic::{AtomicU8, Ordering}, +}; + +const WORDS: u64 = 5 * 4; +/// Phase 1's sections are each tested every `RETEST` frames. +const RETEST: u32 = 8; +/// Culling runs while the last result read back hid at least this share of +/// the frame's solid indices: below it the test and the second pass cost +/// more than they save. Else one frame in `PROBE` tests every section. +const MIN_SHARE: f32 = 0.1; +const PROBE: u32 = 64; +/// Boxes over more than this share of the screen count as seen untested. +const BIG: f32 = 0.25; +/// Results read back at once, some frames late so the CPU never waits. +const READBACKS: usize = 3; +const FREE: u8 = 0; +const PENDING: u8 = 1; +const MAPPED: u8 = 2; + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Params { + stamp: u32, + big: f32, + pad: [u32; 2], +} + +/// One frame's results on their way back. +struct Readback { + buffer: wgpu::Buffer, + capacity: u64, + state: Arc, + stamp: u32, + /// The resident slot of each test, and its section's solid indices. + slots: Vec, + indices: Vec, + /// The frame's solid indices. + total: u64, +} + +/// The bind group and the buffers from outside it was made with. +struct Group { + origins: wgpu::Buffer, + globals: wgpu::Buffer, + group: wgpu::BindGroup, +} + +pub struct Cull { + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + group: Option, + params: wgpu::Buffer, + /// Phase 2's draws: the solid draws after phase 1's in the frame's list. + pub phase2: wgpu::Buffer, + phase2_capacity: u64, + tests: wgpu::Buffer, + tests_capacity: u64, + /// This frame's tests: visible index, first phase 2 draw, phase 2 draws. + test_data: Vec<[u32; 4]>, + test_slots: Vec, + test_indices: Vec, + total: u64, + /// The frame tests every section, as culling was off. + probe: bool, + results: wgpu::Buffer, + readbacks: Vec, + next: usize, + current: Option, + /// Per resident slot: whether the last result read back saw it. + seen: Vec, + stamp: u32, + /// Of the boxes the last test read back drew, how many it did not see + /// and how many it drew, and the share of solid indices hidden. + pub hidden: ([usize; 2], f32), + /// Cull every frame, whatever the hidden share (A/B checks). + pub always: bool, +} + +fn buffer( + device: &wgpu::Device, + label: &str, + size: u64, + usage: wgpu::BufferUsages, +) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size, + usage, + mapped_at_creation: false, + }) +} + +const PHASE2_USAGE: wgpu::BufferUsages = wgpu::BufferUsages::INDIRECT + .union(wgpu::BufferUsages::STORAGE) + .union(wgpu::BufferUsages::COPY_DST); +const TESTS_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_DST); +const RESULTS_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_SRC); +const READBACK_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::MAP_READ.union(wgpu::BufferUsages::COPY_DST); + +impl Cull { + /// The device feature culling needs, where the adapter has it. + pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features { + adapter.features() & wgpu::Features::SHADER_EARLY_DEPTH_TEST + } + /// Whether the device draws an indirect multi-draw natively and runs + /// fragment shaders that write storage only past an early depth test. + pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + adapter.get_info().backend == wgpu::Backend::Vulkan + && device.features().contains( + wgpu::Features::SHADER_EARLY_DEPTH_TEST | wgpu::Features::INDIRECT_FIRST_INSTANCE, + ) + && adapter.get_downlevel_capabilities().flags.contains( + wgpu::DownlevelFlags::VERTEX_STORAGE + | wgpu::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE, + ) + } + /// `color` is the world pass's colour format. + pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat) -> Self { + let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry { + binding, + visibility, + ty, + count: None, + }; + let storage = |read_only| wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only }, + has_dynamic_offset: false, + min_binding_size: None, + }; + let uniform = wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }; + let both = wgpu::ShaderStages::VERTEX_FRAGMENT; + let vertex = wgpu::ShaderStages::VERTEX; + let fragment = wgpu::ShaderStages::FRAGMENT; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Section culling"), + entries: &[ + entry(0, both, storage(true)), + entry(1, fragment, storage(false)), + entry(2, fragment, storage(false)), + entry(3, vertex, storage(true)), + entry(4, vertex, uniform), + entry(5, both, uniform), + ], + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Section culling"), + source: wgpu::ShaderSource::Wgsl(include_str!("cull.wgsl").into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Section culling"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Section culling"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs_box"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + ..Default::default() + }, + // The world pass's reversed depth test, without writes. + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::GreaterEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_box"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: color, + blend: None, + write_mask: wgpu::ColorWrites::empty(), + })], + }), + multiview_mask: None, + cache: None, + }); + Self { + pipeline, + layout, + group: None, + params: buffer( + device, + "Section culling parameters", + std::mem::size_of::() as u64, + wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + ), + phase2: buffer(device, "Section draws, phase 2", WORDS, PHASE2_USAGE), + phase2_capacity: 1, + tests: buffer(device, "Section tests", 16, TESTS_USAGE), + tests_capacity: 1, + test_data: Vec::new(), + test_slots: Vec::new(), + test_indices: Vec::new(), + total: 0, + probe: false, + results: buffer(device, "Section test results", 4, RESULTS_USAGE), + readbacks: (0..READBACKS) + .map(|_| Readback { + buffer: buffer(device, "Section test readback", 4, READBACK_USAGE), + capacity: 1, + state: Arc::new(AtomicU8::new(FREE)), + stamp: 0, + slots: Vec::new(), + indices: Vec::new(), + total: 0, + }) + .collect(), + next: 0, + current: None, + seen: Vec::new(), + stamp: 0, + hidden: ([0; 2], 1.0), + always: false, + } + } + + /// Start a frame: take in the results that came back, and tell whether + /// the frame culls. + pub fn begin(&mut self, device: &wgpu::Device) -> bool { + let _ = device.poll(wgpu::PollType::Poll); + for i in 0..READBACKS { + let r = &mut self.readbacks[(self.next + i) % READBACKS]; + if r.state.load(Ordering::Acquire) != MAPPED { + continue; + } + let mapped = r.buffer.slice(..r.slots.len() as u64 * 4); + if let Ok(data) = mapped.get_mapped_range() { + let results: &[u32] = bytemuck::cast_slice(&data); + let (mut hidden, mut indices) = (0, 0u64); + for (&result, &n) in results.iter().zip(&r.indices) { + if result != r.stamp { + hidden += 1; + indices += u64::from(n); + } + } + let share = indices as f32 / r.total.max(1) as f32; + self.hidden = ([hidden, results.len()], share); + for (&slot, &result) in r.slots.iter().zip(results) { + let slot = slot as usize; + if slot >= self.seen.len() { + self.seen.resize(slot + 1, false); + } + self.seen[slot] = result == r.stamp; + } + } + r.buffer.unmap(); + r.state.store(FREE, Ordering::Release); + } + self.stamp = self.stamp.wrapping_add(1).max(1); + self.test_data.clear(); + self.test_slots.clear(); + self.test_indices.clear(); + self.total = 0; + self.probe = !self.always && self.hidden.1 < MIN_SHARE; + !self.probe || self.stamp.is_multiple_of(PROBE) + } + + /// Whether phase 1 draws the section in resident `slot`. + pub fn first(&self, slot: u32) -> bool { + self.seen.get(slot as usize).copied().unwrap_or(false) + } + + /// A section phase 1 draws, `index` in the visible list, with `indices` + /// solid indices: tested in turn. + pub fn drawn(&mut self, index: usize, slot: u32, indices: u32) { + self.total += u64::from(indices); + if indices > 0 && (self.probe || slot.wrapping_add(self.stamp).is_multiple_of(RETEST)) { + self.push([index as u32, 0, 0, 0], slot, indices); + } + } + + /// A section left to phase 2: its `draws` from phase 2's `first`. + pub fn deferred(&mut self, index: usize, slot: u32, first: usize, draws: usize, indices: u32) { + self.total += u64::from(indices); + if draws > 0 { + self.push([index as u32, first as u32, draws as u32, 0], slot, indices); + } + } + + fn push(&mut self, test: [u32; 4], slot: u32, indices: u32) { + self.test_data.push(test); + self.test_slots.push(slot); + self.test_indices.push(indices); + } + + /// Stage this frame's inputs: phase 2's draws, with instance counts of 0, + /// and the tests, which read the frame's camera-relative `origins` and + /// view projection (the start of `globals`). + pub fn upload( + &mut self, + device: &wgpu::Device, + uploads: &mut super::upload::Uploads, + encoder: &mut wgpu::CommandEncoder, + phase2: &[[u32; 5]], + origins: &wgpu::Buffer, + globals: &wgpu::Buffer, + ) { + let draws = phase2.len() as u64; + if draws > self.phase2_capacity { + self.phase2_capacity = draws.next_power_of_two(); + self.phase2 = buffer( + device, + "Section draws, phase 2", + self.phase2_capacity * WORDS, + PHASE2_USAGE, + ); + self.group = None; + } + let tests = self.test_data.len() as u64; + if tests > self.tests_capacity { + self.tests_capacity = tests.next_power_of_two(); + self.tests = buffer( + device, + "Section tests", + self.tests_capacity * 16, + TESTS_USAGE, + ); + self.results = buffer( + device, + "Section test results", + self.tests_capacity * 4, + RESULTS_USAGE, + ); + self.group = None; + } + if draws > 0 { + uploads.buffer(encoder, &self.phase2, 0, bytemuck::cast_slice(phase2)); + } + if tests > 0 { + uploads.buffer( + encoder, + &self.tests, + 0, + bytemuck::cast_slice(&self.test_data), + ); + } + let params = Params { + stamp: self.stamp, + big: BIG, + pad: [0; 2], + }; + uploads.buffer(encoder, &self.params, 0, bytemuck::bytes_of(¶ms)); + if !self + .group + .as_ref() + .is_some_and(|g| g.origins == *origins && g.globals == *globals) + { + self.group = Some(self.make_group(device, origins, globals)); + } + } + + /// In the world pass after phase 1: draw the tested boxes against its + /// depth. Leaves the pass's pipeline and group 0 changed. + pub fn test(&self, pass: &mut wgpu::RenderPass<'_>) { + let Some(Group { group, .. }) = &self.group else { + return; + }; + if self.test_data.is_empty() { + return; + } + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, group, &[]); + pass.draw(0..36, 0..self.test_data.len() as u32); + } + + /// After the world passes: copy the results for reading back, when a + /// readback buffer is free. + pub fn end(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) { + let tests = self.test_data.len() as u64; + let r = &mut self.readbacks[self.next]; + if tests == 0 || r.state.load(Ordering::Acquire) != FREE { + return; + } + if tests > r.capacity { + r.capacity = tests.next_power_of_two(); + r.buffer = buffer( + device, + "Section test readback", + r.capacity * 4, + READBACK_USAGE, + ); + } + encoder.copy_buffer_to_buffer(&self.results, 0, &r.buffer, 0, tests * 4); + r.stamp = self.stamp; + r.slots.clear(); + r.slots.extend_from_slice(&self.test_slots); + r.indices.clear(); + r.indices.extend_from_slice(&self.test_indices); + r.total = self.total; + self.current = Some(self.next); + } + + /// After the frame's submission: start reading its results back. + pub fn submitted(&mut self) { + let Some(i) = self.current.take() else { + return; + }; + let r = &self.readbacks[i]; + let state = r.state.clone(); + state.store(PENDING, Ordering::Release); + r.buffer + .slice(..r.slots.len() as u64 * 4) + .map_async(wgpu::MapMode::Read, move |result| { + state.store( + if result.is_ok() { MAPPED } else { FREE }, + Ordering::Release, + ); + }); + self.next = (i + 1) % READBACKS; + } + + fn make_group( + &self, + device: &wgpu::Device, + origins: &wgpu::Buffer, + globals: &wgpu::Buffer, + ) -> Group { + fn whole(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> { + wgpu::BindGroupEntry { + binding, + resource: buffer.as_entire_binding(), + } + } + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Section culling"), + layout: &self.layout, + entries: &[ + whole(0, &self.tests), + whole(1, &self.results), + whole(2, &self.phase2), + whole(3, origins), + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: globals, + offset: 0, + size: NonZeroU64::new(64), + }), + }, + whole(5, &self.params), + ], + }); + Group { + origins: origins.clone(), + globals: globals.clone(), + group, + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn shader_validates() { + let module = naga::front::wgsl::parse_str(include_str!("cull.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } +} diff --git a/crates/horizon-client/src/gfx/cull.wgsl b/crates/horizon-client/src/gfx/cull.wgsl new file mode 100644 index 000000000..faa495caf --- /dev/null +++ b/crates/horizon-client/src/gfx/cull.wgsl @@ -0,0 +1,101 @@ +// Occlusion culling of solid section draws (gfx/cull.rs). + +struct Params { + // This frame's test: a test that sees its box stores the number. + stamp: u32, + // Boxes covering more than this share of the screen count as seen. + big: f32, +} +// The leading member of terrain.wgsl's Globals. +struct Globals { + view_proj: mat4x4, +} + +// One test per section: its visible index (which names its origin), its +// first draw in `phase2` and how many draws it has there (0: phase 1 drew +// it, and the test only tells whether it is still in sight). +@group(0) @binding(0) var tests: array>; +// Per test: the stamp of the frame whose test saw the box. +@group(0) @binding(1) var results: array; +// Phase 2's draws, 5 words each, with instance counts of 0 until seen. +@group(0) @binding(2) var phase2: array; +// Camera-relative origin of each visible section. +@group(0) @binding(3) var origins: array>; +@group(0) @binding(4) var globals: Globals; +@group(0) @binding(5) var params: Params; + +// The corners (bit 0: x, bit 1: y, bit 2: z) of the box's 12 triangles, +// counter-clockwise seen from outside. +const CORNERS = array( + 0u, 6u, 2u, 0u, 4u, 6u, 1u, 3u, 7u, 1u, 7u, 5u, 0u, 1u, 5u, 0u, 5u, 4u, + 2u, 7u, 3u, 2u, 6u, 7u, 0u, 3u, 1u, 0u, 2u, 3u, 4u, 5u, 7u, 4u, 7u, 6u, +); + +struct Box { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) test: u32, +} + +fn corner(origin: vec3, c: u32) -> vec3 { + return origin + vec3( + select(-1.0, 17.0, (c & 1u) != 0u), + select(-1.0, 17.0, (c & 2u) != 0u), + select(-1.0, 17.0, (c & 4u) != 0u), + ); +} + +// Each tested section's box, grown by a block (block models reach one block +// out of their cell), drawn after phase 1 against its depth with back faces +// culled: a front face fragment that passes the depth test is the box's +// nearest point on that pixel in front of phase 1's depth, so the section +// may show there. A box failing everywhere would have every fragment of its +// section fail the depth test against the final depth, which is only nearer. +@vertex +fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box { + let origin = origins[tests[t].x].xyz; + var out: Box; + out.test = t; + // The box's screen rectangle, from the corners in front of the camera. + var lo = vec2(1e30); + var hi = vec2(-1e30); + var behind = false; + for (var c = 0u; c < 8u; c++) { + let p = globals.view_proj * vec4(corner(origin, c), 1.0); + behind = behind || p.w <= 0.0; + let q = p.xy / max(p.w, 1e-6); + lo = min(lo, q); + hi = max(hi, q); + } + let size = max(min(hi, vec2(1.0)) - max(lo, vec2(-1.0)), vec2(0.0)); + // A box within a block of the camera may cross the near plane, which + // clips its front faces away, and a box over a large part of the screen + // is nearly always in sight and costly to test: both count as seen, + // through a small triangle in the top left corner at the nearest depth. + let near = all(origin < vec3(2.0)) && all(origin > vec3(-18.0)); + if near || (!behind && size.x * size.y > params.big * 4.0) { + var p = vec2(-1.0, 1.0); + if v == 1u { + p.y -= 0.05; + } else if v == 2u { + p.x += 0.05; + } + out.position = select(vec4(0.0, 0.0, 0.0, 1.0), vec4(p, 1.0, 1.0), v < 3u); + return out; + } + out.position = globals.view_proj * vec4(corner(origin, CORNERS[v]), 1.0); + return out; +} + +// Runs only for fragments that pass the depth test (forced early). +@fragment +@early_depth_test(force) +fn fs_box(in: Box) -> @location(0) vec4 { + if results[in.test] != params.stamp { + results[in.test] = params.stamp; + let test = tests[in.test]; + for (var k = 0u; k < test.z; k++) { + phase2[(test.y + k) * 5u + 1u] = 1u; + } + } + return vec4(0.0); +}