webgl_matrix/vector.rs
1/// The base Vector trait
2///
3/// Note that vector operations are permitted on slices.
4/// This is useful for WebGl vertex storages, where many vectors are stored in
5/// a single array. The caveat obviously is the potential for errors. Sadly
6/// there is no secure alternative for handling this use-case.
7pub trait Vector {
8 type VectorType;
9
10 /// Create a vector filled with zeros
11 fn zeros() -> Self::VectorType;
12
13 /// Create a vector filled with ones
14 fn ones() -> Self::VectorType;
15
16 /// Perform element-wise multiplication with the given right-hand-side operand
17 fn mul(&self, rhs: &[f32]) -> Self::VectorType;
18
19 /// Perform element-wise addition with the given right-hand-side operand
20 fn add(&self, rhs: &[f32]) -> Self::VectorType;
21 /// Perform element-wise substraction with the given right-hand-side operand
22 fn sub(&self, rhs: &[f32]) -> Self::VectorType;
23
24 /// Scale the vector elment-wise by the given constant
25 fn scale(&self, factor: f32) -> Self::VectorType;
26
27 /// Calculate the magnitude of this vector
28 fn mag(&self) -> f32;
29
30 /// Calculate the squared magnitude of this vector
31 fn mag2(&self) -> f32;
32
33 /// Calculate the dot product of this vector and the given right-hand-side operand
34 fn dot(&self, rhs: &[f32]) -> f32;
35}
36
37#[cfg(any(feature = "Matrix4", feature = "Matrix3"))]
38/// Adds matrix operations to vector types.
39pub trait MulVectorMatrix<Matrix> {
40 type VectorType;
41
42 /// Interprets `self` as a column vector and multiplies the given matrix
43 /// from the left-hand-side, i.e. `lhs * self`
44 fn mul_matrix_left(&self, lhs: &Matrix) -> Self::VectorType;
45
46 /// Interprets `self` as a row vector and multiplies the given matrix
47 /// from the right-hand-side, i.e. `self * rhs`
48 fn mul_matrix(&self, rhs: &Matrix) -> Self::VectorType;
49}
50
51macro_rules! impl_vector {
52 ($type:ty, $n:expr) => {
53 impl Vector for $type {
54 type VectorType = $type;
55 fn zeros() -> $type {
56 [0.; $n]
57 }
58
59 fn ones() -> $type {
60 [1.; $n]
61 }
62
63 fn mul(&self, rhs: &[f32]) -> $type {
64 let mut dst = *self;
65 mul(&mut dst, rhs);
66 dst
67 }
68
69 fn add(&self, rhs: &[f32]) -> $type {
70 let mut dst = *self;
71 add(&mut dst, rhs);
72 dst
73 }
74
75 fn sub(&self, rhs: &[f32]) -> $type {
76 let mut dst = *self;
77 sub(&mut dst, rhs);
78 dst
79 }
80
81 fn scale(&self, factor: f32) -> $type {
82 let mut dst = *self;
83 scale(&mut dst, factor);
84 dst
85 }
86
87 fn mag(&self) -> f32 {
88 mag(self)
89 }
90
91 fn mag2(&self) -> f32 {
92 mag2(self)
93 }
94
95 fn dot(&self, rhs: &[f32]) -> f32 {
96 dot(self, rhs)
97 }
98 }
99 };
100}