use crcbl_shaders::mesh::{self, MeshVertex};
use glam::Mat4;
use crate::scene::{Geometry, SceneDesc};
crcbl_console::convar! {
pub static r_probe_visibility: bool = true;
}
pub(crate) fn enabled() -> bool {
r_probe_visibility.get_bool()
}
#[derive(Clone, Debug, PartialEq)]
struct MeshTriangles {
positions: Vec<[f32; 3]>,
indices: Vec<u32>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Occluders {
meshes: Vec<(u32, MeshTriangles)>,
}
impl Occluders {
pub(crate) fn from_scene(scene: &SceneDesc<'_>, ids: &[u32]) -> Self {
if scene.capacities.probes == 0 {
return Self::default();
}
let mut meshes: Vec<(u32, MeshTriangles)> = Vec::with_capacity(scene.meshes.len());
for (index, desc) in scene.meshes.iter().enumerate() {
let Some(&id) = ids.get(index) else {
continue;
};
let triangles = match &desc.geometry {
Geometry::Flat {
vertices, indices, ..
} => MeshTriangles {
positions: vertices
.as_chunks::<{ mesh::VERTEX_STRIDE }>()
.0
.iter()
.map(|record| MeshVertex::from_bytes(record).position)
.collect(),
indices: indices.to_vec(),
},
Geometry::Dag { dag, .. } => {
let Some(level) = dag.levels.first() else {
continue;
};
MeshTriangles {
positions: level.positions.clone(),
indices: level.indices(),
}
}
};
meshes.push((id, triangles));
}
meshes.sort_by_key(|(id, _)| *id);
Self { meshes }
}
pub(crate) fn is_empty(&self) -> bool {
self.meshes.is_empty()
}
fn triangles(&self, mesh: u32) -> Option<&MeshTriangles> {
self.meshes
.binary_search_by_key(&mesh, |(id, _)| *id)
.ok()
.map(|at| &self.meshes[at].1)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Occluder {
pub(crate) mesh: u32,
pub(crate) transform: Mat4,
}
pub(crate) fn world_triangles(geometry: &Occluders, occluders: &[Occluder]) -> Vec<[[f32; 3]; 3]> {
let mut soup = Vec::new();
for placed in occluders {
let Some(mesh) = geometry.triangles(placed.mesh) else {
continue;
};
let world: Vec<[f32; 3]> = mesh
.positions
.iter()
.map(|position| {
placed
.transform
.transform_point3(glam::Vec3::from_array(*position))
.to_array()
})
.collect();
for triangle in mesh.indices.as_chunks::<3>().0 {
let corner = |lane: usize| world.get(triangle[lane] as usize).copied();
if let (Some(a), Some(b), Some(c)) = (corner(0), corner(1), corner(2)) {
soup.push([a, b, c]);
}
}
}
soup
}
#[cfg(test)]
mod tests {
use super::*;
fn cube() -> (Vec<[f32; 3]>, Vec<u32>) {
let positions = vec![
[-0.5, -0.5, -0.5],
[0.5, -0.5, -0.5],
[0.5, 0.5, -0.5],
[-0.5, 0.5, -0.5],
[-0.5, -0.5, 0.5],
[0.5, -0.5, 0.5],
[0.5, 0.5, 0.5],
[-0.5, 0.5, 0.5],
];
let indices = vec![
0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 4, 7, 0, 7, 3, 1, 2, 6, 1, 6, 5, 0, 1, 5, 0, 5, 4, 3, 7, 6, 3, 6, 2, ];
(positions, indices)
}
fn one_cube() -> Occluders {
let (positions, indices) = cube();
Occluders {
meshes: vec![(0, MeshTriangles { positions, indices })],
}
}
#[test]
fn a_placed_mesh_puts_its_triangles_where_the_transform_says() {
let placed = [Occluder {
mesh: 0,
transform: Mat4::from_translation(glam::Vec3::new(10.0, 0.0, 0.0))
* Mat4::from_scale(glam::Vec3::new(4.0, 2.0, 6.0)),
}];
let soup = world_triangles(&one_cube(), &placed);
assert_eq!(soup.len(), 12, "a cube is twelve triangles");
let (mut low, mut high) = ([f32::MAX; 3], [f32::MIN; 3]);
for triangle in &soup {
for corner in triangle {
for axis in 0..3 {
low[axis] = low[axis].min(corner[axis]);
high[axis] = high[axis].max(corner[axis]);
}
}
}
for (axis, (want_low, want_high)) in [(8.0, 12.0), (-1.0, 1.0), (-3.0, 3.0)]
.into_iter()
.enumerate()
{
assert!(
(low[axis] - want_low).abs() <= 1.0e-5 && (high[axis] - want_high).abs() <= 1.0e-5,
"axis {axis} spans {} to {}, not {want_low} to {want_high}",
low[axis],
high[axis]
);
}
}
#[test]
fn an_unkept_mesh_places_no_triangles() {
let placed = [
Occluder {
mesh: 7,
transform: Mat4::IDENTITY,
},
Occluder {
mesh: 0,
transform: Mat4::IDENTITY,
},
];
assert_eq!(world_triangles(&one_cube(), &placed).len(), 12);
}
#[test]
fn a_scene_with_no_probes_keeps_nothing() {
let scene = crate::scene::demo();
assert_eq!(scene.capacities.probes, 0);
let ids: Vec<u32> = (0..scene.meshes.len() as u32).collect();
let geometry = Occluders::from_scene(&scene, &ids);
assert!(geometry.is_empty());
assert!(world_triangles(&geometry, &[]).is_empty());
}
#[test]
fn a_scene_with_probes_keeps_its_triangles() {
let mut scene = crate::scene::demo();
scene.capacities.probes = 1;
let ids: Vec<u32> = (0..scene.meshes.len() as u32).map(|id| id * 3).collect();
let geometry = Occluders::from_scene(&scene, &ids);
assert_eq!(geometry.meshes.len(), scene.meshes.len());
for (index, id) in ids.iter().enumerate() {
let kept = geometry
.triangles(*id)
.unwrap_or_else(|| panic!("mesh {index} was kept under id {id}"));
assert!(!kept.positions.is_empty());
assert!(kept.indices.len().is_multiple_of(3));
}
assert_eq!(
geometry.triangles(1),
None,
"and nothing under an id no mesh has"
);
}
}