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
use crate::NearlyEqual;

/// A vector in 2D space.
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub struct Vector2 {
    pub x: f32,
    pub y: f32,
}

/// A vector in 3D space.
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

/// A point in 3D space.
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub struct Point {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

/// A homogeneous vector in 3D space.
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub struct Vector4 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub w: f32,
}

macro_rules! implement_operator {
    // Binary operator
    (impl $Op:ident<$S:ident> for $T:ident {
        fn $op:ident($x:ident, $s:ident) -> $Output:ty $body:block
    }) => {
        impl std::ops::$Op<$S> for $T {
            type Output = $Output;

            fn $op($x, $s: $S) -> Self::Output $body
        }
    };
    // Binary assignment operator
    (impl $Op:ident<$S:ident> for $T:ident {
        fn $op:ident(&mut $x:ident, $s:ident) $body:block
    }) => {
        impl std::ops::$Op<$S> for $T {
            fn $op(&mut $x, $s: $S) $body
        }
    };
}

macro_rules! implement_vector {
    ($VectorT:ident { $($field:ident),+ }) => {
        impl $VectorT {
            /// Construct new a vector from individual coordinates
            pub const fn new($($field: f32),+) -> Self {
                Self { $($field),+ }
            }

            /// Construct new a vector where each coordinate is the same
            pub const fn from_scalar(s: f32) -> Self {
                Self { $($field: s),+ }
            }

            /// The additive identity
            pub const fn zero() -> Self {
                Self { $($field: 0.0),+ }
            }

            /// The multiplicative identity
            pub const fn one() -> Self {
                Self { $($field: 1.0),+ }
            }

            /// Compute the dot product between this vector and another
            pub fn dot(&self, rhs: Self) -> f32 {
                [$(self.$field * rhs.$field),+].iter().sum()
            }

            /// Linear interpolation between this vector and another
            pub fn lerp(&self, rhs: Self, factor: f32) -> Self {
                let t = factor.min(1.0).max(0.0);
                Self::new($(self.$field * (1.0 - t) + rhs.$field * t),+)
            }

            /// Compute the element-wise minimum of this vector and another
            pub fn min(&self, rhs: Self) -> Self {
                Self::new($(self.$field.min(rhs.$field)),+)
            }

            /// Compute the element-wise maximum of this vector and another
            pub fn max(&self, rhs: Self) -> Self {
                Self::new($(self.$field.max(rhs.$field)),+)
            }

            /// The length of this vector squared. Note that this avoids an expensive square root.
            pub fn magnitude_squared(&self) -> f32 {
                self.dot(*self)
            }

            /// The length of this vector. Note that this involves an expensive square root.
            pub fn magnitude(&self) -> f32 {
                self.magnitude_squared().sqrt()
            }

            /// Normalize this vector to unit length. Note that this involves an expensive square root.
            pub fn normalized(&self) -> Self {
                let d = self.magnitude();
                if d > 0.0 {
                    let d = 1.0 / d;
                    *self * d
                } else {
                    *self
                }
            }

            pub fn as_slice(&self) -> &[f32] {
                unsafe { std::slice::from_raw_parts(&self.x, std::mem::size_of::<Self>() / std::mem::size_of::<f32>()) }
            }
        }

        impl std::ops::Neg for $VectorT {
            type Output = $VectorT;
            fn neg(self) -> $VectorT { $VectorT::new($(-self.$field),+) }
        }

        implement_operator!(impl Add<f32> for $VectorT {
            fn add(self, t) -> $VectorT { $VectorT::new($(self.$field + t),+) }
        });
        implement_operator!(impl Sub<f32> for $VectorT {
            fn sub(self, t) -> $VectorT { $VectorT::new($(self.$field - t),+) }
        });
        implement_operator!(impl Mul<f32> for $VectorT {
            fn mul(self, t) -> $VectorT { $VectorT::new($(self.$field * t),+) }
        });
        implement_operator!(impl Div<f32> for $VectorT {
            fn div(self, t) -> $VectorT { $VectorT::new($(self.$field / t),+) }
        });

        implement_operator!(impl AddAssign<f32> for $VectorT {
            fn add_assign(&mut self, t) { $(self.$field += t);+ }
        });
        implement_operator!(impl SubAssign<f32> for $VectorT {
            fn sub_assign(&mut self, t) { $(self.$field -= t);+ }
        });
        implement_operator!(impl MulAssign<f32> for $VectorT {
            fn mul_assign(&mut self, t) { $(self.$field *= t);+ }
        });
        implement_operator!(impl DivAssign<f32> for $VectorT {
            fn div_assign(&mut self, t) { $(self.$field /= t);+ }
        });

        implement_operator!(impl Mul<$VectorT> for f32 {
            fn mul(self, t) -> $VectorT { $VectorT::new($(self * t.$field),+) }
        });
        implement_operator!(impl Div<$VectorT> for f32 {
            fn div(self, t) -> $VectorT { $VectorT::new($(self / t.$field),+) }
        });

        impl std::ops::Index<usize> for $VectorT {
            type Output = f32;
            fn index(&self, i: usize) -> &f32 {
                [$(&self.$field),+][i]
            }
        }

        impl std::ops::IndexMut<usize> for $VectorT {
            fn index_mut(&mut self, i: usize) -> &mut f32 {
                [$(&mut self.$field),+][i]
            }
        }

        impl NearlyEqual for &$VectorT {
            fn nearly_equals(self, rhs: Self) -> bool {
                $(self.$field.nearly_equals(rhs.$field))&&+
            }
        }
    }
}

