use crcbl_shaders::cull::{
ENTRY_FACE_SHIFT, ENTRY_OCCLUDED, ENTRY_RESCUED, FACE_COUNT, FACE_PLANES,
OCCLUSION_DEPTH_SLACK, OCCLUSION_GUARD_TEXELS, PROJECTION_LIMIT,
};
use crcbl_shaders::mesh::{GpuInstance, GpuMesh};
use glam::{Mat3, Mat4, Vec3, Vec4};
use super::Frustum;
use crate::occlusion_cull::{level_extent, levels_for};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reduction {
Farthest,
Nearest,
}
#[derive(Clone, Debug, PartialEq)]
pub struct DepthPyramid {
extent: (u32, u32),
levels: Vec<Vec<f32>>,
}
impl DepthPyramid {
#[must_use]
pub fn reduce(depth: &[f32], extent: (u32, u32), reduction: Reduction) -> Self {
assert_eq!(
depth.len(),
extent.0 as usize * extent.1 as usize,
"a depth image of {extent:?} holds that many texels"
);
let combine = |a: f32, b: f32| match reduction {
Reduction::Farthest => a.min(b),
Reduction::Nearest => a.max(b),
};
let mut levels: Vec<Vec<f32>> = Vec::new();
for level in 1..=levels_for(extent) {
let (source_width, source_height) = level_extent(extent, level - 1);
let (width, height) = level_extent(extent, level);
let source: &[f32] = levels.last().map_or(depth, Vec::as_slice);
let load = |x: i64, y: i64| {
let x = x.clamp(0, i64::from(source_width) - 1) as usize;
let y = y.clamp(0, i64::from(source_height) - 1) as usize;
source[y * source_width as usize + x]
};
let odd_x = source_width & 1 == 1;
let odd_y = source_height & 1 == 1;
let mut out = Vec::with_capacity(width as usize * height as usize);
for y in 0..i64::from(height) {
for x in 0..i64::from(width) {
let (bx, by) = (x * 2, y * 2);
let mut value = load(bx, by);
value = combine(value, load(bx + 1, by));
value = combine(value, load(bx, by + 1));
value = combine(value, load(bx + 1, by + 1));
if odd_x {
value = combine(value, load(bx + 2, by));
value = combine(value, load(bx + 2, by + 1));
}
if odd_y {
value = combine(value, load(bx, by + 2));
value = combine(value, load(bx + 1, by + 2));
}
if odd_x && odd_y {
value = combine(value, load(bx + 2, by + 2));
}
out.push(value);
}
}
levels.push(out);
}
Self { extent, levels }
}
#[must_use]
pub fn from_levels(extent: (u32, u32), levels: Vec<Vec<f32>>) -> Self {
assert_eq!(levels.len(), levels_for(extent) as usize, "a whole chain");
for (index, level) in levels.iter().enumerate() {
let (width, height) = level_extent(extent, index as u32 + 1);
assert_eq!(
level.len(),
width as usize * height as usize,
"level {}",
index + 1
);
}
Self { extent, levels }
}
#[must_use]
pub fn reduce_level(source: &[f32], extent: (u32, u32), reduction: Reduction) -> Vec<f32> {
let chain = Self::reduce(source, extent, reduction);
chain.levels.into_iter().next().unwrap_or_default()
}
#[must_use]
pub const fn extent(&self) -> (u32, u32) {
self.extent
}
#[must_use]
pub fn levels(&self) -> u32 {
u32::try_from(self.levels.len()).unwrap_or(u32::MAX)
}
#[must_use]
pub fn level(&self, level: u32) -> &[f32] {
assert!(
level >= 1 && level <= self.levels(),
"level {level} of a {}-level pyramid",
self.levels()
);
&self.levels[level as usize - 1]
}
fn load(&self, level: u32, x: u32, y: u32) -> f32 {
let width = level_extent(self.extent, level).0;
self.levels[level as usize - 1][y as usize * width as usize + x as usize]
}
}
#[must_use]
pub fn world_box(instance: &GpuInstance, mesh: &GpuMesh) -> Option<(Vec3, Vec3)> {
let (min, max) = instance.cull_bounds(mesh)?;
let min = Vec3::from_array(min);
let max = Vec3::from_array(max);
let local_center = (max + min) * 0.5;
let local_extent = (max - min) * 0.5;
let transform = Mat4::from_cols_array(&instance.transform);
let basis = Mat3::from_mat4(transform);
let absolute = Mat3::from_cols(basis.x_axis.abs(), basis.y_axis.abs(), basis.z_axis.abs());
Some((
transform.transform_point3(local_center),
absolute * local_extent,
))
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScreenBounds {
pub min: [f32; 2],
pub max: [f32; 2],
pub nearest: f32,
}
#[must_use]
pub fn project_box(
view_projection: Mat4,
center: Vec3,
extent: Vec3,
target: (u32, u32),
) -> Option<ScreenBounds> {
let (width, height) = (target.0 as f32, target.1 as f32);
let mut bounds = ScreenBounds {
min: [PROJECTION_LIMIT; 2],
max: [-PROJECTION_LIMIT; 2],
nearest: 0.0,
};
for corner in 0..8u32 {
let side = Vec3::new(
if corner & 1 != 0 { 1.0 } else { -1.0 },
if corner & 2 != 0 { 1.0 } else { -1.0 },
if corner & 4 != 0 { 1.0 } else { -1.0 },
);
let clip = view_projection * (center + side * extent).extend(1.0);
let in_front = clip.w > 0.0;
if !in_front {
return None;
}
let depth = clip.z / clip.w;
let x = (clip.x / clip.w * 0.5 + 0.5) * width;
let y = (0.5 - clip.y / clip.w * 0.5) * height;
let behind_near = depth <= 1.0;
let on_the_page = x.abs() < PROJECTION_LIMIT && y.abs() < PROJECTION_LIMIT;
if !behind_near || !on_the_page {
return None;
}
bounds.min = [bounds.min[0].min(x), bounds.min[1].min(y)];
bounds.max = [bounds.max[0].max(x), bounds.max[1].max(y)];
bounds.nearest = bounds.nearest.max(depth);
}
Some(bounds)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PyramidFootprint {
pub level: u32,
pub columns: (u32, u32),
pub rows: (u32, u32),
}
#[must_use]
pub fn footprint(
bounds: &ScreenBounds,
target: (u32, u32),
levels: u32,
) -> Option<PyramidFootprint> {
let (width, height) = (
i32::try_from(target.0).unwrap_or(i32::MAX),
i32::try_from(target.1).unwrap_or(i32::MAX),
);
let x0 = bounds.min[0].floor() as i32 - OCCLUSION_GUARD_TEXELS;
let y0 = bounds.min[1].floor() as i32 - OCCLUSION_GUARD_TEXELS;
let x1 = bounds.max[0].floor() as i32 + OCCLUSION_GUARD_TEXELS;
let y1 = bounds.max[1].floor() as i32 + OCCLUSION_GUARD_TEXELS;
if x1 < 0 || y1 < 0 || x0 >= width || y0 >= height {
return None;
}
let left = x0.max(0) as u32;
let top = y0.max(0) as u32;
let right = x1.min(width - 1) as u32;
let bottom = y1.min(height - 1) as u32;
let mut level = 1;
while level < levels
&& ((right >> level) - (left >> level) > 1 || (bottom >> level) - (top >> level) > 1)
{
level += 1;
}
let level_width = (target.0 >> level).max(1);
let level_height = (target.1 >> level).max(1);
Some(PyramidFootprint {
level,
columns: (
(left >> level).min(level_width - 1),
(right >> level).min(level_width - 1),
),
rows: (
(top >> level).min(level_height - 1),
(bottom >> level).min(level_height - 1),
),
})
}
#[must_use]
pub fn occluded(view_projection: Mat4, center: Vec3, extent: Vec3, pyramid: &DepthPyramid) -> bool {
if pyramid.levels() == 0 {
return false;
}
let Some(bounds) = project_box(view_projection, center, extent, pyramid.extent()) else {
return false;
};
let Some(footprint) = footprint(&bounds, pyramid.extent(), pyramid.levels()) else {
return false;
};
let mut farthest = 1.0f32;
for y in footprint.rows.0..=footprint.rows.1 {
for x in footprint.columns.0..=footprint.columns.1 {
farthest = farthest.min(pyramid.load(footprint.level, x, y));
}
}
bounds.nearest * (1.0 + OCCLUSION_DEPTH_SLACK) < farthest
}
#[must_use]
pub fn small_feature(
view_projection: Mat4,
center: Vec3,
extent: Vec3,
target: (u32, u32),
pixels: f32,
) -> bool {
project_box(view_projection, center, extent, target).is_some_and(|bounds| {
(bounds.max[0] - bounds.min[0]).max(bounds.max[1] - bounds.min[1]) < pixels
})
}
#[derive(Clone, Copy, Debug)]
pub struct EarlyInputs<'a> {
pub view_projection: Mat4,
pub previous_view_projection: Mat4,
pub history: Option<&'a DepthPyramid>,
pub target: (u32, u32),
pub small_feature_pixels: Option<f32>,
}
#[must_use]
pub fn early_entries(
frustum: &Frustum,
instances: &[GpuInstance],
meshes: &[GpuMesh],
hidden_view: u32,
inputs: &EarlyInputs<'_>,
) -> Vec<u32> {
let mut entries = Vec::new();
for index in super::visible_instances(frustum, instances, meshes, hidden_view) {
let instance = &instances[index as usize];
let Some((center, extent)) = world_box(instance, &meshes[instance.mesh as usize]) else {
entries.push(index);
continue;
};
if inputs.small_feature_pixels.is_some_and(|pixels| {
small_feature(
inputs.view_projection,
center,
extent,
inputs.target,
pixels,
)
}) {
continue;
}
let hidden = inputs.history.is_some_and(|pyramid| {
occluded(inputs.previous_view_projection, center, extent, pyramid)
});
entries.push(if hidden {
index | ENTRY_OCCLUDED
} else {
index
});
}
entries
}
#[must_use]
pub fn late_entry(
entry: u32,
instances: &[GpuInstance],
meshes: &[GpuMesh],
view_projection: Mat4,
pyramid: &DepthPyramid,
) -> u32 {
if entry & ENTRY_OCCLUDED == 0 {
return entry;
}
let instance = &instances[(entry & crcbl_shaders::cull::ENTRY_INDEX_MASK) as usize];
let hidden = world_box(instance, &meshes[instance.mesh as usize])
.is_some_and(|(center, extent)| occluded(view_projection, center, extent, pyramid));
if hidden { entry } else { entry | ENTRY_RESCUED }
}
pub type FacePlanes = [[Vec4; FACE_PLANES]; FACE_COUNT];
#[must_use]
pub fn face_planes(view_projections: &[Mat4; FACE_COUNT]) -> FacePlanes {
view_projections.map(|matrix| {
let planes = Frustum::from_view_projection(matrix).planes;
[planes[0], planes[1], planes[2], planes[3]]
})
}
#[must_use]
pub fn face_tags(faces: &FacePlanes, center: Vec3, extent: Vec3) -> u32 {
let mut tags = 0;
for (face, planes) in faces.iter().enumerate() {
let inside = planes.iter().all(|plane| {
let normal = plane.truncate();
let radius = normal.abs().dot(extent);
normal.dot(center) + plane.w >= -radius
});
if inside {
tags |= 1 << (ENTRY_FACE_SHIFT as usize + face);
}
}
tags
}
#[must_use]
pub fn face_entries(
frustum: &Frustum,
faces: &FacePlanes,
instances: &[GpuInstance],
meshes: &[GpuMesh],
) -> Vec<u32> {
super::visible_instances(frustum, instances, meshes, 0)
.into_iter()
.map(|index| {
let instance = &instances[index as usize];
world_box(instance, &meshes[instance.mesh as usize]).map_or(
index | (((1 << FACE_COUNT) - 1) << ENTRY_FACE_SHIFT),
|(center, extent)| index | face_tags(faces, center, extent),
)
})
.collect()
}
#[cfg(test)]
mod tests;