Skip to main content

lib_jsl_geometry/dim_2/
free_vector2d.rs

1//! Concrete two-dimensional free-vector type for the public geometry API.
2//!
3//! [`FreeVector2D`] represents displacement, scale factors, and other non-coordinate-vector
4//! vectors. Its stored coordinates may be Cartesian or polar, and all math is performed in
5//! Cartesian space before converting the result back to the vector's declared coordinate system.
6
7use crate::common::{
8    CanNormalize, CanScale, CanScaleNonUniform, CoordinatePrimitive, DotProduct,
9    GeometricPrimitive, GeometricPrimitive2D, GeometryMeasure, HasDimension, HasNorm, Normalize,
10    ScalarOperable, SelfAddition, SelfProductInner,
11};
12use crate::coordinate_systems::{CoordinateSystem2D, ToCartesian, ToPolar};
13use crate::two_d::coordinate_conversions;
14use std::fmt::{self, Display, Formatter};
15use std::hash::{Hash, Hasher};
16use std::ops::{Add, Div, Index, IndexMut, Mul, Sub};
17
18/// Concrete 2D free-vector implementation whose stored coordinates may be Cartesian or polar.
19#[derive(Debug, Clone, Copy, PartialEq)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub struct FreeVector2D {
22    coords: [GeometryMeasure; 2],
23    coordinate_system: CoordinateSystem2D,
24}
25
26impl Eq for FreeVector2D {}
27
28impl Hash for FreeVector2D {
29    fn hash<H: Hasher>(&self, state: &mut H) {
30        for value in self.coords {
31            value.to_bits().hash(state);
32        }
33        self.coordinate_system.hash(state);
34    }
35}
36
37impl FreeVector2D {
38    /// Creates a vector from Cartesian `x` and `y` components.
39    pub fn new(x: GeometryMeasure, y: GeometryMeasure) -> Self {
40        Self {
41            coords: [x, y],
42            coordinate_system: CoordinateSystem2D::Cartesian,
43        }
44    }
45
46    /// Creates a vector from raw coordinates in the specified system.
47    pub fn new_in_system(
48        first: GeometryMeasure,
49        second: GeometryMeasure,
50        coordinate_system: CoordinateSystem2D,
51    ) -> Self {
52        Self {
53            coords: [first, second],
54            coordinate_system,
55        }
56    }
57
58    pub(crate) fn from_array_in_system(
59        coords: [GeometryMeasure; 2],
60        coordinate_system: CoordinateSystem2D,
61    ) -> Self {
62        Self {
63            coords,
64            coordinate_system,
65        }
66    }
67
68    pub(crate) fn from_cartesian_components(
69        coords: [GeometryMeasure; 2],
70        coordinate_system: CoordinateSystem2D,
71    ) -> Self {
72        Self::from_array_in_system(
73            coordinate_conversions::from_cartesian(coords, coordinate_system),
74            coordinate_system,
75        )
76    }
77
78    /// Returns the raw stored coordinates in the currently declared coordinate system.
79    pub fn raw_components(&self) -> [GeometryMeasure; 2] {
80        self.coords
81    }
82
83    /// Returns the Cartesian `[x, y]` representation of this vector.
84    pub fn cartesian_components(&self) -> [GeometryMeasure; 2] {
85        coordinate_conversions::to_cartesian(self.coords, self.coordinate_system)
86    }
87
88    /// Returns the current coordinate system.
89    pub fn coordinate_system(&self) -> CoordinateSystem2D {
90        self.coordinate_system
91    }
92
93    /// Converts the stored coordinates to `coordinate_system` if needed.
94    pub fn set_coordinate_system(&mut self, coordinate_system: CoordinateSystem2D) {
95        if self.coordinate_system != coordinate_system {
96            let cartesian = self.cartesian_components();
97            self.coords = coordinate_conversions::from_cartesian(cartesian, coordinate_system);
98            self.coordinate_system = coordinate_system;
99        }
100    }
101
102    /// Returns a copy represented in the requested coordinate system.
103    pub fn converted_to(&self, coordinate_system: CoordinateSystem2D) -> Self {
104        let mut converted = *self;
105        converted.set_coordinate_system(coordinate_system);
106        converted
107    }
108
109    /// Returns the Cartesian x-component.
110    pub fn x(&self) -> GeometryMeasure {
111        self.cartesian_components()[0]
112    }
113
114    /// Returns the Cartesian y-component.
115    pub fn y(&self) -> GeometryMeasure {
116        self.cartesian_components()[1]
117    }
118}
119
120impl Display for FreeVector2D {
121    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
122        write!(
123            f,
124            "FreeVector2D({:?}, {}, {})",
125            self.coordinate_system, self.coords[0], self.coords[1]
126        )
127    }
128}
129
130impl GeometricPrimitive for FreeVector2D {}
131impl GeometricPrimitive2D for FreeVector2D {}
132impl CoordinatePrimitive for FreeVector2D {}
133impl HasDimension for FreeVector2D {
134    const DIM: usize = 2;
135}
136
137impl AsRef<GeometryMeasure> for FreeVector2D {
138    fn as_ref(&self) -> &GeometryMeasure {
139        &self.coords[0]
140    }
141}
142
143impl AsMut<GeometryMeasure> for FreeVector2D {
144    fn as_mut(&mut self) -> &mut GeometryMeasure {
145        &mut self.coords[0]
146    }
147}
148
149impl Index<usize> for FreeVector2D {
150    type Output = GeometryMeasure;
151
152    fn index(&self, index: usize) -> &Self::Output {
153        &self.coords[index]
154    }
155}
156
157impl IndexMut<usize> for FreeVector2D {
158    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
159        &mut self.coords[index]
160    }
161}
162
163impl Add<GeometryMeasure> for FreeVector2D {
164    type Output = Self;
165
166    fn add(self, rhs: GeometryMeasure) -> Self::Output {
167        let cartesian = self.cartesian_components();
168        Self::from_cartesian_components([cartesian[0] + rhs, cartesian[1] + rhs], self.coordinate_system)
169    }
170}
171
172impl Sub<GeometryMeasure> for FreeVector2D {
173    type Output = Self;
174
175    fn sub(self, rhs: GeometryMeasure) -> Self::Output {
176        let cartesian = self.cartesian_components();
177        Self::from_cartesian_components([cartesian[0] - rhs, cartesian[1] - rhs], self.coordinate_system)
178    }
179}
180
181impl Mul<GeometryMeasure> for FreeVector2D {
182    type Output = Self;
183
184    fn mul(self, rhs: GeometryMeasure) -> Self::Output {
185        let cartesian = self.cartesian_components();
186        Self::from_cartesian_components([cartesian[0] * rhs, cartesian[1] * rhs], self.coordinate_system)
187    }
188}
189
190impl Div<GeometryMeasure> for FreeVector2D {
191    type Output = Self;
192
193    fn div(self, rhs: GeometryMeasure) -> Self::Output {
194        let cartesian = self.cartesian_components();
195        Self::from_cartesian_components([cartesian[0] / rhs, cartesian[1] / rhs], self.coordinate_system)
196    }
197}
198
199impl Add for FreeVector2D {
200    type Output = Self;
201
202    fn add(self, rhs: Self) -> Self::Output {
203        let lhs = self.cartesian_components();
204        let rhs = rhs.cartesian_components();
205        Self::from_cartesian_components([lhs[0] + rhs[0], lhs[1] + rhs[1]], self.coordinate_system)
206    }
207}
208
209impl Sub for FreeVector2D {
210    type Output = Self;
211
212    fn sub(self, rhs: Self) -> Self::Output {
213        let lhs = self.cartesian_components();
214        let rhs = rhs.cartesian_components();
215        Self::from_cartesian_components([lhs[0] - rhs[0], lhs[1] - rhs[1]], self.coordinate_system)
216    }
217}
218
219impl Mul<FreeVector2D> for FreeVector2D {
220    type Output = GeometryMeasure;
221
222    fn mul(self, rhs: FreeVector2D) -> Self::Output {
223        let lhs = self.cartesian_components();
224        let rhs = rhs.cartesian_components();
225        lhs[0] * rhs[0] + lhs[1] * rhs[1]
226    }
227}
228
229impl ScalarOperable for FreeVector2D {}
230impl SelfAddition for FreeVector2D {}
231impl SelfProductInner for FreeVector2D {}
232
233impl CanScale for FreeVector2D {
234    fn scale(&mut self, factor: GeometryMeasure) {
235        *self = *self * factor;
236    }
237}
238
239impl CanScaleNonUniform for FreeVector2D {
240    type ScaleVector = FreeVector2D;
241
242    fn scale_non_uniform(&mut self, factors: &Self::ScaleVector) {
243        let coords = self.cartesian_components();
244        let factor_coords = factors.cartesian_components();
245        *self = Self::from_cartesian_components(
246            [coords[0] * factor_coords[0], coords[1] * factor_coords[1]],
247            self.coordinate_system,
248        );
249    }
250}
251
252impl DotProduct for FreeVector2D {
253    type Output = GeometryMeasure;
254
255    fn dot(&self, rhs: &Self) -> <Self as DotProduct>::Output {
256        let lhs = self.cartesian_components();
257        let rhs = rhs.cartesian_components();
258        lhs[0] * rhs[0] + lhs[1] * rhs[1]
259    }
260}
261
262impl HasNorm for FreeVector2D {
263    fn norm(&self) -> GeometryMeasure {
264        let coords = self.cartesian_components();
265        (coords[0] * coords[0] + coords[1] * coords[1]).sqrt()
266    }
267}
268
269impl Normalize for FreeVector2D {
270    fn normalized(&self) -> Self {
271        let norm = self.norm();
272        if norm == 0.0 {
273            Self::new(0.0, 0.0)
274        } else {
275            Self::from_cartesian_components(
276                [self.x() / norm, self.y() / norm],
277                self.coordinate_system,
278            )
279        }
280    }
281}
282
283impl CanNormalize for FreeVector2D {
284    fn normalize(&mut self) {
285        *self = self.normalized();
286    }
287}
288
289impl ToCartesian for FreeVector2D {
290    type Cartesian = FreeVector2D;
291
292    fn to_cartesian(&self) -> Self::Cartesian {
293        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem2D::Cartesian)
294    }
295}
296
297impl ToPolar for FreeVector2D {
298    type Polar = FreeVector2D;
299
300    fn to_polar(&self) -> Self::Polar {
301        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem2D::Polar)
302    }
303}