From 111745145b910aa93aa39543035ec8eb8860d745 Mon Sep 17 00:00:00 2001 From: Ralph Kuepper Date: Mon, 16 Nov 2026 19:43:22 +0100 Subject: [PATCH 1/2] perf(shadows): shadow casters read a 24-byte depth twin of the geometry arena Static meshes in the shared geometry arena are 96-byte Vertex3D; a shadow pass only needs position (and uv + alpha for cutouts). The arena now keeps a DepthVertex twin (position, uv, alpha; 24 bytes, 4:1 so base_vertex is unchanged) written on upload and copied on grow. Sun cascades and lamp shadow cubes draw arena geometry from the twin with two compact pipelines; skinned and non-arena buffers keep the full stream. Radeon 760M, High, fight at fixed resolution: shadow_pass 4.2 -> 2.9 ms, fight 28.9 -> 30.0 fps, worst window 24.9 -> 27.4. SCENESHOT views match (differences are wind and clouds only). Costs ~26 MB of extra VRAM for the forest arena. BLOOM_SKIP=shadow_compact restores the full stream for A/B. --- native/shared/src/renderer/geometry_arena.rs | 79 ++++++++++++++ native/shared/src/renderer/gpu_driven.rs | 9 ++ .../src/renderer/local_light_shadows.rs | 14 ++- native/shared/src/renderer/shadow_pass.rs | 38 ++++++- native/shared/src/shadows.rs | 103 ++++++++++++++++++ 5 files changed, 237 insertions(+), 6 deletions(-) diff --git a/native/shared/src/renderer/geometry_arena.rs b/native/shared/src/renderer/geometry_arena.rs index 9a074155..adea4768 100644 --- a/native/shared/src/renderer/geometry_arena.rs +++ b/native/shared/src/renderer/geometry_arena.rs @@ -6,6 +6,56 @@ use super::super::{material_indirection::GpuCompletionTracker, Vertex3D}; use super::GeometrySlice; +/// The depth-only twin of an arena vertex: what a pass that only writes depth +/// reads (position, and uv + vertex alpha for an alpha-tested cutout). +/// +/// WHY A TWIN STREAM. `Vertex3D` is 96 bytes, and a depth pass that reads only +/// its position still pulls whole 96-byte vertices through the cache. On an +/// integrated GPU, whose vertex fetch shares system memory with everything +/// else, the forest's ~1.1M vertices cost ~4 ms per pass that draws them, and a +/// frame draws them into every shadow cascade and lamp shadow face as well as +/// the camera. This stream is a quarter of that, at the same vertex index: +/// vertex i of the arena is twin i here, so a draw's `base_vertex` and index +/// range are unchanged and only the bound buffer and pipeline differ. +#[repr(C)] +#[derive(Copy, Clone, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)] +pub(crate) struct DepthVertex { + pub(crate) position: [f32; 3], + pub(crate) uv: [f32; 2], + pub(crate) alpha: f32, +} + +/// Bytes of the arena's `Vertex3D` stream per byte of its depth twin. +const DEPTH_RATIO: u64 = + (std::mem::size_of::() / std::mem::size_of::()) as u64; +const _: () = assert!( + std::mem::size_of::() % std::mem::size_of::() == 0, + "the depth twin must divide the vertex stride exactly", +); + +impl DepthVertex { + pub(crate) fn desc() -> wgpu::VertexBufferLayout<'static> { + const ATTRS: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![ + 0 => Float32x3, + 1 => Float32x2, + 2 => Float32, + ]; + wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &ATTRS, + } + } + + fn of(v: &Vertex3D) -> Self { + Self { + position: v.position, + uv: v.uv, + alpha: v.color[3], + } + } +} + #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] struct FreeRange { offset: u64, @@ -19,6 +69,8 @@ struct RetiredGeometry { pub(super) struct GeometryArena { pub(super) vertex: wgpu::Buffer, + /// `vertex`'s depth-only twin (see `DepthVertex`), byte offset / DEPTH_RATIO. + pub(super) depth: wgpu::Buffer, pub(super) index: wgpu::Buffer, vertex_capacity: u64, index_capacity: u64, @@ -48,6 +100,7 @@ impl GeometryArena { ), full_warned: false, vertex: create_vertex_arena(device, Self::INITIAL_CAPACITY), + depth: create_depth_arena(device, Self::INITIAL_CAPACITY / DEPTH_RATIO), index: create_index_arena(device, Self::INITIAL_CAPACITY), vertex_capacity: Self::INITIAL_CAPACITY, index_capacity: Self::INITIAL_CAPACITY, @@ -120,6 +173,12 @@ impl GeometryArena { ); if vertex_size > 0 { queue.write_buffer(&self.vertex, vertex_offset, bytemuck::cast_slice(vertices)); + let depth: Vec = vertices.iter().map(DepthVertex::of).collect(); + queue.write_buffer( + &self.depth, + vertex_offset / DEPTH_RATIO, + bytemuck::cast_slice(&depth), + ); } if index_size > 0 { queue.write_buffer(&self.index, index_offset, bytemuck::cast_slice(indices)); @@ -199,10 +258,19 @@ impl GeometryArena { }); if new_vertex_capacity != self.vertex_capacity { let next = create_vertex_arena(device, new_vertex_capacity); + let next_depth = create_depth_arena(device, new_vertex_capacity / DEPTH_RATIO); if copy_vertex_end > 0 { encoder.copy_buffer_to_buffer(&self.vertex, 0, &next, 0, copy_vertex_end); + encoder.copy_buffer_to_buffer( + &self.depth, + 0, + &next_depth, + 0, + copy_vertex_end / DEPTH_RATIO, + ); } self.vertex = next; + self.depth = next_depth; self.vertex_capacity = new_vertex_capacity; } if new_index_capacity != self.index_capacity { @@ -230,6 +298,17 @@ fn create_vertex_arena(device: &wgpu::Device, size: u64) -> wgpu::Buffer { }) } +fn create_depth_arena(device: &wgpu::Device, size: u64) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("gpu_driven_shared_depth_vertices"), + size: size.max(4), + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::COPY_SRC + | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) +} + fn create_index_arena(device: &wgpu::Device, size: u64) -> wgpu::Buffer { device.create_buffer(&wgpu::BufferDescriptor { label: Some("gpu_driven_shared_indices"), diff --git a/native/shared/src/renderer/gpu_driven.rs b/native/shared/src/renderer/gpu_driven.rs index c33dd6af..f700e9ce 100644 --- a/native/shared/src/renderer/gpu_driven.rs +++ b/native/shared/src/renderer/gpu_driven.rs @@ -17,6 +17,7 @@ use std::sync::OnceLock; #[path = "geometry_arena.rs"] mod geometry_arena; use geometry_arena::GeometryArena; +pub(crate) use geometry_arena::DepthVertex; pub const GPU_DRIVEN_FEATURES: wgpu::Features = wgpu::Features::INDIRECT_FIRST_INSTANCE; pub(crate) const DRAW_FLAG_DOUBLE_SIDED: u32 = 1 << 0; @@ -387,6 +388,14 @@ impl GpuDrivenRenderer { (&self.arena.vertex, &self.arena.index) } + /// The depth-only twin of a draw's vertex buffer, when it has one: a draw + /// from the shared arena reads `geometry_arena::DepthVertex` at the same + /// vertex index (same `base_vertex`, same index range). Anything else + /// (dedicated buffers, immediate batches) has no twin. + pub(crate) fn depth_twin(&self, vertex: &wgpu::Buffer) -> Option<&wgpu::Buffer> { + std::ptr::eq(vertex, &self.arena.vertex).then_some(&self.arena.depth) + } + pub fn upload_static( &mut self, device: &wgpu::Device, diff --git a/native/shared/src/renderer/local_light_shadows.rs b/native/shared/src/renderer/local_light_shadows.rs index 5a4e2831..65b6b25c 100644 --- a/native/shared/src/renderer/local_light_shadows.rs +++ b/native/shared/src/renderer/local_light_shadows.rs @@ -522,10 +522,15 @@ pub(crate) struct PassInputs<'a> { pub queue: &'a wgpu::Queue, pub nodes: &'a [ShadowDrawEntry], pub vbs: &'a [&'a wgpu::Buffer], + /// Per `vbs` entry, its depth-only twin stream if it has one. + pub depth_vbs: &'a [Option<&'a wgpu::Buffer>], pub ibs: &'a [&'a wgpu::Buffer], pub cutout_bgs: &'a [&'a wgpu::BindGroup], pub pipeline: &'a wgpu::RenderPipeline, pub pipeline_cutout: &'a wgpu::RenderPipeline, + /// `pipeline` / `pipeline_cutout` reading the depth twin stream. + pub pipeline_compact: &'a wgpu::RenderPipeline, + pub pipeline_cutout_compact: &'a wgpu::RenderPipeline, pub pipeline_skinned: &'a wgpu::RenderPipeline, pub joint_bind_group: &'a wgpu::BindGroup, pub camera_pos: [f32; 3], @@ -890,21 +895,26 @@ impl LocalLightShadows { } else { 0 }; + // 3 / 4: kinds 0 / 1 drawn from the depth twin stream. + let twin = if kind == 2 { None } else { inputs.depth_vbs[entry.vb_idx] }; + let kind = if twin.is_some() { kind + 3 } else { kind }; if kind != current_kind { pass.set_pipeline(match kind { 1 => inputs.pipeline_cutout, 2 => inputs.pipeline_skinned, + 3 => inputs.pipeline_compact, + 4 => inputs.pipeline_cutout_compact, _ => inputs.pipeline, }); current_kind = kind; } pass.set_bind_group(0, &gpu.draw_bind_group, &[(base + slot * stride) as u32]); - if kind == 1 { + if kind == 1 || kind == 4 { pass.set_bind_group(1, inputs.cutout_bgs[entry.cutout_idx as usize], &[]); } else if kind == 2 { pass.set_bind_group(1, inputs.joint_bind_group, &[]); } - pass.set_vertex_buffer(0, inputs.vbs[entry.vb_idx].slice(..)); + pass.set_vertex_buffer(0, twin.unwrap_or(inputs.vbs[entry.vb_idx]).slice(..)); pass.set_index_buffer( inputs.ibs[entry.ib_idx].slice(..), wgpu::IndexFormat::Uint32, diff --git a/native/shared/src/renderer/shadow_pass.rs b/native/shared/src/renderer/shadow_pass.rs index 565f42e3..593eaadb 100644 --- a/native/shared/src/renderer/shadow_pass.rs +++ b/native/shared/src/renderer/shadow_pass.rs @@ -844,6 +844,17 @@ impl Renderer { &prepared_local_lights, ); + // Each caster's depth-only twin stream, when it is drawn from the + // shared arena (gpu_driven::DepthVertex: 24 bytes a vertex instead + // of 96). Same triangles, same depths; on an integrated GPU the + // forest's vertex fetch is most of what a shadow pass costs. + // BLOOM_SKIP=shadow_compact draws everything from the full stream. + let shadow_depth_vbs: Vec> = if self.dbg_skip("shadow_compact") { + vec![None; shadow_vbs.len()] + } else { + shadow_vbs.iter().map(|vb| self.gpu_driven.depth_twin(vb)).collect() + }; + // Render each cascade. Static casters live in a cached depth // texture ("cached whole-scene shadows") re-rendered only when // the cascade's VP or static content changes; every frame the @@ -951,10 +962,15 @@ impl Renderer { } else { 0 }; + // 3 / 4: kinds 0 / 1 drawn from the depth twin. + let twin = if kind == 2 { None } else { shadow_depth_vbs[entry.vb_idx] }; + let kind = if twin.is_some() { kind + 3 } else { kind }; if kind != cur_kind { shadow_pass.set_pipeline(match kind { 1 => &self.shadow_map.pipeline_cutout, 2 => &self.shadow_map.pipeline_skinned, + 3 => &self.shadow_map.pipeline_compact, + 4 => &self.shadow_map.pipeline_cutout_compact, _ => &self.shadow_map.pipeline, }); cur_kind = kind; @@ -964,7 +980,7 @@ impl Renderer { &self.shadow_map.uniform_bind_group, &[offset], ); - if kind == 1 { + if kind == 1 || kind == 4 { shadow_pass.set_bind_group( 1, cutout_bgs[entry.cutout_idx as usize], @@ -979,7 +995,10 @@ impl Renderer { &[], ); } - shadow_pass.set_vertex_buffer(0, shadow_vbs[entry.vb_idx].slice(..)); + shadow_pass.set_vertex_buffer( + 0, + twin.unwrap_or(shadow_vbs[entry.vb_idx]).slice(..), + ); shadow_pass.set_index_buffer( shadow_ibs[entry.ib_idx].slice(..), wgpu::IndexFormat::Uint32, @@ -1100,10 +1119,15 @@ impl Renderer { } else { 0 }; + // 3 / 4: kinds 0 / 1 drawn from the depth twin. + let twin = if kind == 2 { None } else { shadow_depth_vbs[entry.vb_idx] }; + let kind = if twin.is_some() { kind + 3 } else { kind }; if kind != cur_kind { shadow_pass.set_pipeline(match kind { 1 => &self.shadow_map.pipeline_cutout, 2 => &self.shadow_map.pipeline_skinned, + 3 => &self.shadow_map.pipeline_compact, + 4 => &self.shadow_map.pipeline_cutout_compact, _ => &self.shadow_map.pipeline, }); cur_kind = kind; @@ -1113,7 +1137,7 @@ impl Renderer { &self.shadow_map.uniform_bind_group, &[offset], ); - if kind == 1 { + if kind == 1 || kind == 4 { shadow_pass.set_bind_group( 1, cutout_bgs[entry.cutout_idx as usize], @@ -1130,7 +1154,10 @@ impl Renderer { &[], ); } - shadow_pass.set_vertex_buffer(0, shadow_vbs[entry.vb_idx].slice(..)); + shadow_pass.set_vertex_buffer( + 0, + twin.unwrap_or(shadow_vbs[entry.vb_idx]).slice(..), + ); shadow_pass.set_index_buffer( shadow_ibs[entry.ib_idx].slice(..), wgpu::IndexFormat::Uint32, @@ -1511,10 +1538,13 @@ impl Renderer { queue: &self.queue, nodes: &shadow_nodes, vbs: &shadow_vbs, + depth_vbs: &shadow_depth_vbs, ibs: &shadow_ibs, cutout_bgs: &cutout_bgs, pipeline: &self.shadow_map.pipeline, pipeline_cutout: &self.shadow_map.pipeline_cutout, + pipeline_compact: &self.shadow_map.pipeline_compact, + pipeline_cutout_compact: &self.shadow_map.pipeline_cutout_compact, pipeline_skinned: &self.shadow_map.pipeline_skinned, joint_bind_group: &self.joint_bind_group, camera_pos: self.current_camera_pos, diff --git a/native/shared/src/shadows.rs b/native/shared/src/shadows.rs index c9f1ec4f..b0c198e1 100644 --- a/native/shared/src/shadows.rs +++ b/native/shared/src/shadows.rs @@ -105,6 +105,19 @@ fn vs_shadow(in: ShadowVertexInput) -> @builtin(position) vec4 { let world_pos = shadow_u.model * vec4(p, 1.0); return shadow_u.light_vp * world_pos; } + +// The same caster read from the arena's depth-only twin stream +// (gpu_driven::DepthVertex, 24 bytes instead of 96). Same maths as vs_shadow. +struct ShadowDepthVertexInput { + @location(0) position: vec3, +}; + +@vertex +fn vs_shadow_compact(in: ShadowDepthVertexInput) -> @builtin(position) vec4 { + let p = foliage_wind_local(in.position, shadow_u.model, shadow_u.wind, shadow_u.misc.z, 0.0); + let world_pos = shadow_u.model * vec4(p, 1.0); + return shadow_u.light_vp * world_pos; +} "# ); @@ -201,6 +214,25 @@ fn vs_shadow_cutout(in: ShadowVertexInput) -> VsOut { return o; } +// vs_shadow_cutout reading the arena's depth-only twin stream +// (gpu_driven::DepthVertex): position, uv, vertex alpha. +struct ShadowDepthVertexInput { + @location(0) position: vec3, + @location(1) uv: vec2, + @location(2) alpha: f32, +}; + +@vertex +fn vs_shadow_cutout_compact(in: ShadowDepthVertexInput) -> VsOut { + var o: VsOut; + let p = foliage_wind_local(in.position, shadow_u.model, shadow_u.wind, shadow_u.misc.z, 1.0); + let world_pos = shadow_u.model * vec4(p, 1.0); + o.pos = shadow_u.light_vp * world_pos; + o.uv = in.uv; + o.alpha = in.alpha; + return o; +} + @fragment fn fs_shadow_cutout(in: VsOut) { let uv = vec2( @@ -341,6 +373,11 @@ pub struct ShadowMap { /// Alpha-tested variant for cutout foliage casters. Opaque casters keep /// using `pipeline` (byte-identical to before this was added). pub pipeline_cutout: LazyRenderPipeline, + /// `pipeline` and `pipeline_cutout` for casters drawn from the shared + /// arena's depth-only twin stream (`GpuDriven::depth_twin`): a quarter of + /// the vertex bytes for the same triangles and the same depths. + pub pipeline_compact: LazyRenderPipeline, + pub pipeline_cutout_compact: LazyRenderPipeline, /// Skinning-aware variant for the immediate-mode batch (animated /// characters). Binds the joint-matrix buffer at group 1 and skins /// per-vertex so player/enemies cast a real posed shadow. @@ -780,6 +817,70 @@ impl ShadowMap { }, ); + // The two above, reading the arena's depth-only twin stream. Same + // modules, state and bias; only the vertex entry point and layout differ. + let depth_layout = crate::renderer::gpu_driven::DepthVertex::desc(); + let shadow_depth_state = || wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Less), + stencil: Default::default(), + bias: wgpu::DepthBiasState { + constant: 1, + slope_scale: 1.0, + clamp: 0.0, + }, + }; + let shadow_primitive = || wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Ccw, + cull_mode: None, + ..Default::default() + }; + let pipeline_compact = LazyRenderPipeline::new( + device, + &wgpu::RenderPipelineDescriptor { + label: Some("shadow_pipeline_compact"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_shadow_compact"), + buffers: &[depth_layout.clone()], + compilation_options: Default::default(), + }, + fragment: None, + primitive: shadow_primitive(), + depth_stencil: Some(shadow_depth_state()), + multisample: Default::default(), + multiview_mask: None, + cache: None, + }, + ); + let pipeline_cutout_compact = LazyRenderPipeline::new( + device, + &wgpu::RenderPipelineDescriptor { + label: Some("shadow_pipeline_cutout_compact"), + layout: Some(&cutout_pl_layout), + vertex: wgpu::VertexState { + module: &cutout_shader, + entry_point: Some("vs_shadow_cutout_compact"), + buffers: &[depth_layout], + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &cutout_shader, + entry_point: Some("fs_shadow_cutout"), + targets: &[], + compilation_options: Default::default(), + }), + primitive: shadow_primitive(), + depth_stencil: Some(shadow_depth_state()), + multisample: Default::default(), + multiview_mask: None, + cache: None, + }, + ); + // Skinned (animated-character) shadow pipeline. Group 0 = the shared // shadow uniforms (light_vp + model, dynamic offset); group 1 = the // joint-matrix buffer. Depth-only, same bias as the opaque path. @@ -842,6 +943,8 @@ impl ShadowMap { bind_group, pipeline, pipeline_cutout, + pipeline_compact, + pipeline_cutout_compact, pipeline_skinned, cutout_tex_layout, uniform_buffer, From 069ed823fc530ed3ae0590f17b603fbdce7e2cf9 Mon Sep 17 00:00:00 2001 From: Ralph Kuepper Date: Mon, 16 Nov 2026 19:43:23 +0100 Subject: [PATCH 2/2] perf(planar): crop a horizontal probe to where its water is on screen Water samples the probe at screen_uv + n.xz * 0.08, so only the screen rect of the visible linked surfaces (plus a 0.25 NDC margin) is ever read. For a horizontal plane the mirrored view maps plane points to the same screen position, so the probe passes are scissored to that rect and cull against the cropped frustum. Instanced or unbounded water, and tilted planes, keep the full rect. Unit tests cover rect, planes and scissor. Radeon 760M, High fight: planar_probe_models ~4.1 -> ~3.8 ms; picture unchanged. BLOOM_SKIP=probe_crop disables it. --- native/shared/src/renderer/planar_pass.rs | 70 ++++++- .../shared/src/renderer/planar_reflection.rs | 190 ++++++++++++++++++ 2 files changed, 250 insertions(+), 10 deletions(-) diff --git a/native/shared/src/renderer/planar_pass.rs b/native/shared/src/renderer/planar_pass.rs index 2f6a3f4b..e0f620c3 100644 --- a/native/shared/src/renderer/planar_pass.rs +++ b/native/shared/src/renderer/planar_pass.rs @@ -336,10 +336,23 @@ impl Renderer { // camera half the time, that was most frames. A probe skipped this way // is simply not sampled; the frame the surface comes back into view // renders it before the main pass reads it. - let probe_seen = { + // + // The same walk finds WHERE on screen the probe is read. A surface reads + // its probe at its own screen position (plus a ripple offset), and a + // point on the mirror plane lands on the same screen position in the + // mirrored view as in the real one. So only the screen rectangle of the + // visible surface, grown by PROBE_READ_MARGIN_NDC, is ever sampled: the + // probe culls its draws to that part of the mirrored frustum and + // scissors to it. A river seen as a band across the bottom of the + // screen no longer redraws the whole mirrored forest above the band. + let full_rect = [-1.0_f32, 1.0, -1.0, 1.0]; + let (probe_seen, probe_rect) = { let main_planes = crate::scene::extract_frustum_planes(&self.current_vp_matrix); let ms = &self.material_system; let mut seen = vec![false; probe_count]; + // None = nothing yet; Some(full_rect) once any draw is unbounded. + let mut rect: Vec> = vec![None; probe_count]; + let crop = !self.dbg_skip("probe_crop"); for cmd in ms.commands.iter().chain(ms.translucent_commands.iter()) { let link = (cmd.material as usize) .checked_sub(1) @@ -348,29 +361,57 @@ impl Renderer { Some(p) if p >= 1 && (p as usize) <= probe_count => p as usize - 1, _ => continue, }; - if seen[slot] { + if rect[slot] == Some(full_rect) { continue; } - // Instanced or unknown bounds: assume visible. - let visible = match (cmd.instance, self.model_gpu_cache.get(&cmd.mesh_handle)) { + // Instanced or unknown bounds: visible, anywhere on screen. + let on_screen = match (cmd.instance, self.model_gpu_cache.get(&cmd.mesh_handle)) { (None, Some(Some(meshes))) if cmd.mesh_idx < meshes.len() => { let m = &meshes[cmd.mesh_idx]; let (wmin, wmax) = transform_aabb(&cmd.model, m.local_min, m.local_max); - !(wmin[0] <= wmax[0] - && crate::scene::aabb_outside_frustum(&main_planes, wmin, wmax)) + if wmin[0] > wmax[0] { + Some(full_rect) + } else if crate::scene::aabb_outside_frustum(&main_planes, wmin, wmax) { + None + } else if !crop { + Some(full_rect) + } else { + // Bounds that pass the box test but whose faces all + // clip away still count: be generous, not exact. + Some( + planar_reflection::surface_screen_rect( + &self.current_vp_matrix, + &main_planes, + wmin, + wmax, + ) + .map(|r| { + planar_reflection::grow_screen_rect( + r, + planar_reflection::PROBE_READ_MARGIN_NDC, + ) + }) + .unwrap_or(full_rect), + ) + } } - _ => true, + _ => Some(full_rect), }; - if visible { + if let Some(r) = on_screen { seen[slot] = true; + rect[slot] = Some(match rect[slot] { + None => r, + Some(a) => [a[0].min(r[0]), a[1].max(r[1]), a[2].min(r[2]), a[3].max(r[3])], + }); } } - seen + (seen, rect) }; for i in 0..probe_count { if !probe_seen[i] { continue; } + let read_rect = probe_rect[i].unwrap_or(full_rect); let ( plane_y, normal, @@ -580,7 +621,13 @@ impl Renderer { // append after the cached models in the same slot space — // creation order decides who survives the cap, so games // should create hero geometry before filler (grass). - let mirror_planes = crate::scene::extract_frustum_planes(&mirror_vp); + // Cropped to the screen rectangle the surface reads (see probe_rect). + // Horizontal planes only: surface_screen_rect bounds a surface by + // the top and bottom faces of its box, exact for a level surface. + let read_rect = if normal[1].abs() > 0.999 { read_rect } else { full_rect }; + let mirror_planes = planar_reflection::cropped_frustum_planes(&mirror_vp, read_rect); + let (sc_x, sc_y, sc_w, sc_h) = + planar_reflection::screen_rect_scissor(read_rect, probe_res); // Projected-size cull. The probe is small (512 px in the shooter) and // the water shows it rippled, yet every draw the mirrored frustum can // see used to be drawn at full detail: on an integrated GPU the forest @@ -743,6 +790,8 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); + // Outside the read rectangle the clear stays: nothing samples it. + pass.set_scissor_rect(sc_x, sc_y, sc_w, sc_h); mat_sys.dispatch_with_view( &mut pass, view_bg, @@ -812,6 +861,7 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); + pass.set_scissor_rect(sc_x, sc_y, sc_w, sc_h); if let (Some(rp), Some(rmbg), Some(rlbg)) = (refl_pipeline, refl_model_bg, refl_light_bg) { diff --git a/native/shared/src/renderer/planar_reflection.rs b/native/shared/src/renderer/planar_reflection.rs index bb3bcf65..fa31d8f8 100644 --- a/native/shared/src/renderer/planar_reflection.rs +++ b/native/shared/src/renderer/planar_reflection.rs @@ -327,6 +327,121 @@ pub fn oblique_proj(proj: [[f32; 4]; 4], plane_eye_space: [f32; 4]) -> [[f32; 4] out } +/// How far (in NDC, both axes) a surface may read its probe away from its own +/// screen position. The water shader offsets its lookup by its ripple normal, +/// `screen_uv + n.xz * 0.08`: at most 0.08 in UV, 0.16 in NDC. A little more, +/// so a surface that ripples harder does not read past the drawn region. +pub const PROBE_READ_MARGIN_NDC: f32 = 0.25; + +/// Clip a convex polygon against one plane (`p · x + d >= 0` is kept). +fn clip_polygon(poly: &[[f32; 3]], plane: [f32; 4]) -> Vec<[f32; 3]> { + let side = |v: [f32; 3]| plane[0] * v[0] + plane[1] * v[1] + plane[2] * v[2] + plane[3]; + let mut out = Vec::with_capacity(poly.len() + 2); + for i in 0..poly.len() { + let a = poly[i]; + let b = poly[(i + 1) % poly.len()]; + let (da, db) = (side(a), side(b)); + if da >= 0.0 { + out.push(a); + } + if (da >= 0.0) != (db >= 0.0) { + let t = da / (da - db); + out.push([ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + a[2] + (b[2] - a[2]) * t, + ]); + } + } + out +} + +/// The NDC rectangle `[x0, x1, y0, y1]` a horizontal surface with world bounds +/// `wmin..wmax` covers on screen, clipped to the camera frustum, or `None` when +/// none of it is in view. The bounds' top and bottom faces are both projected, +/// so a surface displaced vertically (waves) stays inside the rectangle. +pub fn surface_screen_rect( + vp: &[[f32; 4]; 4], + planes: &[[f32; 4]; 6], + wmin: [f32; 3], + wmax: [f32; 3], +) -> Option<[f32; 4]> { + let mut rect = [f32::MAX, f32::MIN, f32::MAX, f32::MIN]; + let mut any = false; + for y in [wmin[1], wmax[1]] { + let mut poly = vec![ + [wmin[0], y, wmin[2]], + [wmax[0], y, wmin[2]], + [wmax[0], y, wmax[2]], + [wmin[0], y, wmax[2]], + ]; + for p in planes.iter() { + poly = clip_polygon(&poly, *p); + if poly.is_empty() { + break; + } + } + for v in &poly { + let c = mat4_mul_vec4(vp, &[v[0], v[1], v[2], 1.0]); + if c[3] <= 1e-6 { + // On the eye plane after clipping: cannot bound it, so + // claim the whole screen rather than guess. + return Some([-1.0, 1.0, -1.0, 1.0]); + } + let (x, y) = (c[0] / c[3], c[1] / c[3]); + rect = [rect[0].min(x), rect[1].max(x), rect[2].min(y), rect[3].max(y)]; + any = true; + } + } + any.then_some(rect) +} + +/// Grow a screen rectangle by `margin` on every side, clamped to the screen. +pub fn grow_screen_rect(r: [f32; 4], margin: f32) -> [f32; 4] { + [ + (r[0] - margin).max(-1.0), + (r[1] + margin).min(1.0), + (r[2] - margin).max(-1.0), + (r[3] + margin).min(1.0), + ] +} + +/// Frustum planes for the part of `vp`'s view inside the NDC rectangle +/// `[x0, x1, y0, y1]`: the same six planes `extract_frustum_planes` returns, +/// with the four side planes moved in. A full rectangle gives exactly the +/// plain frustum. +pub fn cropped_frustum_planes(vp: &[[f32; 4]; 4], r: [f32; 4]) -> [[f32; 4]; 6] { + let row = |i: usize| [vp[0][i], vp[1][i], vp[2][i], vp[3][i]]; + let (r0, r1, r2, r3) = (row(0), row(1), row(2), row(3)); + let comb = |a: [f32; 4], sa: f32, b: [f32; 4], sb: f32| { + [ + a[0] * sa + b[0] * sb, + a[1] * sa + b[1] * sb, + a[2] * sa + b[2] * sb, + a[3] * sa + b[3] * sb, + ] + }; + [ + comb(r0, 1.0, r3, -r[0]), // x >= x0 * w + comb(r3, r[1], r0, -1.0), // x <= x1 * w + comb(r1, 1.0, r3, -r[2]), // y >= y0 * w + comb(r3, r[3], r1, -1.0), // y <= y1 * w + r2, + comb(r3, 1.0, r2, -1.0), + ] +} + +/// The scissor rectangle `(x, y, w, h)` in texels of a `res`-square probe for +/// an NDC rectangle (NDC y up, texel y down). Never empty. +pub fn screen_rect_scissor(r: [f32; 4], res: u32) -> (u32, u32, u32, u32) { + let f = res as f32; + let x0 = (((r[0] + 1.0) * 0.5 * f).floor().max(0.0) as u32).min(res - 1); + let x1 = (((r[1] + 1.0) * 0.5 * f).ceil() as u32).clamp(x0 + 1, res); + let y0 = (((1.0 - r[3]) * 0.5 * f).floor().max(0.0) as u32).min(res - 1); + let y1 = (((1.0 - r[2]) * 0.5 * f).ceil() as u32).clamp(y0 + 1, res); + (x0, y0, x1 - x0, y1 - y0) +} + fn normalise(v: [f32; 3]) -> [f32; 3] { let len_sq = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; if len_sq < 1e-10 { @@ -390,6 +505,81 @@ mod tests { assert!((helper_out[2] - mat_out[2]).abs() < 1e-5); } + fn test_vp() -> [[f32; 4]; 4] { + use crate::renderer::util::{mat4_look_at, mat4_perspective}; + let view = mat4_look_at([0.0, 3.0, 10.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]); + mat4_multiply(mat4_perspective(1.2, 16.0 / 9.0, 0.1, 500.0), view) + } + + fn ndc(vp: &[[f32; 4]; 4], p: [f32; 3]) -> [f32; 2] { + let c = mat4_mul_vec4(vp, &[p[0], p[1], p[2], 1.0]); + [c[0] / c[3], c[1] / c[3]] + } + + /// A surface wholly in view: the rectangle is the bounds of its projected + /// corners. One wholly behind the camera: no rectangle. + #[test] + fn surface_rect_bounds_the_visible_surface() { + let vp = test_vp(); + let planes = crate::scene::extract_frustum_planes(&vp); + let (wmin, wmax) = ([-1.0, 0.0, -1.0], [1.0, 0.0, 1.0]); + let r = surface_screen_rect(&vp, &planes, wmin, wmax).expect("in view"); + for x in [wmin[0], wmax[0]] { + for z in [wmin[2], wmax[2]] { + let p = ndc(&vp, [x, 0.0, z]); + assert!(p[0] >= r[0] - 1e-4 && p[0] <= r[1] + 1e-4); + assert!(p[1] >= r[2] - 1e-4 && p[1] <= r[3] + 1e-4); + } + } + assert!(r[1] - r[0] < 1.0, "a 2 m patch 10 m away is not half the screen: {r:?}"); + assert!(surface_screen_rect(&vp, &planes, [-1.0, 0.0, 20.0], [1.0, 0.0, 22.0]).is_none()); + } + + /// A surface far larger than the view (a river through the whole arena) is + /// clipped to the frustum, not projected from corners behind the eye. + #[test] + fn surface_rect_clips_a_huge_surface_to_the_screen() { + let vp = test_vp(); + let planes = crate::scene::extract_frustum_planes(&vp); + let r = surface_screen_rect(&vp, &planes, [-500.0, 0.0, -500.0], [500.0, 0.0, 500.0]) + .expect("in view"); + for v in r { + assert!((-1.0001..=1.0001).contains(&v), "{r:?}"); + } + assert!(r[1] - r[0] > 1.9, "the ground plane spans the screen width: {r:?}"); + assert!(r[2] < -0.99, "and reaches the bottom edge: {r:?}"); + } + + /// The full rectangle crops nothing; a crop rejects what projects outside + /// it and keeps what projects inside. + #[test] + fn cropped_planes_cull_by_screen_rect() { + let vp = test_vp(); + let full = cropped_frustum_planes(&vp, [-1.0, 1.0, -1.0, 1.0]); + let plain = crate::scene::extract_frustum_planes(&vp); + for (a, b) in full.iter().zip(plain.iter()) { + for k in 0..4 { + assert!((a[k] - b[k]).abs() < 1e-5); + } + } + let left_half = cropped_frustum_planes(&vp, [-1.0, 0.0, -1.0, 1.0]); + let left = ([-3.0, -0.2, -0.2], [-2.6, 0.2, 0.2]); + let right = ([2.6, -0.2, -0.2], [3.0, 0.2, 0.2]); + assert!(!crate::scene::aabb_outside_frustum(&left_half, left.0, left.1)); + assert!(crate::scene::aabb_outside_frustum(&left_half, right.0, right.1)); + assert!(!crate::scene::aabb_outside_frustum(&plain, right.0, right.1)); + } + + #[test] + fn scissor_covers_the_rect_and_is_never_empty() { + assert_eq!(screen_rect_scissor([-1.0, 1.0, -1.0, 1.0], 512), (0, 0, 512, 512)); + // Lower-left quarter: NDC y down = texel y up. + assert_eq!(screen_rect_scissor([-1.0, 0.0, -1.0, 0.0], 512), (0, 256, 256, 256)); + let (_, _, w, h) = screen_rect_scissor([0.3, 0.3, 0.3, 0.3], 512); + assert!(w >= 1 && h >= 1); + assert_eq!(grow_screen_rect([-0.9, 0.0, 0.5, 0.95], 0.25), [-1.0, 0.25, 0.25, 1.0]); + } + /// Reflection is its own inverse — applying it twice returns /// the original point. #[test]