use thiserror::Error;
#[derive(Debug, Error)]
pub enum PickingError {
#[error("Invalid ray: {0}")]
InvalidRay(String),
#[error("Invalid camera: {0}")]
InvalidCamera(String),
#[error("Empty scene: no Gaussians to pick")]
EmptyScene,
}
#[derive(Debug, Clone, Copy)]
pub struct Ray {
pub origin: [f32; 3],
pub direction: [f32; 3],
}
impl Ray {
pub fn new(origin: [f32; 3], direction: [f32; 3]) -> Result<Self, PickingError> {
let len_sq =
direction[0] * direction[0] + direction[1] * direction[1] + direction[2] * direction[2];
if len_sq < f32::EPSILON * f32::EPSILON {
return Err(PickingError::InvalidRay(
"direction vector is zero-length".to_string(),
));
}
let inv_len = 1.0 / len_sq.sqrt();
Ok(Self {
origin,
direction: [
direction[0] * inv_len,
direction[1] * inv_len,
direction[2] * inv_len,
],
})
}
#[inline]
pub fn at(&self, t: f32) -> [f32; 3] {
[
self.origin[0] + t * self.direction[0],
self.origin[1] + t * self.direction[1],
self.origin[2] + t * self.direction[2],
]
}
#[inline]
pub fn direction_len(&self) -> f32 {
let d = &self.direction;
(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt()
}
}
#[derive(Debug, Clone)]
pub struct PickCamera {
pub position: [f32; 3],
pub rotation: [f32; 9],
pub width: u32,
pub height: u32,
pub fov_x: f32,
}
impl PickCamera {
pub fn new(
position: [f32; 3],
rotation: [f32; 9],
width: u32,
height: u32,
fov_x: f32,
) -> Result<Self, PickingError> {
if width == 0 {
return Err(PickingError::InvalidCamera(
"image width must be > 0".to_string(),
));
}
if height == 0 {
return Err(PickingError::InvalidCamera(
"image height must be > 0".to_string(),
));
}
if fov_x <= 0.0 || fov_x >= std::f32::consts::PI {
return Err(PickingError::InvalidCamera(format!(
"fov_x must be in (0, π), got {fov_x}"
)));
}
Ok(Self {
position,
rotation,
width,
height,
fov_x,
})
}
pub fn ray_for_pixel(&self, px: u32, py: u32) -> Result<Ray, PickingError> {
if px >= self.width {
return Err(PickingError::InvalidCamera(format!(
"pixel x={px} out of range [0, {})",
self.width
)));
}
if py >= self.height {
return Err(PickingError::InvalidCamera(format!(
"pixel y={py} out of range [0, {})",
self.height
)));
}
let nx = (px as f32 + 0.5) / self.width as f32 * 2.0 - 1.0;
let ny = 1.0 - (py as f32 + 0.5) / self.height as f32 * 2.0;
let aspect = self.width as f32 / self.height as f32;
let tan_half_fov_x = (self.fov_x * 0.5).tan();
let tan_half_fov_y = tan_half_fov_x / aspect;
let vd = [nx * tan_half_fov_x, ny * tan_half_fov_y, -1.0_f32];
let r = &self.rotation;
let world_dir = [
r[0] * vd[0] + r[1] * vd[1] + r[2] * vd[2],
r[3] * vd[0] + r[4] * vd[1] + r[5] * vd[2],
r[6] * vd[0] + r[7] * vd[1] + r[8] * vd[2],
];
Ray::new(self.position, world_dir)
}
pub fn rays_for_region(
&self,
x0: u32,
y0: u32,
x1: u32,
y1: u32,
) -> Result<Vec<Ray>, PickingError> {
if x0 >= x1 {
return Err(PickingError::InvalidCamera(format!(
"region x range is empty: x0={x0} >= x1={x1}"
)));
}
if y0 >= y1 {
return Err(PickingError::InvalidCamera(format!(
"region y range is empty: y0={y0} >= y1={y1}"
)));
}
if x1 > self.width {
return Err(PickingError::InvalidCamera(format!(
"region x1={x1} exceeds image width {}",
self.width
)));
}
if y1 > self.height {
return Err(PickingError::InvalidCamera(format!(
"region y1={y1} exceeds image height {}",
self.height
)));
}
let num_rays = ((x1 - x0) * (y1 - y0)) as usize;
let mut rays = Vec::with_capacity(num_rays);
for py in y0..y1 {
for px in x0..x1 {
rays.push(self.ray_for_pixel(px, py)?);
}
}
Ok(rays)
}
}
#[derive(Debug, Clone, Copy)]
pub struct GaussianPickData {
pub center: [f32; 3],
pub radius: f32,
pub opacity: f32,
}
#[derive(Debug, Clone)]
pub struct PickHit {
pub index: usize,
pub t: f32,
pub closest_point: [f32; 3],
pub distance_to_center: f32,
pub opacity: f32,
}
impl PickHit {
#[inline]
pub fn world_position(&self) -> [f32; 3] {
self.closest_point
}
}
#[derive(Debug, Clone)]
pub struct PickConfig {
pub radius_scale: f32,
pub min_opacity: f32,
pub max_hit_distance: f32,
pub max_t: f32,
}
impl Default for PickConfig {
fn default() -> Self {
Self {
radius_scale: 1.0,
min_opacity: 0.1,
max_hit_distance: f32::MAX,
max_t: 1000.0,
}
}
}
pub fn ray_point_distance(ray: &Ray, point: [f32; 3]) -> (f32, f32) {
let vec = [
point[0] - ray.origin[0],
point[1] - ray.origin[1],
point[2] - ray.origin[2],
];
let t = vec[0] * ray.direction[0] + vec[1] * ray.direction[1] + vec[2] * ray.direction[2];
let closest = ray.at(t);
let dx = point[0] - closest[0];
let dy = point[1] - closest[1];
let dz = point[2] - closest[2];
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
(t, dist)
}
pub fn ray_sphere_intersect(ray: &Ray, center: [f32; 3], radius: f32) -> Option<f32> {
let oc = [
ray.origin[0] - center[0],
ray.origin[1] - center[1],
ray.origin[2] - center[2],
];
let b = 2.0 * (oc[0] * ray.direction[0] + oc[1] * ray.direction[1] + oc[2] * ray.direction[2]);
let c = oc[0] * oc[0] + oc[1] * oc[1] + oc[2] * oc[2] - radius * radius;
let discriminant = b * b - 4.0 * c;
if discriminant < 0.0 {
return None; }
let sqrt_disc = discriminant.sqrt();
let t1 = (-b - sqrt_disc) * 0.5;
let t2 = (-b + sqrt_disc) * 0.5;
if t2 < 0.0 {
return None;
}
if t1 < 0.0 {
Some(t2)
} else {
Some(t1)
}
}
pub fn pick_nearest(
ray: &Ray,
gaussians: &[GaussianPickData],
config: &PickConfig,
) -> Option<PickHit> {
let mut best: Option<PickHit> = None;
for (index, g) in gaussians.iter().enumerate() {
if g.opacity < config.min_opacity {
continue;
}
let scaled_radius = g.radius * config.radius_scale;
let sphere_t = match ray_sphere_intersect(ray, g.center, scaled_radius) {
Some(t) => t,
None => continue,
};
if sphere_t > config.max_t {
continue;
}
let (t_closest, dist) = ray_point_distance(ray, g.center);
let closest_point = ray.at(t_closest);
if dist > config.max_hit_distance {
continue;
}
let is_nearer = best.as_ref().is_none_or(|b| sphere_t < b.t);
if is_nearer {
best = Some(PickHit {
index,
t: sphere_t,
closest_point,
distance_to_center: dist,
opacity: g.opacity,
});
}
}
best
}
pub fn pick_all(ray: &Ray, gaussians: &[GaussianPickData], config: &PickConfig) -> Vec<PickHit> {
let mut hits = Vec::new();
for (index, g) in gaussians.iter().enumerate() {
if g.opacity < config.min_opacity {
continue;
}
let scaled_radius = g.radius * config.radius_scale;
let sphere_t = match ray_sphere_intersect(ray, g.center, scaled_radius) {
Some(t) => t,
None => continue,
};
if sphere_t > config.max_t {
continue;
}
let (t_closest, dist) = ray_point_distance(ray, g.center);
let closest_point = ray.at(t_closest);
if dist > config.max_hit_distance {
continue;
}
hits.push(PickHit {
index,
t: sphere_t,
closest_point,
distance_to_center: dist,
opacity: g.opacity,
});
}
hits.sort_by(|a, b| a.t.partial_cmp(&b.t).unwrap_or(std::cmp::Ordering::Equal));
hits
}
pub fn pick_closest_approach(
ray: &Ray,
gaussians: &[GaussianPickData],
config: &PickConfig,
) -> Option<PickHit> {
let mut best: Option<PickHit> = None;
for (index, g) in gaussians.iter().enumerate() {
if g.opacity < config.min_opacity {
continue;
}
let (t, dist) = ray_point_distance(ray, g.center);
if t <= 0.0 {
continue; }
if t >= config.max_t {
continue;
}
if dist > config.max_hit_distance {
continue;
}
let closest_point = ray.at(t);
let is_closer = best.as_ref().is_none_or(|b| dist < b.distance_to_center);
if is_closer {
best = Some(PickHit {
index,
t,
closest_point,
distance_to_center: dist,
opacity: g.opacity,
});
}
}
best
}
#[derive(Debug, Clone)]
pub struct RegionPickResult {
pub hits: Vec<PickHit>,
pub total_tested: usize,
pub num_rays: usize,
}
pub fn pick_region(
camera: &PickCamera,
gaussians: &[GaussianPickData],
x0: u32,
y0: u32,
x1: u32,
y1: u32,
config: &PickConfig,
) -> Result<RegionPickResult, PickingError> {
let rays = camera.rays_for_region(x0, y0, x1, y1)?;
let num_rays = rays.len();
let mut all_hits = Vec::new();
let total_tested = num_rays * gaussians.len();
for ray in &rays {
let hits = pick_all(ray, gaussians, config);
all_hits.extend(hits);
}
Ok(RegionPickResult {
hits: all_hits,
total_tested,
num_rays,
})
}
#[derive(Debug, Clone)]
pub struct PickStats {
pub total_gaussians: usize,
pub skipped_opacity: usize,
pub num_hits: usize,
pub nearest_t: Option<f32>,
pub mean_distance_to_center: f32,
}
pub fn compute_pick_stats(gaussians: &[GaussianPickData], hits: &[PickHit]) -> PickStats {
let total_gaussians = gaussians.len();
let skipped_opacity = gaussians
.iter()
.filter(|g| g.opacity < PickConfig::default().min_opacity)
.count();
let num_hits = hits.len();
let nearest_t = hits.iter().map(|h| h.t).reduce(f32::min);
let mean_distance_to_center = if num_hits == 0 {
0.0
} else {
let sum: f32 = hits.iter().map(|h| h.distance_to_center).sum();
sum / num_hits as f32
};
PickStats {
total_gaussians,
skipped_opacity,
num_hits,
nearest_t,
mean_distance_to_center,
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn identity_rotation() -> [f32; 9] {
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
}
fn forward_camera() -> PickCamera {
PickCamera::new(
[0.0, 0.0, 0.0],
identity_rotation(),
100,
100,
std::f32::consts::FRAC_PI_2,
)
.unwrap()
}
fn gaussian_on_axis(z: f32) -> GaussianPickData {
GaussianPickData {
center: [0.0, 0.0, z],
radius: 0.5,
opacity: 0.9,
}
}
#[test]
fn test_ray_new_valid() {
let ray = Ray::new([0.0, 0.0, 0.0], [3.0, 0.0, 0.0]).unwrap();
let len = ray.direction_len();
assert!(
(len - 1.0).abs() < 1e-6,
"direction should be unit-length, got {len}"
);
assert_eq!(ray.direction, [1.0, 0.0, 0.0]);
}
#[test]
fn test_ray_new_zero_direction() {
let result = Ray::new([0.0, 0.0, 0.0], [0.0, 0.0, 0.0]);
assert!(result.is_err(), "zero direction should return Err");
}
#[test]
fn test_ray_at() {
let ray = Ray::new([1.0, 2.0, 3.0], [0.0, 0.0, 1.0]).unwrap();
let p = ray.at(5.0);
assert!((p[0] - 1.0).abs() < 1e-6);
assert!((p[1] - 2.0).abs() < 1e-6);
assert!((p[2] - 8.0).abs() < 1e-6);
}
#[test]
fn test_ray_point_distance_on_ray() {
let ray = Ray::new([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]).unwrap();
let (t, dist) = ray_point_distance(&ray, [5.0, 0.0, 0.0]);
assert!((t - 5.0).abs() < 1e-5, "t should be 5, got {t}");
assert!(dist < 1e-5, "distance should be ~0, got {dist}");
}
#[test]
fn test_ray_point_distance_perpendicular() {
let ray = Ray::new([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]).unwrap();
let (t, dist) = ray_point_distance(&ray, [3.0, 4.0, 0.0]);
assert!((t - 3.0).abs() < 1e-5, "t should be 3, got {t}");
assert!(
(dist - 4.0).abs() < 1e-5,
"distance should be 4, got {dist}"
);
}
#[test]
fn test_ray_sphere_intersect_hit() {
let ray = Ray::new([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]).unwrap();
let t = ray_sphere_intersect(&ray, [0.0, 0.0, -5.0], 1.0);
assert!(t.is_some(), "should hit sphere");
let t = t.unwrap();
assert!(t > 0.0, "t should be positive, got {t}");
assert!((t - 4.0).abs() < 1e-4, "expected t≈4, got {t}");
}
#[test]
fn test_ray_sphere_intersect_miss() {
let ray = Ray::new([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]).unwrap();
let t = ray_sphere_intersect(&ray, [0.0, 10.0, 0.0], 1.0);
assert!(t.is_none(), "should miss sphere");
}
#[test]
fn test_ray_sphere_intersect_inside() {
let ray = Ray::new([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]).unwrap();
let t = ray_sphere_intersect(&ray, [0.0, 0.0, 0.0], 10.0);
assert!(t.is_some(), "should return exit point");
let t = t.unwrap();
assert!(t > 0.0, "exit t should be positive, got {t}");
assert!((t - 10.0).abs() < 1e-4, "expected t≈10, got {t}");
}
#[test]
fn test_ray_sphere_intersect_behind() {
let ray = Ray::new([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]).unwrap();
let t = ray_sphere_intersect(&ray, [0.0, 0.0, 5.0], 1.0);
assert!(t.is_none(), "sphere is behind origin — should return None");
}
#[test]
fn test_pick_camera_new_valid() {
let cam = PickCamera::new(
[1.0, 2.0, 3.0],
identity_rotation(),
800,
600,
std::f32::consts::FRAC_PI_4,
);
assert!(cam.is_ok(), "valid camera should succeed");
}
#[test]
fn test_ray_for_center_pixel() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
assert!(
ray.direction[2] < -0.9,
"center pixel should point mostly −Z, got {:?}",
ray.direction
);
assert!(ray.direction[0].abs() < 0.1);
assert!(ray.direction[1].abs() < 0.1);
}
#[test]
fn test_ray_for_left_pixel() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(0, 50).unwrap();
assert!(
ray.direction[0] < 0.0,
"left pixel should have negative X, got {:?}",
ray.direction
);
}
#[test]
fn test_pick_nearest_hit() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
let gaussians = vec![gaussian_on_axis(-5.0)];
let config = PickConfig::default();
let hit = pick_nearest(&ray, &gaussians, &config);
assert!(hit.is_some(), "should hit Gaussian on −Z axis");
let hit = hit.unwrap();
assert_eq!(hit.index, 0);
assert!(hit.t > 0.0);
}
#[test]
fn test_pick_nearest_empty() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
let hit = pick_nearest(&ray, &[], &PickConfig::default());
assert!(hit.is_none());
}
#[test]
fn test_pick_nearest_two_gaussians() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
let gaussians = vec![
gaussian_on_axis(-10.0), gaussian_on_axis(-4.0), ];
let hit = pick_nearest(&ray, &gaussians, &PickConfig::default()).unwrap();
assert_eq!(hit.index, 1, "nearer Gaussian (index 1) should be selected");
}
#[test]
fn test_pick_nearest_opacity_filter() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
let gaussians = vec![GaussianPickData {
center: [0.0, 0.0, -5.0],
radius: 0.5,
opacity: 0.05, }];
let hit = pick_nearest(&ray, &gaussians, &PickConfig::default());
assert!(hit.is_none(), "low-opacity Gaussian should be skipped");
}
#[test]
fn test_pick_all_sorted() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
let gaussians = vec![
gaussian_on_axis(-10.0),
gaussian_on_axis(-4.0),
gaussian_on_axis(-7.0),
];
let hits = pick_all(&ray, &gaussians, &PickConfig::default());
assert_eq!(hits.len(), 3, "all three Gaussians should be hit");
for w in hits.windows(2) {
assert!(
w[0].t <= w[1].t,
"hits not sorted: t[0]={} > t[1]={}",
w[0].t,
w[1].t
);
}
assert_eq!(hits[0].index, 1, "nearest hit should be index 1 (z=−4)");
}
#[test]
fn test_pick_nearest_respects_max_t() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
let gaussians = vec![gaussian_on_axis(-2000.0)];
let hit = pick_nearest(&ray, &gaussians, &PickConfig::default());
assert!(hit.is_none(), "hit beyond max_t should be rejected");
}
#[test]
fn test_pick_nearest_max_t_allows_hit_just_inside() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
let config = PickConfig {
max_t: 10.0,
..PickConfig::default()
};
let gaussians = vec![gaussian_on_axis(-5.0)];
let hit = pick_nearest(&ray, &gaussians, &config);
assert!(hit.is_some(), "hit within max_t should still be found");
}
#[test]
fn test_pick_all_respects_max_t() {
let cam = forward_camera();
let ray = cam.ray_for_pixel(50, 50).unwrap();
let gaussians = vec![gaussian_on_axis(-4.0), gaussian_on_axis(-2000.0)];
let hits = pick_all(&ray, &gaussians, &PickConfig::default());
assert_eq!(
hits.len(),
1,
"only the in-range Gaussian should be returned"
);
assert_eq!(hits[0].index, 0);
}
#[test]
fn test_pick_all_empty() {
let ray = Ray::new([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]).unwrap();
let hits = pick_all(&ray, &[], &PickConfig::default());
assert!(hits.is_empty());
}
#[test]
fn test_pick_closest_approach() {
let ray = Ray::new([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]).unwrap();
let gaussians = vec![
GaussianPickData {
center: [3.0, 0.0, -5.0], radius: 0.5,
opacity: 0.9,
},
GaussianPickData {
center: [1.0, 0.0, -5.0], radius: 0.5,
opacity: 0.9,
},
];
let config = PickConfig {
max_hit_distance: 10.0,
..Default::default()
};
let hit = pick_closest_approach(&ray, &gaussians, &config).unwrap();
assert_eq!(
hit.index, 1,
"should pick the Gaussian with smaller perpendicular distance"
);
}
#[test]
fn test_pick_region_single_pixel() {
let cam = forward_camera();
let gaussians = vec![gaussian_on_axis(-5.0)];
let result = pick_region(&cam, &gaussians, 50, 50, 51, 51, &PickConfig::default()).unwrap();
assert_eq!(result.num_rays, 1);
assert_eq!(result.total_tested, 1); assert!(!result.hits.is_empty(), "should hit the Gaussian");
}
#[test]
fn test_compute_pick_stats() {
let gaussians = vec![
GaussianPickData {
center: [0.0, 0.0, -5.0],
radius: 0.5,
opacity: 0.9,
},
GaussianPickData {
center: [0.0, 0.0, -8.0],
radius: 0.5,
opacity: 0.05,
}, ];
let hits = vec![PickHit {
index: 0,
t: 4.5,
closest_point: [0.0, 0.0, -4.5],
distance_to_center: 0.0,
opacity: 0.9,
}];
let stats = compute_pick_stats(&gaussians, &hits);
assert_eq!(stats.total_gaussians, 2);
assert_eq!(stats.skipped_opacity, 1);
assert_eq!(stats.num_hits, 1);
assert!(stats.nearest_t.is_some());
assert!((stats.nearest_t.unwrap() - 4.5).abs() < 1e-6);
}
#[test]
fn test_pick_hit_world_position() {
let hit = PickHit {
index: 0,
t: 5.0,
closest_point: [1.0, 2.0, 3.0],
distance_to_center: 0.1,
opacity: 0.8,
};
assert_eq!(hit.world_position(), hit.closest_point);
}
}