Skip to main content

ty_math/
ty_vector3.rs

1use std::ops::{Add, Mul, Sub};
2
3/// A 3D vector with `f64` components.
4#[derive(Clone, Copy, Debug, Default, PartialEq)]
5pub struct TyVector3 {
6    pub x: f64,
7    pub y: f64,
8    pub z: f64,
9}
10
11impl TyVector3 {
12    /// Creates a new vector from `x`, `y`, and `z` components.
13    pub fn new(x: f64, y: f64, z: f64) -> Self {
14        Self { x, y, z }
15    }
16
17    /// Returns the cross product of `self` and `other`.
18    pub fn cross(&self, other: &Self) -> Self {
19        Self {
20            x: self.y * other.z - self.z * other.y,
21            y: self.z * other.x - self.x * other.z,
22            z: self.x * other.y - self.y * other.x,
23        }
24    }
25
26    /// Returns the Euclidean length of this vector.
27    pub fn magnitude(&self) -> f64 {
28        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
29    }
30}
31
32impl Add for TyVector3 {
33    type Output = Self;
34
35    fn add(self, rhs: Self) -> Self {
36        Self {
37            x: self.x + rhs.x,
38            y: self.y + rhs.y,
39            z: self.z + rhs.z,
40        }
41    }
42}
43
44impl Sub for TyVector3 {
45    type Output = Self;
46
47    fn sub(self, rhs: Self) -> Self {
48        Self {
49            x: self.x - rhs.x,
50            y: self.y - rhs.y,
51            z: self.z - rhs.z,
52        }
53    }
54}
55
56impl Mul<f64> for TyVector3 {
57    type Output = Self;
58
59    fn mul(self, rhs: f64) -> Self {
60        Self {
61            x: self.x * rhs,
62            y: self.y * rhs,
63            z: self.z * rhs,
64        }
65    }
66}
67
68impl Mul<TyVector3> for f64 {
69    type Output = TyVector3;
70
71    fn mul(self, rhs: TyVector3) -> TyVector3 {
72        TyVector3 {
73            x: self * rhs.x,
74            y: self * rhs.y,
75            z: self * rhs.z,
76        }
77    }
78}