use glam::{Vec2, Vec3};
#[inline(always)]
pub fn sdf_cut_sphere(p: Vec3, radius: f32, cut_height: f32) -> f32 {
let w = radius
.mul_add(radius, -(cut_height * cut_height))
.max(0.0)
.sqrt();
let q = Vec2::new(p.x.hypot(p.z), p.y);
let s1 = ((cut_height - radius) * q.x)
.mul_add(q.x, w * w * 2.0f32.mul_add(-q.y, cut_height + radius));
let s2 = cut_height.mul_add(q.x, -(w * q.y));
let s = s1.max(s2);
if s < 0.0 {
q.length() - radius
} else if q.x < w {
cut_height - q.y
} else {
(q - Vec2::new(w, cut_height)).length()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cut_sphere_inside() {
let d = sdf_cut_sphere(Vec3::new(0.0, 0.8, 0.0), 1.0, 0.5);
assert!(d < 0.0, "Inside cap should be negative, got {}", d);
}
#[test]
fn test_cut_sphere_below_cut() {
let d = sdf_cut_sphere(Vec3::ZERO, 1.0, 0.5);
assert!(d > 0.0, "Below cut should be positive, got {}", d);
}
#[test]
fn test_cut_sphere_negative_cut() {
let d = sdf_cut_sphere(Vec3::ZERO, 1.0, -0.5);
assert!(
d < 0.0,
"Origin should be inside cap with low cut, got {}",
d
);
}
#[test]
fn test_cut_sphere_outside() {
let d = sdf_cut_sphere(Vec3::new(5.0, 0.0, 0.0), 1.0, 0.5);
assert!(d > 0.0, "Far point should be outside, got {}", d);
}
}