1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use {
super::{vec3, vec3_is_finite, Vec3},
serde::{Deserialize, Serialize},
std::ops::{Add, AddAssign},
};
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct Sphere {
center: Vec3,
radius: f32,
}
impl Sphere {
pub fn new(center: Vec3, radius: f32) -> Self {
assert!(vec3_is_finite(center));
assert!(radius.is_finite());
assert!(radius > 0.0);
Self { center, radius }
}
pub fn from_point_cloud<I: Iterator<Item = Vec3>>(cloud: I) -> Self {
let cloud = cloud.collect::<Vec<_>>();
let mut center = Vec3::zero();
for point in &cloud {
center += *point;
}
let count = cloud.len() as f32;
center /= vec3(count, count, count);
let mut distance_squared = 0.0f32;
for point in &cloud {
distance_squared = distance_squared.max(center.distance_squared(*point));
}
Self {
center,
radius: distance_squared.sqrt(),
}
}
pub const fn center(&self) -> Vec3 {
self.center
}
pub fn diameter(&self) -> f32 {
self.radius * 2.0
}
pub const fn radius(&self) -> f32 {
self.radius
}
}
impl<T> Add<T> for Sphere
where
T: Into<f32>,
{
type Output = Self;
fn add(self, val: T) -> Self {
Self {
center: self.center,
radius: self.radius + val.into(),
}
}
}
impl<T> AddAssign<T> for Sphere
where
T: Into<f32>,
{
fn add_assign(&mut self, val: T) {
*self = *self + val.into();
}
}
impl<I> From<I> for Sphere
where
I: Iterator<Item = Vec3>,
{
fn from(cloud: I) -> Self {
Self::from_point_cloud(cloud)
}
}