pixel_canvas/
vector.rs

1//! Types and operations for vectors.
2
3use std::ops::{Add, Div, Mul, Sub};
4
5/// A 3-dimensional vector.
6#[derive(Clone, Copy, Debug)]
7#[allow(missing_docs)]
8pub struct Vec3 {
9    pub x: f32,
10    pub y: f32,
11    pub z: f32,
12}
13
14impl Vec3 {
15    /// Construct a vector out of its components.
16    pub fn xyz(x: f32, y: f32, z: f32) -> Self {
17        Vec3 { x, y, z }
18    }
19
20    /// Normalizes the vector (scales its length to 1).
21    pub fn normal(self) -> Self {
22        self / self.len()
23    }
24
25    /// Computes the dot product between two vectors.
26    pub fn dot(self, rhs: Vec3) -> f32 {
27        self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
28    }
29
30    /// Computes the cross product between two vectors.
31    pub fn cross(self, rhs: Vec3) -> Vec3 {
32        Vec3 {
33            x: self.y * rhs.z - self.z * rhs.y,
34            y: self.z * rhs.x - self.x * rhs.z,
35            z: self.x * rhs.y - self.y * rhs.x,
36        }
37    }
38
39    /// The length of a vector.
40    pub fn len(&self) -> f32 {
41        self.len2().sqrt()
42    }
43
44    /// The squared length of a vector.
45    pub fn len2(&self) -> f32 {
46        self.x * self.x + self.y * self.y + self.z * self.z
47    }
48}
49
50impl Add<Vec3> for Vec3 {
51    type Output = Vec3;
52    fn add(self, rhs: Vec3) -> Self {
53        Vec3 {
54            x: self.x + rhs.x,
55            y: self.y + rhs.y,
56            z: self.z + rhs.z,
57        }
58    }
59}
60
61impl Sub<Vec3> for Vec3 {
62    type Output = Vec3;
63    fn sub(self, rhs: Vec3) -> Self {
64        Vec3 {
65            x: self.x - rhs.x,
66            y: self.y - rhs.y,
67            z: self.z - rhs.z,
68        }
69    }
70}
71
72impl Mul<f32> for Vec3 {
73    type Output = Vec3;
74    fn mul(self, rhs: f32) -> Self {
75        Vec3 {
76            x: self.x * rhs,
77            y: self.y * rhs,
78            z: self.z * rhs,
79        }
80    }
81}
82
83impl Div<f32> for Vec3 {
84    type Output = Vec3;
85    fn div(self, rhs: f32) -> Self {
86        Vec3 {
87            x: self.x / rhs,
88            y: self.y / rhs,
89            z: self.z / rhs,
90        }
91    }
92}