use thiserror::Error;
#[derive(Debug, Error)]
pub enum DepthMapError {
#[error("Invalid camera: {0}")]
InvalidCamera(String),
#[error("Empty scene: no Gaussians provided")]
EmptyScene,
#[error("Invalid dimensions: {0}")]
InvalidDimensions(String),
}
#[derive(Debug, Clone)]
pub struct DepthCamera {
pub position: [f32; 3],
pub view_matrix_rotation: [f32; 9],
pub width: u32,
pub height: u32,
pub fx: f32,
pub fy: f32,
pub cx: f32,
pub cy: f32,
pub near: f32,
pub far: f32,
}
impl DepthCamera {
pub fn from_fov(
position: [f32; 3],
view_rotation: [f32; 9],
width: u32,
height: u32,
fov_y_rad: f32,
near: f32,
far: f32,
) -> Result<Self, DepthMapError> {
if fov_y_rad <= 0.0 || !fov_y_rad.is_finite() {
return Err(DepthMapError::InvalidCamera(format!(
"fov_y_rad must be positive and finite, got {fov_y_rad}"
)));
}
if width == 0 {
return Err(DepthMapError::InvalidCamera(
"width must be non-zero".to_string(),
));
}
if height == 0 {
return Err(DepthMapError::InvalidCamera(
"height must be non-zero".to_string(),
));
}
if near <= 0.0 {
return Err(DepthMapError::InvalidCamera(format!(
"near must be positive, got {near}"
)));
}
if far <= near {
return Err(DepthMapError::InvalidCamera(format!(
"far ({far}) must be greater than near ({near})"
)));
}
let half_fov_tan = (fov_y_rad * 0.5).tan();
let fy = height as f32 / (2.0 * half_fov_tan);
let aspect = width as f32 / height as f32;
let fx = fy * aspect;
let cx = width as f32 * 0.5;
let cy = height as f32 * 0.5;
Ok(Self {
position,
view_matrix_rotation: view_rotation,
width,
height,
fx,
fy,
cx,
cy,
near,
far,
})
}
pub fn project(&self, world_point: [f32; 3]) -> Option<(f32, f32, f32)> {
let diff = [
world_point[0] - self.position[0],
world_point[1] - self.position[1],
world_point[2] - self.position[2],
];
let r = &self.view_matrix_rotation;
let cam_x = r[0] * diff[0] + r[1] * diff[1] + r[2] * diff[2];
let cam_y = r[3] * diff[0] + r[4] * diff[1] + r[5] * diff[2];
let cam_z = r[6] * diff[0] + r[7] * diff[1] + r[8] * diff[2];
let depth = -cam_z;
if depth <= 0.0 {
return None;
}
let px = self.fx * cam_x / depth + self.cx;
let py = -self.fy * cam_y / depth + self.cy;
let w = self.width as f32;
let h = self.height as f32;
if px < 0.0 || px >= w || py < 0.0 || py >= h {
return None;
}
Some((px, py, depth))
}
pub fn in_frustum_approx(&self, center: [f32; 3], radius: f32) -> bool {
let diff = [
center[0] - self.position[0],
center[1] - self.position[1],
center[2] - self.position[2],
];
let r = &self.view_matrix_rotation;
let cam_x = r[0] * diff[0] + r[1] * diff[1] + r[2] * diff[2];
let cam_y = r[3] * diff[0] + r[4] * diff[1] + r[5] * diff[2];
let cam_z = r[6] * diff[0] + r[7] * diff[1] + r[8] * diff[2];
let depth = -cam_z;
if depth + radius < self.near || depth - radius > self.far {
return false;
}
if depth <= 0.0 && depth + radius <= 0.0 {
return false;
}
let ref_depth = if depth > radius {
depth
} else {
depth + radius
};
if ref_depth <= 0.0 {
return false;
}
let denom = (ref_depth * ref_depth - radius * radius)
.max(1e-6_f32)
.sqrt();
let proj_radius_x = self.fx * radius / denom;
let proj_radius_y = self.fy * radius / denom;
let px = self.fx * cam_x / ref_depth + self.cx;
let py = -self.fy * cam_y / ref_depth + self.cy;
let w = self.width as f32;
let h = self.height as f32;
if px + proj_radius_x < 0.0 || px - proj_radius_x >= w {
return false;
}
if py + proj_radius_y < 0.0 || py - proj_radius_y >= h {
return false;
}
true
}
}
#[derive(Debug, Clone)]
pub struct DepthSample {
pub pixel_x: f32,
pub pixel_y: f32,
pub depth: f32,
pub opacity: f32,
pub gaussian_index: usize,
}
#[derive(Debug, Clone)]
pub struct GaussianDepthData {
pub center: [f32; 3],
pub radius: f32,
pub opacity: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DepthMode {
Nearest,
AlphaWeighted,
Median,
MaxOpacity,
}
#[derive(Debug, Clone)]
pub struct DepthMapStats {
pub min_depth: f32,
pub max_depth: f32,
pub mean_depth: f32,
pub std_depth: f32,
pub num_valid: usize,
pub coverage: f32,
}
#[derive(Debug, Clone)]
pub struct DepthMap {
pub width: u32,
pub height: u32,
pub depths: Vec<f32>,
pub opacity_weights: Vec<f32>,
pub mode: DepthMode,
}
impl DepthMap {
pub fn new(width: u32, height: u32, mode: DepthMode) -> Self {
let n = (width as usize) * (height as usize);
Self {
width,
height,
depths: vec![f32::INFINITY; n],
opacity_weights: vec![0.0; n],
mode,
}
}
pub fn pixel_depth(&self, px: u32, py: u32) -> f32 {
if px >= self.width || py >= self.height {
return f32::INFINITY;
}
self.depths[(py as usize) * (self.width as usize) + (px as usize)]
}
pub fn valid_depth(&self, px: u32, py: u32) -> Option<f32> {
let d = self.pixel_depth(px, py);
if d.is_finite() {
Some(d)
} else {
None
}
}
pub fn normalized(&self) -> Vec<f32> {
let finite_iter = self.depths.iter().copied().filter(|d| d.is_finite());
let min_d = finite_iter.clone().fold(f32::INFINITY, f32::min);
let max_d = finite_iter.fold(f32::NEG_INFINITY, f32::max);
let range = max_d - min_d;
if range <= 0.0 || !range.is_finite() {
return self
.depths
.iter()
.map(|d| if d.is_finite() { 0.0 } else { 1.0 })
.collect();
}
self.depths
.iter()
.map(|d| {
if d.is_finite() {
(d - min_d) / range
} else {
1.0
}
})
.collect()
}
pub fn to_u8_image(&self) -> Vec<u8> {
let norm = self.normalized();
norm.iter()
.zip(self.depths.iter())
.map(|(n, d)| {
if d.is_finite() {
(255.0 * (1.0 - n)).clamp(0.0, 255.0) as u8
} else {
0u8
}
})
.collect()
}
pub fn stats(&self) -> DepthMapStats {
let valid: Vec<f32> = self
.depths
.iter()
.copied()
.filter(|d| d.is_finite())
.collect();
let total = (self.width as usize) * (self.height as usize);
let num_valid = valid.len();
if num_valid == 0 {
return DepthMapStats {
min_depth: 0.0,
max_depth: 0.0,
mean_depth: 0.0,
std_depth: 0.0,
num_valid: 0,
coverage: 0.0,
};
}
let min_d = valid.iter().copied().fold(f32::INFINITY, f32::min);
let max_d = valid.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let mean_d = valid.iter().copied().sum::<f32>() / num_valid as f32;
let variance = valid
.iter()
.map(|d| {
let diff = d - mean_d;
diff * diff
})
.sum::<f32>()
/ num_valid as f32;
let std_d = variance.sqrt();
let coverage = num_valid as f32 / total as f32;
DepthMapStats {
min_depth: min_d,
max_depth: max_d,
mean_depth: mean_d,
std_depth: std_d,
num_valid,
coverage,
}
}
pub fn num_valid_pixels(&self) -> usize {
self.depths.iter().filter(|d| d.is_finite()).count()
}
pub fn coverage(&self) -> f32 {
let total = (self.width as usize) * (self.height as usize);
if total == 0 {
return 0.0;
}
self.num_valid_pixels() as f32 / total as f32
}
}
pub fn render_depth_map(
camera: &DepthCamera,
gaussians: &[GaussianDepthData],
mode: DepthMode,
) -> Result<DepthMap, DepthMapError> {
if camera.width == 0 || camera.height == 0 {
return Err(DepthMapError::InvalidDimensions(format!(
"camera dimensions must be non-zero, got {}×{}",
camera.width, camera.height
)));
}
let w = camera.width as usize;
let h = camera.height as usize;
let n_pixels = w * h;
match mode {
DepthMode::Nearest => render_nearest(camera, gaussians, w, h, n_pixels),
DepthMode::AlphaWeighted => render_alpha_weighted(camera, gaussians, w, h, n_pixels),
DepthMode::MaxOpacity => render_max_opacity(camera, gaussians, w, h, n_pixels),
DepthMode::Median => render_median(camera, gaussians, w, h, n_pixels),
}
}
#[inline]
fn projected_radius_px(camera: &DepthCamera, radius: f32, depth: f32) -> (f32, f32) {
(
(camera.fx * radius / depth).max(1.0),
(camera.fy * radius / depth).max(1.0),
)
}
fn render_nearest(
camera: &DepthCamera,
gaussians: &[GaussianDepthData],
w: usize,
h: usize,
n_pixels: usize,
) -> Result<DepthMap, DepthMapError> {
let mut depths = vec![f32::INFINITY; n_pixels];
let opacity_weights = vec![0.0f32; n_pixels];
for gaussian in gaussians {
if !camera.in_frustum_approx(gaussian.center, gaussian.radius) {
continue;
}
let (px_f, py_f, depth) = match camera.project(gaussian.center) {
Some(v) => v,
None => continue,
};
let (proj_rx, proj_ry) = projected_radius_px(camera, gaussian.radius, depth);
splat_nearest(px_f, py_f, depth, proj_rx, proj_ry, (w, h), &mut depths);
}
let mut map = DepthMap::new(camera.width, camera.height, DepthMode::Nearest);
map.depths = depths;
map.opacity_weights = opacity_weights;
Ok(map)
}
#[inline]
fn splat_nearest(
px_f: f32,
py_f: f32,
depth: f32,
radius_x: f32,
radius_y: f32,
(w, h): (usize, usize),
depths: &mut [f32],
) {
let x_min = (px_f - radius_x).floor() as i32;
let x_max = (px_f + radius_x).floor() as i32;
let y_min = (py_f - radius_y).floor() as i32;
let y_max = (py_f + radius_y).floor() as i32;
for iy in y_min..=y_max {
if iy < 0 || iy >= h as i32 {
continue;
}
for ix in x_min..=x_max {
if ix < 0 || ix >= w as i32 {
continue;
}
let idx = iy as usize * w + ix as usize;
if depth < depths[idx] {
depths[idx] = depth;
}
}
}
}
fn render_alpha_weighted(
camera: &DepthCamera,
gaussians: &[GaussianDepthData],
w: usize,
h: usize,
n_pixels: usize,
) -> Result<DepthMap, DepthMapError> {
let mut sum_alpha_depth = vec![0.0f32; n_pixels];
let mut sum_alpha = vec![0.0f32; n_pixels];
for gaussian in gaussians {
if !camera.in_frustum_approx(gaussian.center, gaussian.radius) {
continue;
}
let (px_f, py_f, depth) = match camera.project(gaussian.center) {
Some(v) => v,
None => continue,
};
let (proj_rx, proj_ry) = projected_radius_px(camera, gaussian.radius, depth);
let alpha = gaussian.opacity;
let x_min = (px_f - proj_rx).floor() as i32;
let x_max = (px_f + proj_rx).floor() as i32;
let y_min = (py_f - proj_ry).floor() as i32;
let y_max = (py_f + proj_ry).floor() as i32;
for iy in y_min..=y_max {
if iy < 0 || iy >= h as i32 {
continue;
}
for ix in x_min..=x_max {
if ix < 0 || ix >= w as i32 {
continue;
}
let idx = iy as usize * w + ix as usize;
sum_alpha_depth[idx] += alpha * depth;
sum_alpha[idx] += alpha;
}
}
}
let mut depths = vec![f32::INFINITY; n_pixels];
for i in 0..n_pixels {
if sum_alpha[i] > 0.0 {
depths[i] = sum_alpha_depth[i] / sum_alpha[i];
}
}
let mut map = DepthMap::new(camera.width, camera.height, DepthMode::AlphaWeighted);
map.depths = depths;
map.opacity_weights = sum_alpha;
Ok(map)
}
fn render_max_opacity(
camera: &DepthCamera,
gaussians: &[GaussianDepthData],
w: usize,
h: usize,
n_pixels: usize,
) -> Result<DepthMap, DepthMapError> {
let mut depths = vec![f32::INFINITY; n_pixels];
let mut max_opacities = vec![f32::NEG_INFINITY; n_pixels];
for gaussian in gaussians {
if !camera.in_frustum_approx(gaussian.center, gaussian.radius) {
continue;
}
let (px_f, py_f, depth) = match camera.project(gaussian.center) {
Some(v) => v,
None => continue,
};
let (proj_rx, proj_ry) = projected_radius_px(camera, gaussian.radius, depth);
let alpha = gaussian.opacity;
let x_min = (px_f - proj_rx).floor() as i32;
let x_max = (px_f + proj_rx).floor() as i32;
let y_min = (py_f - proj_ry).floor() as i32;
let y_max = (py_f + proj_ry).floor() as i32;
for iy in y_min..=y_max {
if iy < 0 || iy >= h as i32 {
continue;
}
for ix in x_min..=x_max {
if ix < 0 || ix >= w as i32 {
continue;
}
let idx = iy as usize * w + ix as usize;
if alpha > max_opacities[idx] {
max_opacities[idx] = alpha;
depths[idx] = depth;
}
}
}
}
let mut map = DepthMap::new(camera.width, camera.height, DepthMode::MaxOpacity);
map.depths = depths;
Ok(map)
}
const MEDIAN_MAX_SAMPLES: usize = 8;
fn render_median(
camera: &DepthCamera,
gaussians: &[GaussianDepthData],
w: usize,
h: usize,
n_pixels: usize,
) -> Result<DepthMap, DepthMapError> {
let mut samples = vec![0.0f32; n_pixels * MEDIAN_MAX_SAMPLES];
let mut counts = vec![0u8; n_pixels];
for gaussian in gaussians {
if !camera.in_frustum_approx(gaussian.center, gaussian.radius) {
continue;
}
let (px_f, py_f, depth) = match camera.project(gaussian.center) {
Some(v) => v,
None => continue,
};
let (proj_rx, proj_ry) = projected_radius_px(camera, gaussian.radius, depth);
let x_min = (px_f - proj_rx).floor() as i32;
let x_max = (px_f + proj_rx).floor() as i32;
let y_min = (py_f - proj_ry).floor() as i32;
let y_max = (py_f + proj_ry).floor() as i32;
for iy in y_min..=y_max {
if iy < 0 || iy >= h as i32 {
continue;
}
for ix in x_min..=x_max {
if ix < 0 || ix >= w as i32 {
continue;
}
let idx = iy as usize * w + ix as usize;
let cnt = counts[idx] as usize;
if cnt < MEDIAN_MAX_SAMPLES {
samples[idx * MEDIAN_MAX_SAMPLES + cnt] = depth;
counts[idx] = (cnt + 1) as u8;
}
}
}
}
let mut depths = vec![f32::INFINITY; n_pixels];
for i in 0..n_pixels {
let cnt = counts[i] as usize;
if cnt == 0 {
continue;
}
let base = i * MEDIAN_MAX_SAMPLES;
let slot = &mut samples[base..base + cnt];
slot.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
depths[i] = slot[cnt / 2];
}
let mut map = DepthMap::new(camera.width, camera.height, DepthMode::Median);
map.depths = depths;
Ok(map)
}
pub fn render_depth_maps(
cameras: &[DepthCamera],
gaussians: &[GaussianDepthData],
mode: DepthMode,
) -> Vec<Result<DepthMap, DepthMapError>> {
cameras
.iter()
.map(|cam| render_depth_map(cam, gaussians, mode))
.collect()
}
pub fn depth_to_disparity(depth_map: &DepthMap, focal_length: f32) -> Vec<f32> {
depth_map
.depths
.iter()
.map(|&d| {
if d.is_finite() && d > 0.0 {
focal_length / d
} else {
0.0
}
})
.collect()
}
pub fn depth_map_to_pointcloud(depth_map: &DepthMap, camera: &DepthCamera) -> Vec<[f32; 3]> {
let w = depth_map.width as usize;
let h = depth_map.height as usize;
let r = &camera.view_matrix_rotation;
let rt = [r[0], r[3], r[6], r[1], r[4], r[7], r[2], r[5], r[8]];
let mut points = Vec::new();
for iy in 0..h {
for ix in 0..w {
let idx = iy * w + ix;
let depth = depth_map.depths[idx];
if !depth.is_finite() {
continue;
}
let cam_x = (ix as f32 - camera.cx) * depth / camera.fx;
let cam_y = -(iy as f32 - camera.cy) * depth / camera.fy;
let cam_z = -depth;
let wx = rt[0] * cam_x + rt[1] * cam_y + rt[2] * cam_z + camera.position[0];
let wy = rt[3] * cam_x + rt[4] * cam_y + rt[5] * cam_z + camera.position[1];
let wz = rt[6] * cam_x + rt[7] * cam_y + rt[8] * cam_z + camera.position[2];
points.push([wx, wy, wz]);
}
}
points
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn make_camera() -> DepthCamera {
DepthCamera::from_fov(
[0.0, 0.0, 5.0], [
1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0,
],
64,
64,
std::f32::consts::FRAC_PI_2, 0.1,
100.0,
)
.unwrap()
}
fn make_gaussian(z: f32, opacity: f32) -> GaussianDepthData {
GaussianDepthData {
center: [0.0, 0.0, z],
radius: 0.5,
opacity,
}
}
#[test]
fn test_from_fov_valid() {
let cam = make_camera();
assert!((cam.fy - 32.0).abs() < 1e-3, "fy = {}", cam.fy);
assert!((cam.fx - 32.0).abs() < 1e-3, "fx = {}", cam.fx);
assert!((cam.cx - 32.0).abs() < 1e-3, "cx = {}", cam.cx);
assert!((cam.cy - 32.0).abs() < 1e-3, "cy = {}", cam.cy);
}
#[test]
fn test_from_fov_zero_fov_err() {
let result = DepthCamera::from_fov(
[0.0, 0.0, 5.0],
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
64,
64,
0.0, 0.1,
100.0,
);
assert!(matches!(result, Err(DepthMapError::InvalidCamera(_))));
}
#[test]
fn test_project_in_front() {
let cam = make_camera();
let result = cam.project([0.0, 0.0, 0.0]);
assert!(result.is_some(), "point in front should project");
let (px, py, depth) = result.unwrap();
assert!((px - 32.0).abs() < 1e-3, "px = {px}");
assert!((py - 32.0).abs() < 1e-3, "py = {py}");
assert!((depth - 5.0).abs() < 1e-3, "depth = {depth}");
}
#[test]
fn test_project_behind_camera() {
let cam = make_camera();
let result = cam.project([0.0, 0.0, 10.0]);
assert!(result.is_none(), "point behind camera should return None");
}
#[test]
fn test_project_depth_positive() {
let cam = make_camera();
let (_, _, depth) = cam.project([0.0, 0.0, 0.0]).unwrap();
assert!(depth > 0.0, "depth must be positive, got {depth}");
}
#[test]
fn test_render_empty_gaussians_ok() {
let cam = make_camera();
let result = render_depth_map(&cam, &[], DepthMode::Nearest);
assert!(result.is_ok());
let map = result.unwrap();
assert_eq!(map.num_valid_pixels(), 0);
}
#[test]
fn test_render_single_gaussian_centre_valid() {
let cam = make_camera();
let gaussians = vec![make_gaussian(0.0, 0.9)];
let map = render_depth_map(&cam, &gaussians, DepthMode::Nearest).unwrap();
let d = map.valid_depth(32, 32);
assert!(d.is_some(), "centre pixel should have valid depth");
}
#[test]
fn test_render_nearest_closer_wins() {
let cam = make_camera();
let gaussians = vec![
make_gaussian(0.0, 0.5), make_gaussian(2.0, 0.5), ];
let map = render_depth_map(&cam, &gaussians, DepthMode::Nearest).unwrap();
let d = map.pixel_depth(32, 32);
assert!(d.is_finite(), "centre pixel should have valid depth");
assert!(d < 4.0, "nearest should win, got depth={d}");
}
#[test]
fn test_render_alpha_weighted() {
let cam = make_camera();
let gaussians = vec![
GaussianDepthData {
center: [0.0, 0.0, 3.0],
radius: 0.5,
opacity: 0.9,
}, GaussianDepthData {
center: [0.0, 0.0, -3.0],
radius: 0.5,
opacity: 0.1,
}, ];
let map = render_depth_map(&cam, &gaussians, DepthMode::AlphaWeighted).unwrap();
let d = map.pixel_depth(32, 32);
assert!(d.is_finite(), "should have valid depth");
assert!(
d < 5.0,
"alpha-weighted depth should be closer to high-opacity value, got {d}"
);
}
#[test]
fn test_render_max_opacity() {
let cam = make_camera();
let gaussians = vec![
GaussianDepthData {
center: [0.0, 0.0, 4.0],
radius: 0.5,
opacity: 0.1,
}, GaussianDepthData {
center: [0.0, 0.0, 0.0],
radius: 0.5,
opacity: 0.9,
}, ];
let map = render_depth_map(&cam, &gaussians, DepthMode::MaxOpacity).unwrap();
let d = map.pixel_depth(32, 32);
assert!(d.is_finite());
assert!(
d > 4.0 && d < 6.0,
"max-opacity depth should be ≈5, got {d}"
);
}
#[test]
fn test_num_valid_pixels_fresh() {
let map = DepthMap::new(8, 8, DepthMode::Nearest);
assert_eq!(map.num_valid_pixels(), 0);
}
#[test]
fn test_coverage_fresh() {
let map = DepthMap::new(8, 8, DepthMode::Nearest);
assert!((map.coverage() - 0.0).abs() < 1e-6);
}
#[test]
fn test_normalized_range() {
let cam = make_camera();
let gaussians = vec![
make_gaussian(0.0, 0.9), make_gaussian(3.0, 0.9), ];
let map = render_depth_map(&cam, &gaussians, DepthMode::Nearest).unwrap();
let norm = map.normalized();
for (i, &v) in norm.iter().enumerate() {
let d = map.depths[i];
if d.is_finite() {
assert!(
(0.0..=1.0).contains(&v),
"normalized value {v} out of [0,1]"
);
}
}
}
#[test]
fn test_u8_image_near_brighter_than_far() {
let mut map = DepthMap::new(2, 1, DepthMode::Nearest);
map.depths[0] = 1.0; map.depths[1] = 9.0; let img = map.to_u8_image();
assert!(
img[0] > img[1],
"near pixel ({}) should be brighter than far pixel ({})",
img[0],
img[1]
);
}
#[test]
fn test_stats_ordering() {
let cam = make_camera();
let gaussians = vec![
make_gaussian(0.0, 0.9),
make_gaussian(2.0, 0.9),
make_gaussian(4.0, 0.9),
];
let map = render_depth_map(&cam, &gaussians, DepthMode::Nearest).unwrap();
let stats = map.stats();
assert!(
stats.min_depth <= stats.mean_depth && stats.mean_depth <= stats.max_depth,
"min={} mean={} max={}",
stats.min_depth,
stats.mean_depth,
stats.max_depth
);
}
#[test]
fn test_disparity_inverse_depth() {
let mut map = DepthMap::new(1, 2, DepthMode::Nearest);
map.depths[0] = 2.0; map.depths[1] = 8.0; let disp = depth_to_disparity(&map, 32.0);
assert!(
disp[0] > disp[1],
"near should have larger disparity: {} vs {}",
disp[0],
disp[1]
);
}
#[test]
fn test_disparity_infinity_to_zero() {
let map = DepthMap::new(1, 1, DepthMode::Nearest); let disp = depth_to_disparity(&map, 32.0);
assert!(
(disp[0]).abs() < 1e-6,
"INFINITY depth should give 0 disparity, got {}",
disp[0]
);
}
#[test]
fn test_pointcloud_empty_map() {
let cam = make_camera();
let map = DepthMap::new(8, 8, DepthMode::Nearest);
let pts = depth_map_to_pointcloud(&map, &cam);
assert!(
pts.is_empty(),
"empty depth map should give empty point cloud"
);
}
#[test]
fn test_pointcloud_near_gaussian() {
let cam = make_camera();
let gaussians = vec![GaussianDepthData {
center: [0.0, 0.0, 0.0],
radius: 0.5,
opacity: 0.9,
}];
let map = render_depth_map(&cam, &gaussians, DepthMode::Nearest).unwrap();
let pts = depth_map_to_pointcloud(&map, &cam);
assert!(!pts.is_empty(), "should have at least one point");
let best = pts.iter().min_by(|a, b| {
let da = a[0] * a[0] + a[1] * a[1] + a[2] * a[2];
let db = b[0] * b[0] + b[1] * b[1] + b[2] * b[2];
da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
});
let p = best.unwrap();
let dist = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt();
assert!(
dist < 1.0,
"closest point should be near origin, got dist={dist:.3}"
);
}
#[test]
fn test_render_depth_maps_count() {
let cam1 = make_camera();
let cam2 = DepthCamera::from_fov(
[5.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 0.0],
32,
32,
std::f32::consts::FRAC_PI_4,
0.1,
50.0,
)
.unwrap();
let cameras = vec![cam1, cam2];
let gaussians = vec![make_gaussian(0.0, 0.9)];
let results = render_depth_maps(&cameras, &gaussians, DepthMode::Nearest);
assert_eq!(results.len(), 2, "should have one result per camera");
}
#[test]
fn test_valid_depth() {
let mut map = DepthMap::new(2, 1, DepthMode::Nearest);
map.depths[0] = 3.5;
assert_eq!(map.valid_depth(0, 0), Some(3.5));
assert_eq!(map.valid_depth(1, 0), None);
}
#[test]
fn test_pixel_depth_out_of_bounds() {
let map = DepthMap::new(4, 4, DepthMode::Nearest);
assert!(map.pixel_depth(100, 100).is_infinite());
assert!(map.pixel_depth(4, 0).is_infinite());
assert!(map.pixel_depth(0, 4).is_infinite());
}
#[test]
fn test_in_frustum_approx_large_sphere_near_edge_not_culled() {
let cam = DepthCamera::from_fov(
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], 64,
64,
std::f32::consts::FRAC_PI_2, 0.01,
1000.0,
)
.unwrap();
let radius = 1.0_f32;
let depth = 1.1_f32;
let cam_x = (100.0 - cam.cx) * depth / cam.fx;
let center = [cam_x, 0.0, -depth];
assert!(
cam.in_frustum_approx(center, radius),
"a sphere whose true projected extent still overlaps the image \
must not be culled by the conservative frustum check"
);
}
#[test]
fn test_normalized_all_infinity_maps_to_one() {
let map = DepthMap::new(4, 4, DepthMode::Nearest);
let norm = map.normalized();
assert!(
norm.iter().all(|&v| (v - 1.0).abs() < 1e-6),
"all-INFINITY map should normalize to all 1.0, got {norm:?}"
);
}
#[test]
fn test_render_splat_extent_respects_aspect_ratio() {
let cam = DepthCamera::from_fov(
[0.0, 0.0, 5.0],
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
128,
32,
std::f32::consts::FRAC_PI_2, 0.1,
100.0,
)
.unwrap();
assert!((cam.fx - 64.0).abs() < 1e-3, "fx = {}", cam.fx);
assert!((cam.fy - 16.0).abs() < 1e-3, "fy = {}", cam.fy);
let gaussians = vec![GaussianDepthData {
center: [0.0, 0.0, 1.0],
radius: 1.0,
opacity: 0.9,
}];
let map = render_depth_map(&cam, &gaussians, DepthMode::Nearest).unwrap();
let touched_rows: Vec<usize> = (0..32usize)
.filter(|&row| {
(0..128usize).any(|col| map.pixel_depth(col as u32, row as u32).is_finite())
})
.collect();
let min_row = *touched_rows.first().expect("some row should be touched");
let max_row = *touched_rows.last().expect("some row should be touched");
let row_span = max_row - min_row + 1;
assert!(
row_span <= 14,
"vertical splat extent should track fy (~9 rows), not fx (~32 \
rows); got {row_span} rows spanning {min_row}..={max_row}"
);
}
#[test]
fn test_render_median_resolves_median_depth() {
let cam = make_camera();
let gaussians = vec![
make_gaussian(3.0, 0.9), make_gaussian(0.0, 0.9), make_gaussian(-3.0, 0.9), ];
let map = render_depth_map(&cam, &gaussians, DepthMode::Median).unwrap();
let d = map.pixel_depth(32, 32);
assert!(
(d - 5.0).abs() < 1e-3,
"median of {{2, 5, 8}} should be 5, got {d}"
);
}
#[test]
fn test_render_median_caps_at_max_samples() {
let cam = make_camera();
let gaussians: Vec<GaussianDepthData> = (0..12)
.map(|i| make_gaussian(i as f32 * 0.1, 0.9))
.collect();
let map = render_depth_map(&cam, &gaussians, DepthMode::Median).unwrap();
let d = map.pixel_depth(32, 32);
assert!(d.is_finite(), "centre pixel should still resolve a depth");
}
}