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
use crate::vector::Base;
use crate::vector::Component;
use std::fmt;
use std::ops::*;
#[doc = "A vector with x, y and z components"]
#[doc = "derives traits: Default, Debug, PartialEq, Eq, Copy, Clone, Hash"]
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone, Hash)]
pub struct Vector3<T: Component> {
pub x: T,
pub y: T,
pub z: T,
}
impl<T: Component + fmt::Display> fmt::Display for Vector3<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
return write!(f, "Vector3 - (x:{0}, y:{1}, z:{2})", self.x, self.y, self.z);
}
}
impl<T: Component> Base<T> for Vector3<T> {
#[doc = "Return the magnitude of the vector, sqrt(x^2 + y^2 + z^2)"]
fn magnitude(&self) -> T {
return (self.x * self.x + self.y * self.y + self.z * self.z).sqrt();
}
#[doc = "Shrink vector to have magnitude of 1"]
fn normalize(&mut self) -> Vector3<T> {
*self = *self / self.magnitude();
return *self;
}
}
impl<T: Component> Add<Vector3<T>> for Vector3<T> {
type Output = Vector3<T>;
#[doc = "Add a Vector3 to another Vector3"]
fn add(self, rhs: Vector3<T>) -> Vector3<T> {
return Vector3::<T> {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
};
}
}
impl<T: Component> Sub<Vector3<T>> for Vector3<T> {
type Output = Vector3<T>;
#[doc = "Subtract a Vector3 from another Vector3"]
fn sub(self, rhs: Vector3<T>) -> Vector3<T> {
return Vector3::<T> {
x: self.x - rhs.x,
y: self.y - rhs.y,
z: self.z - rhs.z,
};
}
}
impl<T: Component + Neg<Output = T>> Neg for Vector3<T> {
type Output = Vector3<T>;
#[doc = "Reverse the sign of the vector's components"]
fn neg(self) -> Vector3<T> {
return Vector3::<T> {
x: -self.x,
y: -self.y,
z: -self.z,
};
}
}
impl<T: Component> Mul<T> for Vector3<T> {
type Output = Vector3<T>;
#[doc = "Multiply a Vector3 by a scalar"]
fn mul(self, rhs: T) -> Vector3<T> {
return Vector3 {
x: self.x * rhs,
y: self.y * rhs,
z: self.z * rhs,
};
}
}
impl<T: Component> Div<T> for Vector3<T> {
type Output = Vector3<T>;
#[doc = "Divide a Vector3 by a scalar"]
fn div(self, rhs: T) -> Vector3<T> {
return Vector3 {
x: self.x / rhs,
y: self.y / rhs,
z: self.z / rhs,
};
}
}