vec3-rs 0.3.3

minimal 3d vector implementation
Documentation
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! This crate provides a simple implementation of 3D vectors in Rust. Supports any numeric type trough num-traits.

#![cfg_attr(not(feature = "std"), no_std)]

mod consts;
mod convert;
#[cfg(any(feature = "std", feature = "libm"))]
mod float_lerp;
mod ops;
mod ops_scalar;

#[cfg(any(feature = "std", feature = "libm"))]
use float_lerp::Lerp;
#[cfg(any(feature = "std", feature = "libm"))]
use num_traits::clamp;
#[cfg(feature = "random")]
use rand::{
    RngExt,
    distr::uniform::{SampleRange, SampleUniform},
    make_rng,
    rngs::SmallRng,
};

#[cfg(feature = "random")]
thread_local! {
    static RNG: std::cell::RefCell<SmallRng> = std::cell::RefCell::new(make_rng());
}

/// Trait representing accepted coordonate kind `T` for `Vector3<T>`.
pub trait Vector3Coordinate:
    num_traits::Num
    + num_traits::ToPrimitive
    + PartialOrd
    + core::fmt::Display
    + core::ops::AddAssign
    + core::ops::SubAssign
    + core::ops::MulAssign
    + core::ops::DivAssign
    + Clone
{
}

impl<T> Vector3Coordinate for T where
    T: num_traits::Num
        + num_traits::ToPrimitive
        + PartialOrd
        + core::fmt::Display
        + core::ops::AddAssign
        + core::ops::SubAssign
        + core::ops::MulAssign
        + core::ops::DivAssign
        + Clone
{
}

/// Represents a vector in 3D space.
#[derive(Debug, PartialEq, Eq, Default, Clone, Copy, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Vector3<T: Vector3Coordinate> {
    x: T,
    y: T,
    z: T,
}

#[cfg(any(feature = "std", feature = "libm"))]
impl<T: Vector3Coordinate + num_traits::Float> Vector3<T> {
    /// Checks if this vector is approximately equal to another vector within a given epsilon.
    ///
    /// # Panics
    ///
    /// Panics if `epsilon` is negative.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec3_rs::Vector3;
    ///
    /// let v1 = Vector3::new(0.1, 0.2, 0.3);
    /// let v2 = Vector3::new(0.101, 0.199, 0.299);
    ///
    /// let epsilon = 0.01;
    /// let is_approx_equal = v1.fuzzy_equal(&v2, epsilon);
    /// assert!(is_approx_equal)
    /// ```
    #[must_use]
    #[inline]
    pub fn fuzzy_equal(&self, target: &Self, epsilon: T) -> bool {
        assert!(epsilon.is_sign_positive());
        // unrolled for performance
        (self.x - target.x).abs() <= epsilon
            && (self.y - target.y).abs() <= epsilon
            && (self.z - target.z).abs() <= epsilon
    }

    /// Linearly interpolates between this vector and another vector by a given ratio.
    #[must_use]
    #[inline]
    pub fn lerp(&self, target: &Self, alpha: T) -> Self {
        Self {
            x: self.x.lerp(target.x, alpha),
            y: self.y.lerp(target.y, alpha),
            z: self.z.lerp(target.z, alpha),
        }
    }

    /// Computes the magnitude (length) of the vector.
    #[must_use]
    #[inline]
    pub fn magnitude(&self) -> T {
        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
    }

    /// Computes the angle in radians between this vector and another vector.
    #[must_use]
    #[inline]
    pub fn angle(&self, target: Self) -> T {
        let dot_product = self.dot(target);
        let magnitude_product = self.magnitude() * target.magnitude();
        (dot_product / magnitude_product).acos()
    }

    /// Computes the angle in degrees between this vector and another vector.
    #[must_use]
    #[inline]
    pub fn angle_deg(&self, target: Self) -> T
    where
        T: From<f64>,
    {
        const COEFF: f64 = 180.0 / core::f64::consts::PI;
        self.angle(target) * From::from(COEFF)
    }

    /// Scales the vector such that its magnitude becomes 1.
    #[inline]
    pub fn normalize(&mut self) {
        *self /= self.magnitude();
    }

