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
// Oliver Berzs
// https://github.com/oberzs/duku

use std::iter::Sum;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Div;
use std::ops::DivAssign;
use std::ops::Index;
use std::ops::IndexMut;
use std::ops::Mul;
use std::ops::MulAssign;
use std::ops::Neg;
use std::ops::Sub;
use std::ops::SubAssign;

use super::Vec2;
use crate::color::Rgbf;

/// 3-component Vector.
///
/// Used for 3D sizing and positioning.
///
/// # Examples
///
/// ```no_run
/// # use duku::Duku;
/// # use duku::Vec3;
/// # let (mut d, _) = Duku::windowed(1, 1).unwrap();
/// let point1 = Vec3::new(-10.0, -10.0, -10.0);
/// let point2 = Vec3::new(10.0, 10.0, 10.0);
///
/// # d.draw(None, |t| {
/// // when drawing
/// t.debug_line(point1, point2);
/// # });
/// ```
#[repr(C)]
#[derive(Default, Debug, Copy, Clone, PartialEq)]
pub struct Vec3 {
    /// the X component
    pub x: f32,
    /// the Y component
    pub y: f32,
    /// the Z component
    pub z: f32,
}

impl Vec3 {
    /// Create a new vector
    pub const fn new(x: f32, y: f32, z: f32) -> Self {
        Self { x, y, z }
    }

    /// Create a vector facing up
    pub const fn up() -> Self {
        Self::new(0.0, 1.0, 0.0)
    }

    /// Create a vector facing down
    pub const fn down() -> Self {
        Self::new(0.0, -1.0, 0.0)
    }

    /// Create a vector facing left
    pub const fn left() -> Self {
        Self::new(-1.0, 0.0, 0.0)
    }

    /// Create a vector facing right
    pub const fn right() -> Self {
        Self::new(1.0, 0.0, 0.0)
    }

    /// Create a vector facing forward
    pub const fn forward() -> Self {
        Self::new(0.0, 0.0, 1.0)
    }

    /// Create a vector facing back
    pub const fn back() -> Self {
        Self::new(0.0, 0.0, -1.0)
    }

    /// Create a new vector with all components
    /// with the same value
    pub const fn uniform(v: f32) -> Self {
        Self::new(v, v, v)
    }

    /// Calculate the dot-product of the vector
    pub fn dot(&self, other: impl Into<Self>) -> f32 {
        let o = other.into();
        self.x * o.x + self.y * o.y + self.z * o.z
    }

    /// Calculate the cross-product of the vector
    pub fn cross(&self, other: impl Into<Self>) -> Self {
        let o = other.into();
        let x = self.y * o.z - self.z * o.y;
        let y = self.z * o.x - self.x * o.z;
        let z = self.x * o.y - self.y * o.x;
        Self::new(x, y, z)
    }

    /// Calculate the squared length of a vector
    ///
    /// Can sometimes use this instead of
    /// [length](crate::math::Vec3::length),
    /// because this is faster.
    pub fn sqr_length(&self) -> f32 {
        self.dot(*self)
    }

    /// Calculate the length of a vector
    pub fn length(&self) -> f32 {
        self.sqr_length().sqrt()
    }

    /// Calculate the unit vector
    ///
    /// The unit vector is of length 1 and can also be
    /// thought of as the direction of the vector.
    pub fn unit(&self) -> Self {
        let scale = 1.0 / self.length();
        *self * if scale.is_infinite() { 0.0 } else { scale }
    }

    /// Calculate the angle between 2 vectors
    ///
    /// Resulting angle is in degrees
    ///
    /// # Examples
    ///
    /// ```
    /// # use duku::Vec3;
    /// let up = Vec3::up();
    /// let right = Vec3::right();
    /// let angle = up.angle_between(right);
    /// // angle is ~90 degrees
    /// ```
    pub fn angle_between(&self, other: impl Into<Self>) -> f32 {
        let o = other.into();
        let cos = self.dot(o) / (self.length() * o.length());
        cos.acos().to_degrees()
    }

    /// Calculate the projected vector onto some other vector
    pub fn project_onto(&self, other: impl Into<Self>) -> Self {
        let o = other.into();
        let projected_length = self.dot(o) / o.length();
        o.unit() * projected_length
    }

    /// Get the [Vec2](crate::math::Vec2)
    /// made from this vectors x and y
    pub const fn xy(&self) -> Vec2 {
        Vec2::new(self.x, self.y)
    }

    /// Floor every component of the vector
    pub fn floor(&self) -> Self {
        Vec3::new(self.x.floor(), self.y.floor(), self.z.floor())
    }

    /// Ceil every component of the vector
    pub fn ceil(&self) -> Self {
        Vec3::new(self.x.ceil(), self.y.ceil(), self.z.ceil())
    }

    /// Round every component of the vector
    pub fn round(&self) -> Self {
        Vec3::new(self.x.round(), self.y.round(), self.z.round())
    }
}

impl From<[f32; 3]> for Vec3 {
    fn from(a: [f32; 3]) -> Self {
        Self::new(a[0], a[1], a[2])
    }
}

impl From<(Vec2, f32)> for Vec3 {
    fn from(v: (Vec2, f32)) -> Self {
        Self::new(v.0.x, v.0.y, v.1)
    }
}

