Skip to main content

math/
sphere.rs

1use maths_rs::{dot, Vec3f};
2
3#[derive(Debug, Clone, Copy, PartialEq)]
4pub struct Sphere {
5	pub center: Vec3f,
6	pub radius: f32,
7}
8
9impl Sphere {
10	pub fn new(center: Vec3f, radius: f32) -> Self {
11		Self { center, radius }
12	}
13
14	pub fn contains_point(&self, point: Vec3f) -> bool {
15		let distance_squared = dot(self.center - point, self.center - point);
16		distance_squared <= self.radius * self.radius
17	}
18
19	pub fn intersects(&self, other: &Sphere) -> bool {
20		let distance_squared = dot(self.center - other.center, self.center - other.center);
21		let radius_sum = self.radius + other.radius;
22		distance_squared <= radius_sum * radius_sum
23	}
24}
25
26#[cfg(test)]
27mod tests {
28	use maths_rs::Vec3f;
29
30	use super::Sphere;
31
32	#[test]
33	fn containment_includes_surface_and_is_translation_invariant() {
34		let sphere = Sphere::new(Vec3f::new(10.0, -4.0, 2.0), 3.0);
35		assert!(sphere.contains_point(Vec3f::new(10.0, -4.0, 2.0)));
36		assert!(sphere.contains_point(Vec3f::new(13.0, -4.0, 2.0)));
37		assert!(!sphere.contains_point(Vec3f::new(13.001, -4.0, 2.0)));
38
39		let offset = Vec3f::new(-7.0, 5.0, 11.0);
40		let translated = Sphere::new(sphere.center + offset, sphere.radius);
41		for point in [
42			Vec3f::new(10.0, -4.0, 2.0),
43			Vec3f::new(13.0, -4.0, 2.0),
44			Vec3f::new(13.001, -4.0, 2.0),
45		] {
46			assert_eq!(sphere.contains_point(point), translated.contains_point(point + offset));
47		}
48	}
49
50	#[test]
51	fn intersection_is_symmetric_and_includes_tangency() {
52		let a = Sphere::new(Vec3f::new(0.0, 0.0, 0.0), 2.0);
53		let overlapping = Sphere::new(Vec3f::new(2.5, 0.0, 0.0), 1.0);
54		let tangent = Sphere::new(Vec3f::new(3.0, 0.0, 0.0), 1.0);
55		let separated = Sphere::new(Vec3f::new(3.001, 0.0, 0.0), 1.0);
56
57		for other in [overlapping, tangent, separated] {
58			assert_eq!(a.intersects(&other), other.intersects(&a));
59		}
60		assert!(a.intersects(&overlapping));
61		assert!(a.intersects(&tangent));
62		assert!(!a.intersects(&separated));
63	}
64
65	#[test]
66	fn zero_radius_contains_only_its_center() {
67		let point = Vec3f::new(1.0, 2.0, 3.0);
68		let sphere = Sphere::new(point, 0.0);
69		assert!(sphere.contains_point(point));
70		assert!(!sphere.contains_point(point + Vec3f::new(f32::EPSILON, 0.0, 0.0)));
71	}
72}