use glam::Vec3;
#[inline(always)]
pub fn sdf_capped_torus(p: Vec3, major_radius: f32, minor_radius: f32, cap_angle: f32) -> f32 {
let sc = (
alice_det_math::sin(cap_angle),
alice_det_math::cos(cap_angle),
);
let px = p.x.abs();
let k = if sc.1 * px > sc.0 * p.y {
px * sc.0 + (p.y * sc.1)
} else {
alice_det_math::hypot(px, p.y)
};
((2.0 * major_radius) * -k
+ (major_radius * major_radius + (p.z * p.z + (p.x * p.x + (p.y * p.y)))))
.sqrt()
- minor_radius
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_capped_torus_full() {
let d = sdf_capped_torus(Vec3::new(1.0, 0.0, 0.0), 1.0, 0.3, std::f32::consts::PI);
assert!(
(d + 0.3).abs() < 0.01,
"On tube center should be ~-0.3, got {}",
d
);
}
#[test]
fn test_capped_torus_origin() {
let d = sdf_capped_torus(Vec3::ZERO, 1.0, 0.3, std::f32::consts::FRAC_PI_2);
assert!(d > 0.0, "Origin should be outside, got {}", d);
}
#[test]
fn test_capped_torus_outside() {
let d = sdf_capped_torus(Vec3::new(5.0, 0.0, 0.0), 1.0, 0.3, 1.0);
assert!(d > 0.0, "Far point should be outside, got {}", d);
}
#[test]
fn test_capped_torus_symmetry_x() {
let d1 = sdf_capped_torus(Vec3::new(0.5, 0.3, 0.2), 1.0, 0.3, 1.0);
let d2 = sdf_capped_torus(Vec3::new(-0.5, 0.3, 0.2), 1.0, 0.3, 1.0);
assert!((d1 - d2).abs() < 0.001, "Should be symmetric in X");
}
}