    /// Computes the distance between this vector and another vector.
    #[must_use]
    #[inline]
    pub fn distance(&self, target: Self) -> T {
        (*self - target).magnitude()
    }

    /// Projects this vector onto another vector.
    #[must_use]
    #[inline]
    pub fn project(&self, on_normal: Self) -> Self {
        on_normal * (self.dot(on_normal) / on_normal.dot(on_normal))
    }

    /// Reflects this vector off a surface defined by a normal.
    #[must_use]
    #[inline]
    pub fn reflect(&self, normal: Self) -> Self {
        let two = T::one() + T::one();
        *self - (normal * (self.dot(normal) * two))
    }

    /// Inverts the components of the vector.
    #[must_use]
    #[inline]
    pub fn inverse(&self) -> Self {
        let one = T::one();
        Self {
            x: one / self.x,
            y: one / self.y,
            z: one / self.z,
        }
    }

    /// Returns a new vector with the absolute value of each component.
    #[must_use]
    #[inline]
    pub fn abs(&self) -> Self {
        Self {
            x: self.x.abs(),
            y: self.y.abs(),
            z: self.z.abs(),
        }
    }

    /// Returns a new vector with the ceiling of each component.
    #[must_use]
    #[inline]
    pub fn ceil(&self) -> Self {
        Self {
            x: self.x.ceil(),
            y: self.y.ceil(),
            z: self.z.ceil(),
        }
    }

    /// Returns a new vector with the floor of each component.
    #[must_use]
    #[inline]
    pub fn floor(&self) -> Self {
        Self {
            x: self.x.floor(),
            y: self.y.floor(),
            z: self.z.floor(),
        }
    }

    /// Returns a new vector with the rounded value of each component.
    #[must_use]
    #[inline]
    pub fn round(&self) -> Self {
        Self {
            x: self.x.round(),
            y: self.y.round(),
            z: self.z.round(),
        }
    }

    /// Returns a new vector with each component clamped to a given range.
    #[must_use]
    #[inline]
    pub fn clamp(&self, min: T, max: T) -> Self {
        Self {
            x: clamp(self.x, min, max),
            y: clamp(self.y, min, max),
            z: clamp(self.z, min, max),
        }
    }

    /// Rotates the vector around an axis by a given angle in radians.
    #[must_use]
    #[inline]
    pub fn rotated(&self, axis: Self, angle: T) -> Self {
        let (sin, cos) = angle.sin_cos();
        let axis_normalized = axis / axis.magnitude();

        let term1 = *self * cos;
        let term2 = axis_normalized.cross(*self) * sin;
        let term3_scalar = axis_normalized.dot(*self) * (T::one() - cos);
        let term3 = axis_normalized * term3_scalar;

        term1 + term2 + term3
    }

    /// Creates a new `Vector3` from spherical coordinates.
    ///
    /// # Arguments
    ///
    /// * `radius` - The distance from the origin.
    /// * `polar` - The polar angle (the angle from the z-axis, in radians).
    /// * `azimuth` - The azimuth angle (the angle from the x-axis in the xy-plane, in radians).
    #[must_use]
    #[inline]
    pub fn from_spherical(radius: T, polar: T, azimuth: T) -> Self {
        let (sin_polar, cos_polar) = polar.sin_cos();
        let (sin_azimuth, cos_azimuth) = azimuth.sin_cos();
        Self {
            x: radius * sin_polar * cos_azimuth,
            y: radius * sin_polar * sin_azimuth,
            z: radius * cos_polar,
        }
    }

    /// Generates a random Vector3 with components in the range [0.0, 1.0).
    #[cfg(feature = "random")]
    #[must_use]
    #[inline]
    pub fn random() -> Self
    where
        rand::distr::StandardUniform: rand::prelude::Distribution<T>,
    {
        RNG.with_borrow_mut(|thread| Self {
            x: thread.random(),
            y: thread.random(),
            z: thread.random(),
        })
    }

    /// Generates a random Vector3 with components in the given ranges.
    #[cfg(feature = "random")]
    #[must_use]
    #[inline]
    pub fn random_range(
        range_x: impl SampleRange<T>,
        range_y: impl SampleRange<T>,
        range_z: impl SampleRange<T>,
    ) -> Self
    where
        rand::distr::StandardUniform: rand::prelude::Distribution<T>,
        T: SampleUniform,
    {
        RNG.with_borrow_mut(|thread| Self {
            x: thread.random_range(range_x),
            y: thread.random_range(range_y),
            z: thread.random_range(range_z),
        })
    }
}

