isosurface/
math.rs

1// Copyright 2018 Tristam MacDonald
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std;
16
17/// A 3 dimensional vector
18///
19/// Ideally we'd reuse an exiting geometry library, but in the interest both of minimising
20/// dependencies, and of compatibility with multiple geometry libraries, we'll define our own.
21#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
22pub struct Vec3 {
23    pub x: f32,
24    pub y: f32,
25    pub z: f32,
26}
27
28impl Vec3 {
29    /// Create a vector
30    pub fn new(x: f32, y: f32, z: f32) -> Self {
31        Self { x, y, z }
32    }
33
34    /// Create a vector with all coordinates set to zero
35    pub fn zero() -> Self {
36        Self {
37            x: 0.0,
38            y: 0.0,
39            z: 0.0,
40        }
41    }
42
43    /// Create a vector with all coordinates set to one
44    pub fn one() -> Self {
45        Self {
46            x: 1.0,
47            y: 1.0,
48            z: 1.0,
49        }
50    }
51}
52
53impl std::ops::Add for Vec3 {
54    type Output = Vec3;
55
56    fn add(self, other: Vec3) -> Vec3 {
57        Vec3::new(self.x + other.x, self.y + other.y, self.z + other.z)
58    }
59}
60
61impl std::ops::Sub for Vec3 {
62    type Output = Vec3;
63
64    fn sub(self, other: Vec3) -> Vec3 {
65        Vec3::new(self.x - other.x, self.y - other.y, self.z - other.z)
66    }
67}
68
69impl std::ops::Mul for Vec3 {
70    type Output = Vec3;
71
72    fn mul(self, other: Vec3) -> Vec3 {
73        Vec3::new(self.x * other.x, self.y * other.y, self.z * other.z)
74    }
75}
76
77impl std::ops::Mul<f32> for Vec3 {
78    type Output = Vec3;
79
80    fn mul(self, other: f32) -> Vec3 {
81        Vec3::new(self.x * other, self.y * other, self.z * other)
82    }
83}
84
85impl std::ops::Div for Vec3 {
86    type Output = Vec3;
87
88    fn div(self, other: Vec3) -> Vec3 {
89        Vec3::new(self.x / other.x, self.y / other.y, self.z / other.z)
90    }
91}