rs_math3d/
vector.rs

1// Copyright 2020-Present (c) Raja Lehtihet & Wael El Oraiby
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are met:
5//
6// 1. Redistributions of source code must retain the above copyright notice,
7// this list of conditions and the following disclaimer.
8//
9// 2. Redistributions in binary form must reproduce the above copyright notice,
10// this list of conditions and the following disclaimer in the documentation
11// and/or other materials provided with the distribution.
12//
13// 3. Neither the name of the copyright holder nor the names of its contributors
14// may be used to endorse or promote products derived from this software without
15// specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28//! Vector mathematics module providing 2D, 3D, and 4D vector operations.
29//!
30//! This module provides generic vector types and operations for computer graphics
31//! and linear algebra applications. All vectors support standard arithmetic operations,
32//! dot products, and component-wise operations.
33//!
34//! # Examples
35//!
36//! ```
37//! use rs_math3d::vector::{Vector3, FloatVector};
38//! 
39//! let v1 = Vector3::new(1.0, 2.0, 3.0);
40//! let v2 = Vector3::new(4.0, 5.0, 6.0);
41//! 
42//! // Vector addition
43//! let sum = v1 + v2;
44//! 
45//! // Dot product
46//! let dot = Vector3::dot(&v1, &v2);
47//! 
48//! // Normalization
49//! let normalized = v1.normalize();
50//! ```
51
52use crate::scalar::*;
53use num_traits::{Zero, One};
54use core::ops::{Add, Div, Mul, Neg, Rem, Sub};
55
56/// Generic vector trait defining common vector operations.
57///
58/// This trait provides the foundation for all vector types, defining
59/// operations like addition, subtraction, dot product, and component-wise operations.
60///
61/// # Mathematical Operations
62///
63/// For vectors **v** and **w**, and scalar `s`:
64/// - Addition: **v** + **w** = (v₁ + w₁, v₂ + w₂, ...)
65/// - Subtraction: **v** - **w** = (v₁ - w₁, v₂ - w₂, ...)
66/// - Scalar multiplication: s**v** = (sv₁, sv₂, ...)
67/// - Dot product: **v** · **w** = v₁w₁ + v₂w₂ + ...
68pub trait Vector<T: Scalar, Rhs = Self, Output = Self>:
69    Add<Rhs, Output = Output>
70    + Sub<Rhs, Output = Output>
71    + Mul<Rhs, Output = Output>
72    + Mul<T, Output = Output>
73    + Div<Rhs, Output = Output>
74    + Div<T, Output = Output>
75    + Neg<Output = Output>
76    + Clone
77    + Copy
78{
79    /// Returns the zero vector (all components are zero).
80    fn zero() -> Self;
81
82    /// Adds two vectors component-wise.
83    fn add_vv(l: &Self, r: &Self) -> Self;
84    
85    /// Subtracts two vectors component-wise.
86    fn sub_vv(l: &Self, r: &Self) -> Self;
87    
88    /// Multiplies two vectors component-wise (Hadamard product).
89    fn mul_vv(l: &Self, r: &Self) -> Self;
90    
91    /// Divides two vectors component-wise.
92    fn div_vv(l: &Self, r: &Self) -> Self;
93    
94    /// Multiplies a vector by a scalar.
95    fn mul_vs(l: &Self, r: T) -> Self;
96    
97    /// Divides a vector by a scalar.
98    fn div_vs(l: &Self, r: T) -> Self;
99    
100    /// Computes the remainder of component-wise division.
101    fn rem_vv(l: &Self, r: &Self) -> Self;
102
103    /// Computes the dot product of two vectors.
104    ///
105    /// For vectors **v** and **w**:
106    /// ```text
107    /// v · w = Σᵢ vᵢwᵢ
108    /// ```
109    fn dot(l: &Self, r: &Self) -> T;
110
111    /// Returns a vector with the minimum components from both vectors.
112    fn min(l: &Self, r: &Self) -> Self;
113    
114    /// Returns a vector with the maximum components from both vectors.
115    fn max(l: &Self, r: &Self) -> Self;
116}
117
118/// Trait for vectors with floating-point components.
119///
120/// Extends the base `Vector` trait with operations that require
121/// floating-point arithmetic, such as length calculation and normalization.
122pub trait FloatVector<T: FloatScalar>: Vector<T> {
123    /// Computes the Euclidean length (magnitude) of the vector.
124    ///
125    /// For vector **v**:
126    /// ```text
127    /// ||v|| = √(v₁² + v₂² + ... + vₙ²)
128    /// ```
129    fn length(&self) -> T;
130    
131    /// Returns a unit vector in the same direction.
132    ///
133    /// For vector **v**:
134    /// ```text
135    /// v̂ = v / ||v||
136    /// ```
137    ///
138    /// # Note
139    /// Returns NaN or Inf components if the vector has zero length.
140    fn normalize(&self) -> Self;
141    
142    /// Computes the Euclidean distance between two vectors.
143    ///
144    /// For vectors **v** and **w**:
145    /// ```text
146    /// d(v, w) = ||v - w||
147    /// ```
148    fn distance(l: &Self, r: &Self) -> T;
149}
150
151macro_rules! implVecScalar {
152    ($vecName:ident, $scalar:ident) => {
153        impl Mul<$vecName<$scalar>> for $scalar {
154            type Output = $vecName<$scalar>;
155
156            fn mul(self, rhs: $vecName<$scalar>) -> Self::Output {
157                $vecName::mul_vs(&rhs, self)
158            }
159        }
160    };
161}
162
163macro_rules! implVector {
164    ($vecName:ident, $($field:ident)*) => {
165        #[repr(C)]
166        #[derive(Copy, Clone, Debug, Default)]
167        pub struct $vecName<T> { $(pub $field: T),* }
168
169        impl<T: Scalar> $vecName<T> {
170            pub fn new($($field:T),*) -> Self { Self { $($field: $field),* } }
171        }
172
173        impl<T: Scalar> Vector<T> for $vecName<T> {
174            fn zero() -> Self { Self { $($field: <T as Zero>::zero()),* } }
175            fn dot  (l: &Self, r: &Self) -> T { $(l.$field * r.$field +)* <T as Zero>::zero() }
176            fn add_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field + r.$field),*) }
177            fn sub_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field - r.$field),*) }
178            fn mul_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field * r.$field),*) }
179            fn div_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field / r.$field),*) }
180            fn mul_vs(l: &Self, r: T) -> Self { Self::new($(l.$field * r),*) }
181            fn div_vs(l: &Self, r: T) -> Self { Self::new($(l.$field / r),*) }
182            fn rem_vv(l: &Self, r: &Self) -> Self { Self::new($(l.$field % r.$field),*) }
183            fn min(l: &Self, r: &Self) -> Self { Self::new($(T::min(l.$field, r.$field)),*) }
184            fn max(l: &Self, r: &Self) -> Self { Self::new($(T::max(l.$field, r.$field)),*) }
185        }
186
187        impl<T> Add for $vecName<T> where T: Scalar {
188            type Output = $vecName<T>;
189
190            fn add(self, rhs: Self) -> Self::Output {
191                Self { $($field: self.$field + rhs.$field),* }
192            }
193        }
194
195        impl<T> Sub for $vecName<T> where T: Scalar {
196            type Output = $vecName<T>;
197
198            fn sub(self, rhs: Self) -> Self::Output {
199                Self { $($field: self.$field - rhs.$field),* }
200            }
201        }
202
203        impl<T> Mul for $vecName<T> where T: Scalar {
204            type Output = $vecName<T>;
205
206            fn mul(self, rhs: Self) -> Self::Output {
207                Self { $($field: self.$field * rhs.$field),* }
208            }
209        }
210
211        impl<T> Mul<T> for $vecName<T> where T:Scalar {
212            type Output = $vecName<T>;
213
214            fn mul(self, rhs: T) -> Self::Output {
215                Self { $($field: self.$field * rhs),* }
216            }
217        }
218
219        implVecScalar!($vecName, f32);
220        implVecScalar!($vecName, f64);
221        implVecScalar!($vecName, i32);
222        implVecScalar!($vecName, i64);
223
224        impl<T> Div for $vecName<T> where T:Scalar {
225            type Output = $vecName<T>;
226
227            fn div(self, rhs: Self) -> Self::Output {
228                Self { $($field: self.$field / rhs.$field),* }
229            }
230        }
231
232        impl<T> Div<T> for $vecName<T> where T:Scalar {
233            type Output = $vecName<T>;
234
235            fn div(self, rhs: T) -> Self::Output {
236                Self { $($field: self.$field / rhs),* }
237            }
238        }
239
240        impl<T> Rem for $vecName<T> where T: Scalar {
241            type Output = $vecName<T>;
242
243            fn rem(self, rhs: $vecName<T>) -> Self::Output {
244                Self { $($field: self.$field % rhs.$field),* }
245            }
246        }
247
248        impl<T> Rem<T> for $vecName<T> where T:Scalar {
249            type Output = $vecName<T>;
250
251            fn rem(self, rhs: T) -> Self::Output {
252                Self { $($field: self.$field % rhs),* }
253            }
254        }
255
256        impl<T: Scalar> Neg for $vecName<T> {
257            type Output = $vecName<T>;
258            fn neg(self) -> Self::Output {
259                Self { $($field: -self.$field),* }
260            }
261        }
262    };
263}
264
265macro_rules! implFloatVector {
266    ($vecName:ident) => {
267        impl<T: FloatScalar> FloatVector<T> for $vecName<T> {
268            fn length(&self) -> T {
269                Self::dot(self, self).tsqrt()
270            }
271            fn normalize(&self) -> Self {
272                let len = Self::length(self);
273                *self / len
274            }
275            fn distance(l: &Self, r: &Self) -> T {
276                Self::length(&(*r - *l))
277            }
278        }
279    };
280}
281
282/// Trait for computing the cross product of 3D vectors.
283///
284/// The cross product is only defined for 3D vectors and produces
285/// a vector perpendicular to both input vectors.
286pub trait CrossProduct {
287    /// Computes the cross product of two vectors.
288    ///
289    /// For 3D vectors **v** and **w**:
290    /// ```text
291    /// v × w = (v₂w₃ - v₃w₂, v₃w₁ - v₁w₃, v₁w₂ - v₂w₁)
292    /// ```
293    ///
294    /// The resulting vector is perpendicular to both input vectors,
295    /// with magnitude ||v|| ||w|| sin(θ), where θ is the angle between them.
296    fn cross(l: &Self, r: &Self) -> Self;
297}
298
299/// A 2D vector with x and y components.
300///
301/// # Examples
302/// ```
303/// use rs_math3d::vector::Vector2;
304/// 
305/// let v = Vector2::new(3.0, 4.0);
306/// assert_eq!(v.x, 3.0);
307/// assert_eq!(v.y, 4.0);
308/// ```
309implVector!(Vector2, x y);
310
311/// A 3D vector with x, y, and z components.
312///
313/// # Examples
314/// ```
315/// use rs_math3d::vector::{Vector3, CrossProduct};
316/// 
317/// let v1 = Vector3::new(1.0, 0.0, 0.0);
318/// let v2 = Vector3::new(0.0, 1.0, 0.0);
319/// let cross = Vector3::cross(&v1, &v2);
320/// // Result is (0, 0, 1) - the z-axis
321/// ```
322implVector!(Vector3, x y z);
323
324/// A 4D vector with x, y, z, and w components.
325///
326/// Often used for homogeneous coordinates in 3D graphics.
327///
328/// # Examples
329/// ```
330/// use rs_math3d::vector::Vector4;
331/// 
332/// let v = Vector4::new(1.0, 2.0, 3.0, 1.0);
333/// // w=1 for positions, w=0 for directions
334/// ```
335implVector!(Vector4, x y z w);
336
337implFloatVector!(Vector2);
338implFloatVector!(Vector3);
339implFloatVector!(Vector4);
340
341impl<T> CrossProduct for Vector3<T>
342where
343    T: Scalar,
344{
345    /// Computes the cross product of two 3D vectors.
346    ///
347    /// The cross product **v** × **w** produces a vector perpendicular
348    /// to both **v** and **w**, following the right-hand rule.
349    ///
350    /// # Properties
351    /// - Anti-commutative: **v** × **w** = -(**w** × **v**)
352    /// - Distributive: **v** × (**w** + **u**) = **v** × **w** + **v** × **u**
353    /// - **v** × **v** = **0**
354    fn cross(l: &Vector3<T>, r: &Vector3<T>) -> Vector3<T> {
355        Vector3::new(
356            l.y * r.z - l.z * r.y,
357            l.z * r.x - l.x * r.z,
358            l.x * r.y - l.y * r.x,
359        )
360    }
361}
362
363/// Trait for 2D swizzle operations on vectors.
364///
365/// Provides methods to rearrange and duplicate vector components
366/// into 2D vectors using familiar shader-style syntax.
367pub trait Swizzle2<T: Scalar> {
368    fn xx(&self) -> Vector2<T>;
369    fn xy(&self) -> Vector2<T>;
370    fn xz(&self) -> Vector2<T>;
371    fn yx(&self) -> Vector2<T>;
372    fn yy(&self) -> Vector2<T>;
373    fn yz(&self) -> Vector2<T>;
374    fn zx(&self) -> Vector2<T>;
375    fn zy(&self) -> Vector2<T>;
376    fn zz(&self) -> Vector2<T>;
377}
378
379impl<T: Scalar> Swizzle2<T> for Vector2<T> {
380    fn xx(&self) -> Vector2<T> {
381        Vector2::new(self.x, self.x)
382    }
383    fn xy(&self) -> Vector2<T> {
384        Vector2::new(self.x, self.y)
385    }
386    fn xz(&self) -> Vector2<T> {
387        Vector2::new(self.x, <T as Zero>::zero())
388    }
389    fn yx(&self) -> Vector2<T> {
390        Vector2::new(self.y, self.x)
391    }
392    fn yy(&self) -> Vector2<T> {
393        Vector2::new(self.y, self.y)
394    }
395    fn yz(&self) -> Vector2<T> {
396        Vector2::new(self.y, <T as Zero>::zero())
397    }
398    fn zx(&self) -> Vector2<T> {
399        Vector2::new(<T as Zero>::zero(), self.x)
400    }
401    fn zy(&self) -> Vector2<T> {
402        Vector2::new(<T as Zero>::zero(), self.y)
403    }
404    fn zz(&self) -> Vector2<T> {
405        Vector2::new(<T as Zero>::zero(), <T as Zero>::zero())
406    }
407}
408
409impl<T: Scalar> Swizzle2<T> for Vector3<T> {
410    fn xx(&self) -> Vector2<T> {
411        Vector2::new(self.x, self.x)
412    }
413    fn xy(&self) -> Vector2<T> {
414        Vector2::new(self.x, self.y)
415    }
416    fn xz(&self) -> Vector2<T> {
417        Vector2::new(self.x, self.z)
418    }
419    fn yx(&self) -> Vector2<T> {
420        Vector2::new(self.y, self.x)
421    }
422    fn yy(&self) -> Vector2<T> {
423        Vector2::new(self.y, self.y)
424    }
425    fn yz(&self) -> Vector2<T> {
426        Vector2::new(self.y, self.z)
427    }
428    fn zx(&self) -> Vector2<T> {
429        Vector2::new(self.z, self.x)
430    }
431    fn zy(&self) -> Vector2<T> {
432        Vector2::new(self.z, self.y)
433    }
434    fn zz(&self) -> Vector2<T> {
435        Vector2::new(self.z, self.z)
436    }
437}
438
439impl<T: Scalar> Swizzle2<T> for Vector4<T> {
440    fn xx(&self) -> Vector2<T> {
441        Vector2::new(self.x, self.x)
442    }
443    fn xy(&self) -> Vector2<T> {
444        Vector2::new(self.x, self.y)
445    }
446    fn xz(&self) -> Vector2<T> {
447        Vector2::new(self.x, self.z)
448    }
449    fn yx(&self) -> Vector2<T> {
450        Vector2::new(self.y, self.x)
451    }
452    fn yy(&self) -> Vector2<T> {
453        Vector2::new(self.y, self.y)
454    }
455    fn yz(&self) -> Vector2<T> {
456        Vector2::new(self.y, self.z)
457    }
458    fn zx(&self) -> Vector2<T> {
459        Vector2::new(self.z, self.x)
460    }
461    fn zy(&self) -> Vector2<T> {
462        Vector2::new(self.z, self.y)
463    }
464    fn zz(&self) -> Vector2<T> {
465        Vector2::new(self.z, self.z)
466    }
467}
468
469/// Trait for 3D swizzle operations on vectors.
470///
471/// Provides methods to rearrange and duplicate vector components
472/// into 3D vectors using familiar shader-style syntax.
473pub trait Swizzle3<T: Scalar> {
474    fn xxx(&self) -> Vector3<T>;
475    fn xxy(&self) -> Vector3<T>;
476    fn xxz(&self) -> Vector3<T>;
477    fn xyx(&self) -> Vector3<T>;
478    fn xyy(&self) -> Vector3<T>;
479    fn xyz(&self) -> Vector3<T>;
480    fn xzx(&self) -> Vector3<T>;
481    fn xzy(&self) -> Vector3<T>;
482    fn xzz(&self) -> Vector3<T>;
483
484    fn yxx(&self) -> Vector3<T>;
485    fn yxy(&self) -> Vector3<T>;
486    fn yxz(&self) -> Vector3<T>;
487    fn yyx(&self) -> Vector3<T>;
488    fn yyy(&self) -> Vector3<T>;
489    fn yyz(&self) -> Vector3<T>;
490    fn yzx(&self) -> Vector3<T>;
491    fn yzy(&self) -> Vector3<T>;
492    fn yzz(&self) -> Vector3<T>;
493
494    fn zxx(&self) -> Vector3<T>;
495    fn zxy(&self) -> Vector3<T>;
496    fn zxz(&self) -> Vector3<T>;
497    fn zyx(&self) -> Vector3<T>;
498    fn zyy(&self) -> Vector3<T>;
499    fn zyz(&self) -> Vector3<T>;
500    fn zzx(&self) -> Vector3<T>;
501    fn zzy(&self) -> Vector3<T>;
502    fn zzz(&self) -> Vector3<T>;
503}
504
505impl<T: Scalar> Swizzle3<T> for Vector3<T> {
506    fn xxx(&self) -> Vector3<T> {
507        Vector3::new(self.x, self.x, self.x)
508    }
509    fn xxy(&self) -> Vector3<T> {
510        Vector3::new(self.x, self.x, self.y)
511    }
512    fn xxz(&self) -> Vector3<T> {
513        Vector3::new(self.x, self.x, self.z)
514    }
515    fn xyx(&self) -> Vector3<T> {
516        Vector3::new(self.x, self.y, self.x)
517    }
518    fn xyy(&self) -> Vector3<T> {
519        Vector3::new(self.x, self.y, self.y)
520    }
521    fn xyz(&self) -> Vector3<T> {
522        Vector3::new(self.x, self.y, self.z)
523    }
524    fn xzx(&self) -> Vector3<T> {
525        Vector3::new(self.x, self.z, self.x)
526    }
527    fn xzy(&self) -> Vector3<T> {
528        Vector3::new(self.x, self.z, self.y)
529    }
530    fn xzz(&self) -> Vector3<T> {
531        Vector3::new(self.x, self.z, self.z)
532    }
533
534    fn yxx(&self) -> Vector3<T> {
535        Vector3::new(self.y, self.x, self.x)
536    }
537    fn yxy(&self) -> Vector3<T> {
538        Vector3::new(self.y, self.x, self.y)
539    }
540    fn yxz(&self) -> Vector3<T> {
541        Vector3::new(self.y, self.x, self.z)
542    }
543    fn yyx(&self) -> Vector3<T> {
544        Vector3::new(self.y, self.y, self.x)
545    }
546    fn yyy(&self) -> Vector3<T> {
547        Vector3::new(self.y, self.y, self.y)
548    }
549    fn yyz(&self) -> Vector3<T> {
550        Vector3::new(self.y, self.y, self.z)
551    }
552    fn yzx(&self) -> Vector3<T> {
553        Vector3::new(self.y, self.z, self.x)
554    }
555    fn yzy(&self) -> Vector3<T> {
556        Vector3::new(self.y, self.z, self.y)
557    }
558    fn yzz(&self) -> Vector3<T> {
559        Vector3::new(self.y, self.z, self.z)
560    }
561
562    fn zxx(&self) -> Vector3<T> {
563        Vector3::new(self.z, self.x, self.x)
564    }
565    fn zxy(&self) -> Vector3<T> {
566        Vector3::new(self.z, self.x, self.y)
567    }
568    fn zxz(&self) -> Vector3<T> {
569        Vector3::new(self.z, self.x, self.z)
570    }
571    fn zyx(&self) -> Vector3<T> {
572        Vector3::new(self.z, self.y, self.x)
573    }
574    fn zyy(&self) -> Vector3<T> {
575        Vector3::new(self.z, self.y, self.y)
576    }
577    fn zyz(&self) -> Vector3<T> {
578        Vector3::new(self.z, self.y, self.z)
579    }
580    fn zzx(&self) -> Vector3<T> {
581        Vector3::new(self.z, self.z, self.x)
582    }
583    fn zzy(&self) -> Vector3<T> {
584        Vector3::new(self.z, self.z, self.y)
585    }
586    fn zzz(&self) -> Vector3<T> {
587        Vector3::new(self.z, self.z, self.z)
588    }
589}
590
591impl<T: Scalar> Swizzle3<T> for Vector4<T> {
592    fn xxx(&self) -> Vector3<T> {
593        Vector3::new(self.x, self.x, self.x)
594    }
595    fn xxy(&self) -> Vector3<T> {
596        Vector3::new(self.x, self.x, self.y)
597    }
598    fn xxz(&self) -> Vector3<T> {
599        Vector3::new(self.x, self.x, self.z)
600    }
601    fn xyx(&self) -> Vector3<T> {
602        Vector3::new(self.x, self.y, self.x)
603    }
604    fn xyy(&self) -> Vector3<T> {
605        Vector3::new(self.x, self.y, self.y)
606    }
607    fn xyz(&self) -> Vector3<T> {
608        Vector3::new(self.x, self.y, self.z)
609    }
610    fn xzx(&self) -> Vector3<T> {
611        Vector3::new(self.x, self.z, self.x)
612    }
613    fn xzy(&self) -> Vector3<T> {
614        Vector3::new(self.x, self.z, self.y)
615    }
616    fn xzz(&self) -> Vector3<T> {
617        Vector3::new(self.x, self.z, self.z)
618    }
619
620    fn yxx(&self) -> Vector3<T> {
621        Vector3::new(self.y, self.x, self.x)
622    }
623    fn yxy(&self) -> Vector3<T> {
624        Vector3::new(self.y, self.x, self.y)
625    }
626    fn yxz(&self) -> Vector3<T> {
627        Vector3::new(self.y, self.x, self.z)
628    }
629    fn yyx(&self) -> Vector3<T> {
630        Vector3::new(self.y, self.y, self.x)
631    }
632    fn yyy(&self) -> Vector3<T> {
633        Vector3::new(self.y, self.y, self.y)
634    }
635    fn yyz(&self) -> Vector3<T> {
636        Vector3::new(self.y, self.y, self.z)
637    }
638    fn yzx(&self) -> Vector3<T> {
639        Vector3::new(self.y, self.z, self.x)
640    }
641    fn yzy(&self) -> Vector3<T> {
642        Vector3::new(self.y, self.z, self.y)
643    }
644    fn yzz(&self) -> Vector3<T> {
645        Vector3::new(self.y, self.z, self.z)
646    }
647
648    fn zxx(&self) -> Vector3<T> {
649        Vector3::new(self.z, self.x, self.x)
650    }
651    fn zxy(&self) -> Vector3<T> {
652        Vector3::new(self.z, self.x, self.y)
653    }
654    fn zxz(&self) -> Vector3<T> {
655        Vector3::new(self.z, self.x, self.z)
656    }
657    fn zyx(&self) -> Vector3<T> {
658        Vector3::new(self.z, self.y, self.x)
659    }
660    fn zyy(&self) -> Vector3<T> {
661        Vector3::new(self.z, self.y, self.y)
662    }
663    fn zyz(&self) -> Vector3<T> {
664        Vector3::new(self.z, self.y, self.z)
665    }
666    fn zzx(&self) -> Vector3<T> {
667        Vector3::new(self.z, self.z, self.x)
668    }
669    fn zzy(&self) -> Vector3<T> {
670        Vector3::new(self.z, self.z, self.y)
671    }
672    fn zzz(&self) -> Vector3<T> {
673        Vector3::new(self.z, self.z, self.z)
674    }
675}
676
677/// Computes the length (magnitude) of a vector.
678///
679/// # Mathematical Definition
680/// ```text
681/// ||v|| = √(v · v)
682/// ```
683pub fn length<T: FloatScalar, V: Vector<T>>(v: &V) -> T {
684    V::dot(v, v).tsqrt()
685}
686
687/// Computes the dot product of two vectors.
688///
689/// # Mathematical Definition
690/// ```text
691/// v · w = Σᵢ vᵢwᵢ
692/// ```
693pub fn dot<T: Scalar, V: Vector<T>>(l: &V, r: &V) -> T {
694    V::dot(l, r)
695}
696
697/// Normalizes a vector to unit length.
698///
699/// # Mathematical Definition
700/// ```text
701/// v̂ = v / ||v||
702/// ```
703///
704/// # Note
705/// Returns NaN or Inf components if the vector has zero length.
706pub fn normalize<T: FloatScalar, V: FloatVector<T>>(v: &V) -> V {
707    let len = v.length();
708    *v / len
709}
710
711/// Computes the Euclidean distance between two points.
712///
713/// # Mathematical Definition
714/// ```text
715/// d(v, w) = ||v - w||
716/// ```
717pub fn distance<T: FloatScalar, V: FloatVector<T>>(l: &V, r: &V) -> T {
718    (*r - *l).length()
719}
720
721/// Returns a vector with the minimum components from both input vectors.
722///
723/// Performs component-wise minimum:
724/// ```text
725/// min(v, w) = (min(v₁, w₁), min(v₂, w₂), ...)
726/// ```
727pub fn min<T: Scalar, V: Vector<T>>(l: &V, r: &V) -> V {
728    V::min(l, r)
729}
730
731/// Returns a vector with the maximum components from both input vectors.
732///
733/// Performs component-wise maximum:
734/// ```text
735/// max(v, w) = (max(v₁, w₁), max(v₂, w₂), ...)
736/// ```
737pub fn max<T: Scalar, V: Vector<T>>(l: &V, r: &V) -> V {
738    V::max(l, r)
739}
740
741#[cfg(test)]
742mod tests {
743    use super::*;
744    use crate::scalar::FloatScalar;
745    
746    #[test]
747    pub fn test() {
748        let f1 = Vector2 { x: 1.0, y: 2.0 };
749        let f2 = Vector2 { x: 3.0, y: 4.0 };
750        let out = f1 + f2;
751        assert_eq!(out.x, 4.0);
752        assert_eq!(out.y, 6.0);
753
754        let f22: Vector2<f32> = 2.0 * f2;
755        let f23: Vector2<f32> = f2 * 2.0;
756
757        assert_eq!(f22.x, 6.0);
758        assert_eq!(f22.y, 8.0);
759        assert_eq!(f23.x, f22.x);
760        assert_eq!(f23.y, f22.y);
761    }
762
763    #[test]
764    fn test_vector_normalization() {
765        // Test normal case
766        let v = Vector3::<f32>::new(3.0, 4.0, 0.0);
767        let nv = v.normalize();
768        let len = nv.length();
769        assert!((len - 1.0).abs() < f32::epsilon());
770        
771        // Test zero vector normalization (should handle gracefully)
772        let v_zero = Vector3::<f32>::new(0.0, 0.0, 0.0);
773        let nv_zero = v_zero.normalize();
774        // When normalizing zero vector, we get NaN or Inf components
775        // The current implementation divides by zero, resulting in inf/nan
776        assert!(nv_zero.x.is_infinite() || nv_zero.x.is_nan());
777        
778        // Test already normalized vector
779        let v_unit = Vector3::<f32>::new(1.0, 0.0, 0.0);
780        let nv_unit = v_unit.normalize();
781        assert!((nv_unit.x - 1.0).abs() < f32::epsilon());
782        assert!((nv_unit.y).abs() < f32::epsilon());
783        assert!((nv_unit.z).abs() < f32::epsilon());
784    }
785
786    #[test]
787    fn test_vector_length() {
788        let v2 = Vector2::<f32>::new(3.0, 4.0);
789        assert!((v2.length() - 5.0).abs() < f32::epsilon());
790        
791        let v3 = Vector3::<f32>::new(2.0, 3.0, 6.0);
792        assert!((v3.length() - 7.0).abs() < f32::epsilon());
793        
794        let v4 = Vector4::<f32>::new(1.0, 2.0, 2.0, 0.0);
795        assert!((v4.length() - 3.0).abs() < f32::epsilon());
796        
797        // Test zero vector
798        let v_zero = Vector3::<f32>::zero();
799        assert_eq!(v_zero.length(), 0.0);
800    }
801
802    #[test]
803    fn test_vector_dot_product() {
804        let v1 = Vector3::<f32>::new(1.0, 2.0, 3.0);
805        let v2 = Vector3::<f32>::new(4.0, 5.0, 6.0);
806        let dot = Vector3::dot(&v1, &v2);
807        assert_eq!(dot, 32.0); // 1*4 + 2*5 + 3*6 = 32
808        
809        // Test orthogonal vectors
810        let v_ortho1 = Vector3::<f32>::new(1.0, 0.0, 0.0);
811        let v_ortho2 = Vector3::<f32>::new(0.0, 1.0, 0.0);
812        assert_eq!(Vector3::dot(&v_ortho1, &v_ortho2), 0.0);
813        
814        // Test dot product with itself equals length squared
815        let self_dot = Vector3::dot(&v1, &v1);
816        let len_squared = v1.length() * v1.length();
817        assert!((self_dot - len_squared).abs() < 0.0001);
818    }
819
820    #[test]
821    fn test_vector_cross_product() {
822        // Test standard basis vectors
823        let x = Vector3::<f32>::new(1.0, 0.0, 0.0);
824        let y = Vector3::<f32>::new(0.0, 1.0, 0.0);
825        let z = Vector3::<f32>::new(0.0, 0.0, 1.0);
826        
827        let x_cross_y = Vector3::cross(&x, &y);
828        assert!((x_cross_y.x - z.x).abs() < f32::epsilon());
829        assert!((x_cross_y.y - z.y).abs() < f32::epsilon());
830        assert!((x_cross_y.z - z.z).abs() < f32::epsilon());
831        
832        let y_cross_z = Vector3::cross(&y, &z);
833        assert!((y_cross_z.x - x.x).abs() < f32::epsilon());
834        assert!((y_cross_z.y - x.y).abs() < f32::epsilon());
835        assert!((y_cross_z.z - x.z).abs() < f32::epsilon());
836        
837        let z_cross_x = Vector3::cross(&z, &x);
838        assert!((z_cross_x.x - y.x).abs() < f32::epsilon());
839        assert!((z_cross_x.y - y.y).abs() < f32::epsilon());
840        assert!((z_cross_x.z - y.z).abs() < f32::epsilon());
841        
842        // Test anti-commutativity: a × b = -(b × a)
843        let a = Vector3::<f32>::new(1.0, 2.0, 3.0);
844        let b = Vector3::<f32>::new(4.0, 5.0, 6.0);
845        let a_cross_b = Vector3::cross(&a, &b);
846        let b_cross_a = Vector3::cross(&b, &a);
847        assert!((a_cross_b.x + b_cross_a.x).abs() < f32::epsilon());
848        assert!((a_cross_b.y + b_cross_a.y).abs() < f32::epsilon());
849        assert!((a_cross_b.z + b_cross_a.z).abs() < f32::epsilon());
850        
851        // Test cross product with itself is zero
852        let self_cross = Vector3::cross(&a, &a);
853        assert!(self_cross.x.abs() < f32::epsilon());
854        assert!(self_cross.y.abs() < f32::epsilon());
855        assert!(self_cross.z.abs() < f32::epsilon());
856    }
857
858    #[test]
859    fn test_vector_distance() {
860        let v1 = Vector3::<f32>::new(1.0, 2.0, 3.0);
861        let v2 = Vector3::<f32>::new(4.0, 6.0, 3.0);
862        let dist = Vector3::distance(&v1, &v2);
863        assert!((dist - 5.0).abs() < f32::epsilon()); // sqrt(9 + 16 + 0) = 5
864        
865        // Distance to itself should be zero
866        let self_dist = Vector3::distance(&v1, &v1);
867        assert!(self_dist.abs() < f32::epsilon());
868    }
869
870    #[test]
871    fn test_vector_min_max() {
872        let v1 = Vector3::<f32>::new(1.0, 5.0, 3.0);
873        let v2 = Vector3::<f32>::new(4.0, 2.0, 6.0);
874        
875        let v_min = Vector3::min(&v1, &v2);
876        assert_eq!(v_min.x, 1.0);
877        assert_eq!(v_min.y, 2.0);
878        assert_eq!(v_min.z, 3.0);
879        
880        let v_max = Vector3::max(&v1, &v2);
881        assert_eq!(v_max.x, 4.0);
882        assert_eq!(v_max.y, 5.0);
883        assert_eq!(v_max.z, 6.0);
884    }
885
886    #[test]
887    fn test_vector_arithmetic() {
888        let v1 = Vector3::<f32>::new(1.0, 2.0, 3.0);
889        let v2 = Vector3::<f32>::new(4.0, 5.0, 6.0);
890        
891        // Addition
892        let sum = v1 + v2;
893        assert_eq!(sum.x, 5.0);
894        assert_eq!(sum.y, 7.0);
895        assert_eq!(sum.z, 9.0);
896        
897        // Subtraction
898        let diff = v2 - v1;
899        assert_eq!(diff.x, 3.0);
900        assert_eq!(diff.y, 3.0);
901        assert_eq!(diff.z, 3.0);
902        
903        // Component-wise multiplication
904        let prod = v1 * v2;
905        assert_eq!(prod.x, 4.0);
906        assert_eq!(prod.y, 10.0);
907        assert_eq!(prod.z, 18.0);
908        
909        // Component-wise division
910        let div = v2 / v1;
911        assert_eq!(div.x, 4.0);
912        assert_eq!(div.y, 2.5);
913        assert_eq!(div.z, 2.0);
914        
915        // Scalar multiplication
916        let scaled = v1 * 2.0;
917        assert_eq!(scaled.x, 2.0);
918        assert_eq!(scaled.y, 4.0);
919        assert_eq!(scaled.z, 6.0);
920        
921        // Scalar division
922        let divided = v2 / 2.0;
923        assert_eq!(divided.x, 2.0);
924        assert_eq!(divided.y, 2.5);
925        assert_eq!(divided.z, 3.0);
926        
927        // Negation
928        let neg = -v1;
929        assert_eq!(neg.x, -1.0);
930        assert_eq!(neg.y, -2.0);
931        assert_eq!(neg.z, -3.0);
932    }
933
934    #[test]
935    fn test_swizzle_operations() {
936        let v2 = Vector2::<f32>::new(1.0, 2.0);
937        
938        assert_eq!(v2.xx().x, 1.0);
939        assert_eq!(v2.xx().y, 1.0);
940        
941        assert_eq!(v2.xy().x, 1.0);
942        assert_eq!(v2.xy().y, 2.0);
943        
944        assert_eq!(v2.yx().x, 2.0);
945        assert_eq!(v2.yx().y, 1.0);
946        
947        assert_eq!(v2.yy().x, 2.0);
948        assert_eq!(v2.yy().y, 2.0);
949        
950        let v3 = Vector3::<f32>::new(1.0, 2.0, 3.0);
951        
952        assert_eq!(v3.xz().x, 1.0);
953        assert_eq!(v3.xz().y, 3.0);
954        
955        assert_eq!(v3.zy().x, 3.0);
956        assert_eq!(v3.zy().y, 2.0);
957        
958        let v3_swizzle = v3.zyx();
959        assert_eq!(v3_swizzle.x, 3.0);
960        assert_eq!(v3_swizzle.y, 2.0);
961        assert_eq!(v3_swizzle.z, 1.0);
962    }
963
964    #[test]
965    fn test_vector_rem_operation() {
966        let v1 = Vector3::<i32>::new(10, 15, 20);
967        let v2 = Vector3::<i32>::new(3, 4, 6);
968        
969        let rem = v1 % v2;
970        assert_eq!(rem.x, 1); // 10 % 3 = 1
971        assert_eq!(rem.y, 3); // 15 % 4 = 3
972        assert_eq!(rem.z, 2); // 20 % 6 = 2
973        
974        let v3 = Vector3::<i32>::new(10, 15, 20);
975        let rem_scalar = v3 % 7;
976        assert_eq!(rem_scalar.x, 3); // 10 % 7 = 3
977        assert_eq!(rem_scalar.y, 1); // 15 % 7 = 1
978        assert_eq!(rem_scalar.z, 6); // 20 % 7 = 6
979    }
980}