impl From<Rgbf> for Vec3 {
    fn from(c: Rgbf) -> Self {
        Self::from([c.r, c.g, c.b])
    }
}

impl Index<usize> for Vec3 {
    type Output = f32;

    fn index(&self, index: usize) -> &f32 {
        match index {
            0 => &self.x,
            1 => &self.y,
            2 => &self.z,
            _ => panic!("index out of range {}", index),
        }
    }
}

impl IndexMut<usize> for Vec3 {
    fn index_mut(&mut self, index: usize) -> &mut f32 {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            2 => &mut self.z,
            _ => panic!("index out of range {}", index),
        }
    }
}

impl Neg for Vec3 {
    type Output = Self;

    fn neg(self) -> Self {
        Self::new(-self.x, -self.y, -self.z)
    }
}

impl Add<Self> for Vec3 {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
    }
}

impl<'vec> Sum<&'vec Vec3> for Vec3 {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = &'vec Self>,
    {
        iter.fold(Self::default(), |a, b| a + *b)
    }
}

impl Sub<Self> for Vec3 {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self {
        Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
    }
}

impl Mul<f32> for Vec3 {
    type Output = Self;

    fn mul(self, rhs: f32) -> Self {
        Self::new(self.x * rhs, self.y * rhs, self.z * rhs)
    }
}

impl Div<f32> for Vec3 {
    type Output = Self;

    fn div(self, rhs: f32) -> Self {
        Self::new(self.x / rhs, self.y / rhs, self.z / rhs)
    }
}

impl AddAssign<Self> for Vec3 {
    fn add_assign(&mut self, rhs: Self) {
        *self = *self + rhs;
    }
}

impl SubAssign<Self> for Vec3 {
    fn sub_assign(&mut self, rhs: Self) {
        *self = *self - rhs;
    }
}

impl MulAssign<f32> for Vec3 {
    fn mul_assign(&mut self, rhs: f32) {
        *self = *self * rhs;
    }
}

impl DivAssign<f32> for Vec3 {
    fn div_assign(&mut self, rhs: f32) {
        *self = *self / rhs;
    }
}

#[cfg(test)]
mod test {
    use super::Vec2;
    use super::Vec3;

    #[test]
    fn default() {
        let v = Vec3::default();
        assert_eq_delta!(v.x, 0.0);
        assert_eq_delta!(v.y, 0.0);
        assert_eq_delta!(v.z, 0.0);
    }

    #[test]
    fn new() {
        let v = Vec3::new(1.0, 2.0, 3.0);
        assert_eq_delta!(v.x, 1.0);
        assert_eq_delta!(v.y, 2.0);
        assert_eq_delta!(v.z, 3.0);
    }

    #[test]
    fn dot() {
        let a = Vec3::new(1.0, 2.0, 3.0);
        let b = Vec3::new(5.0, 6.0, 7.0);
        assert_eq_delta!(a.dot(b), 38.0);
    }

    #[test]
    fn cross() {
        let a = Vec3::new(2.0, 3.0, 4.0);
        let b = Vec3::new(5.0, 6.0, 7.0);
        let r = a.cross(b);
        assert_eq_delta!(r.x, -3.0);
        assert_eq_delta!(r.y, 6.0);
        assert_eq_delta!(r.z, -3.0);
    }

    #[test]
    fn length() {
        let v = Vec3::new(3.0, 4.0, 0.0);
        assert_eq_delta!(v.length(), 5.0);
    }

    #[test]
    fn unit() {
        let v = Vec3::new(3.0, 4.0, 0.0);
        let u = v.unit();
        assert_eq_delta!(u.x, 0.6);
        assert_eq_delta!(u.y, 0.8);
        assert_eq_delta!(u.z, 0.0);
    }

    #[test]
    fn angle_between() {
        let a = Vec3::new(4.0, 0.0, 0.0);
        let b = Vec3::new(0.0, 13.0, 0.0);
        assert_eq_delta!(a.angle_between(b), 90.0);
    }

    #[test]
    fn xy() {
        let v = Vec3::new(1.0, 3.0, 2.0);
        assert_eq!(v.xy(), Vec2::new(1.0, 3.0));
    }

    #[test]
    fn direction() {
        assert_eq!(Vec3::forward(), Vec3::new(0.0, 0.0, 1.0));
        assert_eq!(Vec3::back(), Vec3::new(0.0, 0.0, -1.0));
        assert_eq!(Vec3::down(), Vec3::new(0.0, -1.0, 0.0));
        assert_eq!(Vec3::up(), Vec3::new(0.0, 1.0, 0.0));
        assert_eq!(Vec3::right(), Vec3::new(1.0, 0.0, 0.0));
        assert_eq!(Vec3::left(), Vec3::new(-1.0, 0.0, 0.0));
    }

    #[test]
    fn operator() {
        let v1 = Vec3::new(2.0, 3.0, 4.0);
        let v2 = Vec3::new(2.0, 8.0, 4.0);
        assert_eq!(-v1, Vec3::new(-2.0, -3.0, -4.0));
        assert_eq!(v1 + v2, Vec3::new(4.0, 11.0, 8.0));
        assert_eq!(v1 - v2, Vec3::new(0.0, -5.0, 0.0));
        assert_eq!(v1 * 4.0, Vec3::new(8.0, 12.0, 16.0));
        assert_eq!(v2 / 2.0, Vec3::new(1.0, 4.0, 2.0));
    }
}