1use crcbl_shaders::cull::{
41 ENTRY_FACE_SHIFT, ENTRY_OCCLUDED, ENTRY_RESCUED, FACE_COUNT, FACE_PLANES,
42 OCCLUSION_DEPTH_SLACK, OCCLUSION_GUARD_TEXELS, PROJECTION_LIMIT,
43};
44use crcbl_shaders::mesh::{GpuInstance, GpuMesh};
45use glam::{Mat3, Mat4, Vec3, Vec4};
46
47use super::Frustum;
48use crate::occlusion_cull::{level_extent, levels_for};
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum Reduction {
53 Farthest,
56 Nearest,
59}
60
61#[derive(Clone, Debug, PartialEq)]
64pub struct DepthPyramid {
65 extent: (u32, u32),
66 levels: Vec<Vec<f32>>,
68}
69
70impl DepthPyramid {
71 #[must_use]
83 pub fn reduce(depth: &[f32], extent: (u32, u32), reduction: Reduction) -> Self {
84 assert_eq!(
85 depth.len(),
86 extent.0 as usize * extent.1 as usize,
87 "a depth image of {extent:?} holds that many texels"
88 );
89 let combine = |a: f32, b: f32| match reduction {
90 Reduction::Farthest => a.min(b),
91 Reduction::Nearest => a.max(b),
92 };
93 let mut levels: Vec<Vec<f32>> = Vec::new();
94 for level in 1..=levels_for(extent) {
95 let (source_width, source_height) = level_extent(extent, level - 1);
96 let (width, height) = level_extent(extent, level);
97 let source: &[f32] = levels.last().map_or(depth, Vec::as_slice);
98 let load = |x: i64, y: i64| {
99 let x = x.clamp(0, i64::from(source_width) - 1) as usize;
100 let y = y.clamp(0, i64::from(source_height) - 1) as usize;
101 source[y * source_width as usize + x]
102 };
103 let odd_x = source_width & 1 == 1;
104 let odd_y = source_height & 1 == 1;
105 let mut out = Vec::with_capacity(width as usize * height as usize);
106 for y in 0..i64::from(height) {
107 for x in 0..i64::from(width) {
108 let (bx, by) = (x * 2, y * 2);
109 let mut value = load(bx, by);
110 value = combine(value, load(bx + 1, by));
111 value = combine(value, load(bx, by + 1));
112 value = combine(value, load(bx + 1, by + 1));
113 if odd_x {
114 value = combine(value, load(bx + 2, by));
115 value = combine(value, load(bx + 2, by + 1));
116 }
117 if odd_y {
118 value = combine(value, load(bx, by + 2));
119 value = combine(value, load(bx + 1, by + 2));
120 }
121 if odd_x && odd_y {
122 value = combine(value, load(bx + 2, by + 2));
123 }
124 out.push(value);
125 }
126 }
127 levels.push(out);
128 }
129 Self { extent, levels }
130 }
131
132 #[must_use]
140 pub fn from_levels(extent: (u32, u32), levels: Vec<Vec<f32>>) -> Self {
141 assert_eq!(levels.len(), levels_for(extent) as usize, "a whole chain");
142 for (index, level) in levels.iter().enumerate() {
143 let (width, height) = level_extent(extent, index as u32 + 1);
144 assert_eq!(
145 level.len(),
146 width as usize * height as usize,
147 "level {}",
148 index + 1
149 );
150 }
151 Self { extent, levels }
152 }
153
154 #[must_use]
158 pub fn reduce_level(source: &[f32], extent: (u32, u32), reduction: Reduction) -> Vec<f32> {
159 let chain = Self::reduce(source, extent, reduction);
160 chain.levels.into_iter().next().unwrap_or_default()
161 }
162
163 #[must_use]
165 pub const fn extent(&self) -> (u32, u32) {
166 self.extent
167 }
168
169 #[must_use]
171 pub fn levels(&self) -> u32 {
172 u32::try_from(self.levels.len()).unwrap_or(u32::MAX)
173 }
174
175 #[must_use]
181 pub fn level(&self, level: u32) -> &[f32] {
182 assert!(
183 level >= 1 && level <= self.levels(),
184 "level {level} of a {}-level pyramid",
185 self.levels()
186 );
187 &self.levels[level as usize - 1]
188 }
189
190 fn load(&self, level: u32, x: u32, y: u32) -> f32 {
192 let width = level_extent(self.extent, level).0;
193 self.levels[level as usize - 1][y as usize * width as usize + x as usize]
194 }
195}
196
197#[must_use]
201pub fn world_box(instance: &GpuInstance, mesh: &GpuMesh) -> (Vec3, Vec3) {
202 let min = Vec3::from_array(mesh.bounds_min);
203 let max = Vec3::from_array(mesh.bounds_max);
204 let local_center = (max + min) * 0.5;
205 let local_extent = (max - min) * 0.5;
206 let transform = Mat4::from_cols_array(&instance.transform);
207 let basis = Mat3::from_mat4(transform);
208 let absolute = Mat3::from_cols(basis.x_axis.abs(), basis.y_axis.abs(), basis.z_axis.abs());
209 (
210 transform.transform_point3(local_center),
211 absolute * local_extent,
212 )
213}
214
215#[derive(Clone, Copy, Debug, PartialEq)]
218pub struct ScreenBounds {
219 pub min: [f32; 2],
221 pub max: [f32; 2],
223 pub nearest: f32,
225}
226
227#[must_use]
234pub fn project_box(
235 view_projection: Mat4,
236 center: Vec3,
237 extent: Vec3,
238 target: (u32, u32),
239) -> Option<ScreenBounds> {
240 let (width, height) = (target.0 as f32, target.1 as f32);
241 let mut bounds = ScreenBounds {
242 min: [PROJECTION_LIMIT; 2],
243 max: [-PROJECTION_LIMIT; 2],
244 nearest: 0.0,
245 };
246 for corner in 0..8u32 {
247 let side = Vec3::new(
248 if corner & 1 != 0 { 1.0 } else { -1.0 },
249 if corner & 2 != 0 { 1.0 } else { -1.0 },
250 if corner & 4 != 0 { 1.0 } else { -1.0 },
251 );
252 let clip = view_projection * (center + side * extent).extend(1.0);
253 let in_front = clip.w > 0.0;
256 if !in_front {
257 return None;
258 }
259 let depth = clip.z / clip.w;
260 let x = (clip.x / clip.w * 0.5 + 0.5) * width;
261 let y = (0.5 - clip.y / clip.w * 0.5) * height;
262 let behind_near = depth <= 1.0;
263 let on_the_page = x.abs() < PROJECTION_LIMIT && y.abs() < PROJECTION_LIMIT;
264 if !behind_near || !on_the_page {
265 return None;
266 }
267 bounds.min = [bounds.min[0].min(x), bounds.min[1].min(y)];
268 bounds.max = [bounds.max[0].max(x), bounds.max[1].max(y)];
269 bounds.nearest = bounds.nearest.max(depth);
270 }
271 Some(bounds)
272}
273
274#[derive(Clone, Copy, Debug, PartialEq, Eq)]
280pub struct PyramidFootprint {
281 pub level: u32,
283 pub columns: (u32, u32),
285 pub rows: (u32, u32),
287}
288
289#[must_use]
297pub fn footprint(
298 bounds: &ScreenBounds,
299 target: (u32, u32),
300 levels: u32,
301) -> Option<PyramidFootprint> {
302 let (width, height) = (
303 i32::try_from(target.0).unwrap_or(i32::MAX),
304 i32::try_from(target.1).unwrap_or(i32::MAX),
305 );
306 let x0 = bounds.min[0].floor() as i32 - OCCLUSION_GUARD_TEXELS;
309 let y0 = bounds.min[1].floor() as i32 - OCCLUSION_GUARD_TEXELS;
310 let x1 = bounds.max[0].floor() as i32 + OCCLUSION_GUARD_TEXELS;
311 let y1 = bounds.max[1].floor() as i32 + OCCLUSION_GUARD_TEXELS;
312 if x1 < 0 || y1 < 0 || x0 >= width || y0 >= height {
313 return None;
314 }
315 let left = x0.max(0) as u32;
316 let top = y0.max(0) as u32;
317 let right = x1.min(width - 1) as u32;
318 let bottom = y1.min(height - 1) as u32;
319 let mut level = 1;
320 while level < levels
321 && ((right >> level) - (left >> level) > 1 || (bottom >> level) - (top >> level) > 1)
322 {
323 level += 1;
324 }
325 let level_width = (target.0 >> level).max(1);
326 let level_height = (target.1 >> level).max(1);
327 Some(PyramidFootprint {
328 level,
329 columns: (
330 (left >> level).min(level_width - 1),
331 (right >> level).min(level_width - 1),
332 ),
333 rows: (
334 (top >> level).min(level_height - 1),
335 (bottom >> level).min(level_height - 1),
336 ),
337 })
338}
339
340#[must_use]
349pub fn occluded(view_projection: Mat4, center: Vec3, extent: Vec3, pyramid: &DepthPyramid) -> bool {
350 if pyramid.levels() == 0 {
351 return false;
352 }
353 let Some(bounds) = project_box(view_projection, center, extent, pyramid.extent()) else {
354 return false;
355 };
356 let Some(footprint) = footprint(&bounds, pyramid.extent(), pyramid.levels()) else {
357 return false;
358 };
359 let mut farthest = 1.0f32;
360 for y in footprint.rows.0..=footprint.rows.1 {
361 for x in footprint.columns.0..=footprint.columns.1 {
362 farthest = farthest.min(pyramid.load(footprint.level, x, y));
363 }
364 }
365 bounds.nearest * (1.0 + OCCLUSION_DEPTH_SLACK) < farthest
366}
367
368#[must_use]
372pub fn small_feature(
373 view_projection: Mat4,
374 center: Vec3,
375 extent: Vec3,
376 target: (u32, u32),
377 pixels: f32,
378) -> bool {
379 project_box(view_projection, center, extent, target).is_some_and(|bounds| {
380 (bounds.max[0] - bounds.min[0]).max(bounds.max[1] - bounds.min[1]) < pixels
381 })
382}
383
384#[derive(Clone, Copy, Debug)]
386pub struct EarlyInputs<'a> {
387 pub view_projection: Mat4,
389 pub previous_view_projection: Mat4,
391 pub history: Option<&'a DepthPyramid>,
394 pub target: (u32, u32),
396 pub small_feature_pixels: Option<f32>,
398}
399
400#[must_use]
408pub fn early_entries(
409 frustum: &Frustum,
410 instances: &[GpuInstance],
411 meshes: &[GpuMesh],
412 hidden_view: u32,
413 inputs: &EarlyInputs<'_>,
414) -> Vec<u32> {
415 let mut entries = Vec::new();
416 for index in super::visible_instances(frustum, instances, meshes, hidden_view) {
417 let instance = &instances[index as usize];
418 if instance.flags & GpuInstance::BASE_VERTEX_OVERRIDE != 0 {
419 entries.push(index);
420 continue;
421 }
422 let mesh = &meshes[instance.mesh as usize];
423 let (center, extent) = world_box(instance, mesh);
424 if inputs.small_feature_pixels.is_some_and(|pixels| {
425 small_feature(
426 inputs.view_projection,
427 center,
428 extent,
429 inputs.target,
430 pixels,
431 )
432 }) {
433 continue;
434 }
435 let hidden = inputs.history.is_some_and(|pyramid| {
436 occluded(inputs.previous_view_projection, center, extent, pyramid)
437 });
438 entries.push(if hidden {
439 index | ENTRY_OCCLUDED
440 } else {
441 index
442 });
443 }
444 entries
445}
446
447#[must_use]
451pub fn late_entry(
452 entry: u32,
453 instances: &[GpuInstance],
454 meshes: &[GpuMesh],
455 view_projection: Mat4,
456 pyramid: &DepthPyramid,
457) -> u32 {
458 if entry & ENTRY_OCCLUDED == 0 {
459 return entry;
460 }
461 let instance = &instances[(entry & crcbl_shaders::cull::ENTRY_INDEX_MASK) as usize];
462 let (center, extent) = world_box(instance, &meshes[instance.mesh as usize]);
463 if occluded(view_projection, center, extent, pyramid) {
464 entry
465 } else {
466 entry | ENTRY_RESCUED
467 }
468}
469
470pub type FacePlanes = [[Vec4; FACE_PLANES]; FACE_COUNT];
473
474#[must_use]
483pub fn face_planes(view_projections: &[Mat4; FACE_COUNT]) -> FacePlanes {
484 view_projections.map(|matrix| {
485 let planes = Frustum::from_view_projection(matrix).planes;
486 [planes[0], planes[1], planes[2], planes[3]]
487 })
488}
489
490#[must_use]
494pub fn face_tags(faces: &FacePlanes, center: Vec3, extent: Vec3) -> u32 {
495 let mut tags = 0;
496 for (face, planes) in faces.iter().enumerate() {
497 let inside = planes.iter().all(|plane| {
498 let normal = plane.truncate();
499 let radius = normal.abs().dot(extent);
500 normal.dot(center) + plane.w >= -radius
501 });
502 if inside {
503 tags |= 1 << (ENTRY_FACE_SHIFT as usize + face);
504 }
505 }
506 tags
507}
508
509#[must_use]
513pub fn face_entries(
514 frustum: &Frustum,
515 faces: &FacePlanes,
516 instances: &[GpuInstance],
517 meshes: &[GpuMesh],
518) -> Vec<u32> {
519 super::visible_instances(frustum, instances, meshes, 0)
520 .into_iter()
521 .map(|index| {
522 let instance = &instances[index as usize];
523 if instance.flags & GpuInstance::BASE_VERTEX_OVERRIDE != 0 {
524 return index | (((1 << FACE_COUNT) - 1) << ENTRY_FACE_SHIFT);
525 }
526 let (center, extent) = world_box(instance, &meshes[instance.mesh as usize]);
527 index | face_tags(faces, center, extent)
528 })
529 .collect()
530}
531
532#[cfg(test)]
533mod tests;