implement_vector!(Vector2 { x, y });
implement_vector!(Vector3 { x, y, z });
implement_vector!(Point { x, y, z });
implement_vector!(Vector4 { x, y, z, w });

impl Vector2 {
    /// Compute a cross product between this vector and another.
    /// This treats both inputs as 3D vectors with a z-component of zero,
    /// performs the normal 3D cross product, and returns only the resulting z-component.
    pub fn cross(&self, rhs: Self) -> f32 {
        self.x * rhs.y - self.y * rhs.x
    }
}

impl Vector3 {
    /// Compute the cross product between this vector and another.
    pub fn cross(&self, rhs: Self) -> Self {
        Self {
            x: self.y * rhs.z - self.z * rhs.y,
            y: self.z * rhs.x - self.x * rhs.z,
            z: self.x * rhs.y - self.y * rhs.x,
        }
    }
}

impl From<Point> for Vector3 {
    /// Convert a point into a vector
    fn from(p: Point) -> Self {
        Vector3 {
            x: p.x,
            y: p.y,
            z: p.z,
        }
    }
}

impl From<Vector4> for Vector3 {
    /// Convert a point into a vector
    fn from(v: Vector4) -> Self {
        Vector3 {
            x: v.x,
            y: v.y,
            z: v.z,
        }
    }
}

impl From<Vector3> for Point {
    /// Convert a vector into a point
    fn from(v: Vector3) -> Self {
        Point {
            x: v.x,
            y: v.y,
            z: v.z,
        }
    }
}

impl From<Vector4> for Point {
    /// Convert a vector into a point
    fn from(v: Vector4) -> Self {
        Point {
            x: v.x,
            y: v.y,
            z: v.z,
        }
    }
}

impl From<Vector3> for Vector4 {
    /// Convert a point into a vector
    fn from(v: Vector3) -> Self {
        Vector4 {
            x: v.x,
            y: v.y,
            z: v.z,
            w: 0.0,
        }
    }
}

impl From<Point> for Vector4 {
    /// Convert a point into a vector
    fn from(p: Point) -> Self {
        Vector4 {
            x: p.x,
            y: p.y,
            z: p.z,
            w: 1.0,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn products() {
        let a = Vector3::new(3.0, -5.0, 4.0);
        let b = Vector3::new(2.0, 6.0, 5.0);

        assert!(a.dot(b).nearly_equals(-4.0));
        assert_eq!(a.cross(b), Vector3::new(-49.0, -7.0, 28.0));
    }

    #[test]
    fn lerp() {
        let a = Vector3::new(1.0, 0.0, 0.0);
        let b = Vector3::new(0.0, 1.0, 0.0);

        assert_eq!(a.lerp(b, 0.75), Vector3::new(0.25, 0.75, 0.0));
    }

    #[test]
    fn slice() {
        let a = Vector3::new(1.0, 2.0, 3.0);

        assert_eq!(a.as_slice(), &[1.0, 2.0, 3.0]);
    }
}