impl<T: Vector3Coordinate> Vector3<T> {
    /// Creates a new Vector3 with the specified coordinates.
    ///
    /// # Examples
    ///
    /// ```
    /// type Vector3 = vec3_rs::Vector3<f64>;
    ///
    /// let vector3 = Vector3::new(1.0, 2.0, 3.0);
    /// let also_ok = Vector3::new(1, 2, 3);
    /// assert_eq!(vector3, also_ok);
    ///
    /// // can also be created from arrays and tuples
    /// // but no automatic number conversion
    /// let from_array = Vector3::from([1.0, 2.0, 3.0]);
    /// let from_tuple = Vector3::from((1.0, 2.0, 3.0));
    /// assert_eq!(vector3, from_array);
    /// assert_eq!(vector3, from_tuple);
    ///
    /// // conversion is fallible with unknown sized data types
    /// let slice: &[f64] = [1.0, 2.0, 3.0].as_ref();
    /// let from_slice = Vector3::try_from(slice).unwrap();
    /// let from_vec = Vector3::try_from(vec![1.0, 2.0, 3.0]).unwrap();
    /// assert_eq!(vector3, from_slice);
    /// assert_eq!(vector3, from_vec);
    ///
    /// ```
    pub fn new<U: Into<T>>(x: U, y: U, z: U) -> Self {
        let (x, y, z) = (x.into(), y.into(), z.into());
        Self { x, y, z }
    }

    /// Computes the dot product between this vector and another vector.
    #[must_use]
    #[inline]
    pub fn dot(&self, target: Self) -> T {
        let (x, y, z): (T, T, T) = target.into();
        self.x.clone() * x + self.y.clone() * y + self.z.clone() * z
    }

    /// Computes the cross product between this vector and another vector.
    #[must_use]
    #[inline]
    pub fn cross(&self, target: Self) -> Self {
        let (x, y, z): (T, T, T) = target.into();
        Self {
            x: self.y.clone() * z.clone() - self.z.clone() * y.clone(),
            y: self.z.clone() * x.clone() - self.x.clone() * z,
            z: self.x.clone() * y - self.y.clone() * x,
        }
    }

    /// Computes the component-wise maximum of this vector and another vector.
    #[must_use]
    #[inline]
    pub fn max(&self, target: &Self) -> Self {
        let x = if self.x > target.x {
            self.x.clone()
        } else {
            target.x.clone()
        };
        let y = if self.y > target.y {
            self.y.clone()
        } else {
            target.y.clone()
        };
        let z = if self.z > target.z {
            self.z.clone()
        } else {
            target.z.clone()
        };
        Self { x, y, z }
    }

    /// Computes the component-wise minimum of this vector and another vector.
    #[must_use]
    #[inline]
    pub fn min(&self, target: &Self) -> Self {
        let x = if self.x < target.x {
            self.x.clone()
        } else {
            target.x.clone()
        };
        let y = if self.y < target.y {
            self.y.clone()
        } else {
            target.y.clone()
        };
        let z = if self.z < target.z {
            self.z.clone()
        } else {
            target.z.clone()
        };
        Self { x, y, z }
    }

    /// Retrieves the X component of the vector.
    pub const fn x(&self) -> &T {
        &self.x
    }

    /// Retrieves the Y component of the vector.
    pub const fn y(&self) -> &T {
        &self.y
    }

    /// Retrieves the Z component of the vector.
    pub const fn z(&self) -> &T {
        &self.z
    }
}

