Skip to main content

lib_jsl_geometry/dim_3/
unit_vector3d.rs

1//! Concrete three-dimensional unit vector type for the public geometry API.
2//!
3//! [`UnitVector3D`] is used anywhere the concrete API needs a guaranteed direction, such as plane
4//! normals or line directions returned from geometric queries.
5
6use crate::common::{
7    CanNormalize, CoordinatePrimitive, CrossProduct, DotProduct, GeometricPrimitive,
8    GeometricPrimitive3D, GeometryMeasure, HasDimension, HasNorm, IsUnitVector, Normalize,
9};
10use crate::coordinate_systems::{
11    CoordinateSystem3D, ToCartesian, ToCylindrical, ToSpherical,
12};
13use crate::three_d::coordinate_conversions;
14use crate::three_d::FreeVector3D;
15use std::fmt::{self, Display, Formatter};
16use std::hash::{Hash, Hasher};
17use std::ops::{Index, IndexMut};
18
19/// Concrete 3D unit-vector implementation whose stored coordinates may be Cartesian, spherical, or cylindrical.
20#[derive(Debug, Clone, Copy, PartialEq)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub struct UnitVector3D {
23    coords: [GeometryMeasure; 3],
24    coordinate_system: CoordinateSystem3D,
25}
26
27impl Eq for UnitVector3D {}
28
29impl Hash for UnitVector3D {
30    fn hash<H: Hasher>(&self, state: &mut H) {
31        for value in self.coords {
32            value.to_bits().hash(state);
33        }
34        self.coordinate_system.hash(state);
35    }
36}
37
38impl UnitVector3D {
39    /// Creates and normalizes a vector from Cartesian coordinates.
40    pub fn new(x: GeometryMeasure, y: GeometryMeasure, z: GeometryMeasure) -> Self {
41        Self::new_in_system(x, y, z, CoordinateSystem3D::Cartesian)
42    }
43
44    /// Creates and normalizes a vector from raw coordinates in the supplied system.
45    pub fn new_in_system(
46        first: GeometryMeasure,
47        second: GeometryMeasure,
48        third: GeometryMeasure,
49        coordinate_system: CoordinateSystem3D,
50    ) -> Self {
51        let cartesian = coordinate_conversions::to_cartesian([first, second, third], coordinate_system);
52        Self::from_cartesian_components(cartesian, coordinate_system)
53    }
54
55    /// Creates a unit vector by normalizing a free geometry vector.
56    pub fn from_vector(vector: FreeVector3D) -> Self {
57        Self::from_cartesian_components(vector.cartesian_components(), vector.coordinate_system())
58    }
59
60    pub(crate) fn from_cartesian_components(
61        coords: [GeometryMeasure; 3],
62        coordinate_system: CoordinateSystem3D,
63    ) -> Self {
64        let norm = (coords[0] * coords[0] + coords[1] * coords[1] + coords[2] * coords[2]).sqrt();
65        let normalized = if norm == 0.0 {
66            [1.0, 0.0, 0.0]
67        } else {
68            [coords[0] / norm, coords[1] / norm, coords[2] / norm]
69        };
70        Self {
71            coords: coordinate_conversions::from_cartesian(normalized, coordinate_system),
72            coordinate_system,
73        }
74    }
75
76    /// Returns this unit vector as a free geometry vector with the same components.
77    pub fn as_vector(self) -> FreeVector3D {
78        FreeVector3D::from_cartesian_components(self.cartesian_components(), self.coordinate_system)
79    }
80
81    /// Returns the raw stored coordinates in the current coordinate system.
82    pub fn raw_components(&self) -> [GeometryMeasure; 3] {
83        self.coords
84    }
85
86    /// Returns the Cartesian `[x, y, z]` representation of this vector.
87    pub fn cartesian_components(&self) -> [GeometryMeasure; 3] {
88        coordinate_conversions::to_cartesian(self.coords, self.coordinate_system)
89    }
90
91    /// Returns the current coordinate system.
92    pub fn coordinate_system(&self) -> CoordinateSystem3D {
93        self.coordinate_system
94    }
95
96    /// Converts the stored coordinates to `coordinate_system` if needed.
97    pub fn set_coordinate_system(&mut self, coordinate_system: CoordinateSystem3D) {
98        if self.coordinate_system != coordinate_system {
99            let cartesian = self.cartesian_components();
100            self.coords = coordinate_conversions::from_cartesian(cartesian, coordinate_system);
101            self.coordinate_system = coordinate_system;
102        }
103    }
104
105    /// Returns a copy represented in the requested coordinate system.
106    pub fn converted_to(&self, coordinate_system: CoordinateSystem3D) -> Self {
107        let mut converted = *self;
108        converted.set_coordinate_system(coordinate_system);
109        converted
110    }
111
112    /// Returns the Cartesian x-component.
113    pub fn x(&self) -> GeometryMeasure {
114        self.cartesian_components()[0]
115    }
116
117    /// Returns the Cartesian y-component.
118    pub fn y(&self) -> GeometryMeasure {
119        self.cartesian_components()[1]
120    }
121
122    /// Returns the Cartesian z-component.
123    pub fn z(&self) -> GeometryMeasure {
124        self.cartesian_components()[2]
125    }
126}
127
128impl Display for UnitVector3D {
129    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
130        write!(
131            f,
132            "UnitVector3D({:?}, {}, {}, {})",
133            self.coordinate_system, self.coords[0], self.coords[1], self.coords[2]
134        )
135    }
136}
137
138impl GeometricPrimitive for UnitVector3D {}
139impl GeometricPrimitive3D for UnitVector3D {}
140impl CoordinatePrimitive for UnitVector3D {}
141impl IsUnitVector for UnitVector3D {}
142impl HasDimension for UnitVector3D {
143    const DIM: usize = 3;
144}
145
146impl AsRef<GeometryMeasure> for UnitVector3D {
147    fn as_ref(&self) -> &GeometryMeasure {
148        &self.coords[0]
149    }
150}
151
152impl AsMut<GeometryMeasure> for UnitVector3D {
153    fn as_mut(&mut self) -> &mut GeometryMeasure {
154        &mut self.coords[0]
155    }
156}
157
158impl Index<usize> for UnitVector3D {
159    type Output = GeometryMeasure;
160
161    fn index(&self, index: usize) -> &Self::Output {
162        &self.coords[index]
163    }
164}
165
166impl IndexMut<usize> for UnitVector3D {
167    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
168        &mut self.coords[index]
169    }
170}
171
172impl DotProduct for UnitVector3D {
173    type Output = GeometryMeasure;
174
175    fn dot(&self, rhs: &Self) -> <Self as DotProduct>::Output {
176        let lhs = self.cartesian_components();
177        let rhs = rhs.cartesian_components();
178        lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2]
179    }
180}
181
182impl CrossProduct for UnitVector3D {
183    type Output = FreeVector3D;
184
185    fn cross(&self, rhs: &Self) -> <Self as CrossProduct>::Output {
186        let lhs = self.cartesian_components();
187        let rhs = rhs.cartesian_components();
188        FreeVector3D::from_cartesian_components(
189            [
190                lhs[1] * rhs[2] - lhs[2] * rhs[1],
191                lhs[2] * rhs[0] - lhs[0] * rhs[2],
192                lhs[0] * rhs[1] - lhs[1] * rhs[0],
193            ],
194            self.coordinate_system,
195        )
196    }
197}
198
199impl HasNorm for UnitVector3D {
200    fn norm(&self) -> GeometryMeasure {
201        1.0
202    }
203}
204
205impl Normalize for UnitVector3D {
206    fn normalized(&self) -> Self {
207        *self
208    }
209}
210
211impl CanNormalize for UnitVector3D {
212    fn normalize(&mut self) {
213        *self = Self::from_cartesian_components(self.cartesian_components(), self.coordinate_system);
214    }
215}
216
217impl ToCartesian for UnitVector3D {
218    type Cartesian = UnitVector3D;
219
220    fn to_cartesian(&self) -> Self::Cartesian {
221        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem3D::Cartesian)
222    }
223}
224
225impl ToSpherical for UnitVector3D {
226    type Spherical = UnitVector3D;
227
228    fn to_spherical(&self) -> Self::Spherical {
229        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem3D::Spherical)
230    }
231}
232
233impl ToCylindrical for UnitVector3D {
234    type Cylindrical = UnitVector3D;
235
236    fn to_cylindrical(&self) -> Self::Cylindrical {
237        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem3D::Cylindrical)
238    }
239}