impl<T: Vector3Coordinate> core::fmt::Display for Vector3<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Vector3({}, {}, {})", self.x, self.y, self.z)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::ops::Sub;

    #[test]
    fn angle() {
        let angle = core::f64::consts::PI / 2.0;
        let calc_angle = Vector3::<f64>::x_axis().angle(Vector3::<f64>::y_axis());
        assert!(calc_angle.sub(angle) <= f64::EPSILON);
    }

    #[test]
    fn create() {
        let my_vec: Vector3<f64> = Vector3::new(1.3, 0.0, -5.35501);
        assert!((my_vec.x() - 1.3f64).abs() <= f64::EPSILON);
        assert!((my_vec.y() - 0.0f64).abs() <= f64::EPSILON);
        assert!((my_vec.z() - -5.35501f64).abs() <= f64::EPSILON);
    }

    #[test]
    fn sum() {
        let vec1: Vector3<f64> = Vector3::new(1.0, 2.0, 3.0);
        let vec2 = Vector3::new(5.0, 0.0, -1.0);
        assert_eq!(vec1 + vec2, Vector3::new(6.0, 2.0, 2.0));
    }

    #[test]
    fn normalization() {
        let mut test_vec: Vector3<f64> = Vector3::new(1.0, 2.3, 100.123);
        test_vec.normalize();
        assert_eq!(
            test_vec,
            Vector3::new(
                0.009_984_583_160_766_44,
                0.022_964_541_269_762_81,
                0.999_686_419_805_418_3
            )
        );
        assert!((1.0 - test_vec.magnitude()).abs() <= f64::EPSILON);
    }

    #[test]
    fn lerp() {
        let start = Vector3::new(0.0, 0.0, 0.0);
        let end = Vector3::new(1.0, 2.0, 3.0);
        let lerp_result = start.lerp(&end, 0.75);
        assert_eq!(lerp_result, Vector3::new(0.75, 1.5, 2.25));
    }

    #[test]
    fn dot_product() {
        let vec1: Vector3<f64> = Vector3::new(1.0, 2.0, 3.0);
        let vec2 = Vector3::new(5.0, 0.0, -1.0);
        let dot_result = vec1.dot(vec2);
        assert!((dot_result - 2.0f64).abs() <= f64::EPSILON);
    }

    #[test]
    fn cross_product() {
        let vec1: Vector3<f64> = Vector3::new(1.0, 0.0, 0.0);
        let vec2 = Vector3::new(0.0, 1.0, 0.0);
        let cross_result = vec1.cross(vec2);
        assert_eq!(cross_result, Vector3::new(0.0, 0.0, 1.0));
    }

    #[test]
    fn max_components() {
        let vec1: Vector3<f64> = Vector3::new(1.0, 5.0, 3.0);
        let vec2 = Vector3::new(3.0, 2.0, 4.0);
        let max_result = vec1.max(&vec2);
        assert_eq!(max_result, Vector3::new(3.0, 5.0, 4.0));
    }

    #[test]
    fn min_components() {
        let vec1: Vector3<f64> = Vector3::new(1.0, 5.0, 3.0);
        let vec2 = Vector3::new(3.0, 2.0, 4.0);
        let min_result = vec1.min(&vec2);
        assert_eq!(min_result, Vector3::new(1.0, 2.0, 3.0));
    }

    #[test]
    fn fuzzy_equality() {
        let vec1 = Vector3::new(1.0, 2.0, 3.0);
        let vec2 = Vector3::new(1.01, 1.99, 3.01);
        let epsilon = 0.02;
        let fuzzy_equal_result = vec1.fuzzy_equal(&vec2, epsilon);
        assert!(fuzzy_equal_result);
    }

    #[test]
    fn distance() {
        let v1: Vector3<f64> = Vector3::new(1.0, 2.0, 3.0);
        let v2 = Vector3::new(4.0, 6.0, 8.0);
        assert!((v1.distance(v2) - (50.0f64).sqrt()).abs() <= f64::EPSILON);
    }

    #[test]
    fn project() {
        let v: Vector3<f64> = Vector3::new(1.0, 2.0, 3.0);
        let on_normal = Vector3::new(1.0, 0.0, 0.0);
        let expected = Vector3::new(1.0, 0.0, 0.0);
        assert_eq!(v.project(on_normal), expected);
    }

    #[test]
    fn reflect() {
        let v: Vector3<f64> = Vector3::new(1.0, -1.0, 0.0);
        let normal = Vector3::new(0.0, 1.0, 0.0);
        let expected = Vector3::new(1.0, 1.0, 0.0);
        assert_eq!(v.reflect(normal), expected);
    }

    #[test]
    fn inverse() {
        let v: Vector3<f64> = Vector3::new(2.0, 4.0, 8.0);
        let expected = Vector3::new(0.5, 0.25, 0.125);
        assert_eq!(v.inverse(), expected);
    }

    #[test]
    fn abs() {
        let v: Vector3<f64> = Vector3::new(-1.0, -2.0, 3.0);
        let expected = Vector3::new(1.0, 2.0, 3.0);
        assert_eq!(v.abs(), expected);
    }

    #[test]
    fn ceil() {
        let v: Vector3<f64> = Vector3::new(1.1, 2.9, 3.0);
        let expected = Vector3::new(2.0, 3.0, 3.0);
        assert_eq!(v.ceil(), expected);
    }

    #[test]
    fn floor() {
        let v: Vector3<f64> = Vector3::new(1.1, 2.9, 3.0);
        let expected = Vector3::new(1.0, 2.0, 3.0);
        assert_eq!(v.floor(), expected);
    }

    #[test]
    fn round() {
        let v: Vector3<f64> = Vector3::new(1.1, 2.9, 3.5);
        let expected = Vector3::new(1.0, 3.0, 4.0);
        assert_eq!(v.round(), expected);
    }

    #[test]
    fn clamp() {
        let v = Vector3::new(0.0, 5.0, 10.0);
        let min = 1.0;
        let max = 9.0;
        let expected = Vector3::new(1.0, 5.0, 9.0);
        assert_eq!(v.clamp(min, max), expected);
    }

    #[test]
    fn rotated() {
        let v = Vector3::new(1.0, 0.0, 0.0);
        let axis = Vector3::new(0.0, 0.0, 1.0);
        let angle = core::f64::consts::FRAC_PI_2;
        let rotated = v.rotated(axis, angle);
        let expected = Vector3::new(0.0, 1.0, 0.0);
        assert!(rotated.fuzzy_equal(&expected, 1e-15));
    }

    #[test]
    fn from_spherical() {
        let radius = 1.0;
        let polar = core::f64::consts::FRAC_PI_2;
        let azimuth = 0.0;
        let v = Vector3::from_spherical(radius, polar, azimuth);
        let expected = Vector3::new(1.0, 0.0, 0.0);
        assert!(v.fuzzy_equal(&expected, 1e-15));
    }

    #[test]
    fn nan_dont_panic() {
        let mut vec1: Vector3<f64> = Vector3::default();
        vec1 /= f64::NAN;
    }

    #[test]
    fn readme_example() {
        let mut v1: Vector3<f64> = Vector3::new(1.0, 2.0, 3.0);
        let mut v2: Vector3<f64> = Vector3::new(3.0, 1.0, 2.0);

        // Basic operations
        let sum = v1 + v2;
        let difference = v1 - v2;
        let dot_product = v1.dot(v2);
        let cross_product = v1.cross(v2);

        // Other methods
        let lerp_result = v1.lerp(&v2, 0.5);
        let angle = v1.angle(v2);
        let fuzzy_equal = v1.fuzzy_equal(&v2, 0.001);

        println!("Sum: {sum}");
        println!("Difference: {difference}");
        println!("Dot product: {dot_product}");
        println!("Cross product: {cross_product}");
        println!("Lerp 50%: {lerp_result}");
        println!("Angle: {angle}");
        print!("Are they close enough?: {fuzzy_equal}");

        v1.normalize();
        v2.normalize();

        println!("v1 normalized: {v1}");
        println!("v2 normalized: {v2}");
    }
    #[test]
    fn conversion_box() {
        let correct = Vector3::new(1, 2, 3);
        let x = String::from("Vector3(1,2,3)").into_boxed_str();
        assert_eq!(x.parse::<Vector3<i32>>().unwrap(), correct);
    }
    #[test]
    fn from_slice() {
        let correct = Vector3::new(1, 2, 3);
        let arr = [1, 2, 3].as_ref();
        let x = Vector3::try_from(arr).unwrap();
        assert_eq!(correct, x);
    }

    #[test]
    fn from_box_slice() {
        let correct = Vector3::new(1, 2, 3);
        let arr: Box<[i32]> = Box::from([1, 2, 3].as_ref());
        let x = Vector3::try_from(arr).unwrap();
        assert_eq!(correct, x);
    }
}