Skip to content

Commit

Permalink
Add a Vector implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
jstasiak committed Jul 7, 2019
1 parent 33ea5d6 commit 89568f0
Show file tree
Hide file tree
Showing 2 changed files with 140 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use std::ops::{Add, Div, Mul, Sub};

#[derive(Copy, Clone)]
pub struct Vector {
pub x: f32,
pub y: f32,
pub z: f32,
}

impl Vector {
pub fn almost_equal(&self, other: &Vector) -> bool {
self.almost_equal_with_epsilon(other, 0.00000001)
}

pub fn almost_equal_with_epsilon(&self, other: &Vector, epsilon: f32) -> bool {
(self.x - other.x).abs() < epsilon
&& (self.y - other.y).abs() < epsilon
&& (self.z - other.z).abs() < epsilon
}
}

impl Add for Vector {
type Output = Vector;

fn add(self, other: Vector) -> Vector {
Vector {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}

impl Sub for Vector {
type Output = Vector;

fn sub(self, other: Vector) -> Vector {
self + -1.0 * other
}
}

impl Mul<f32> for Vector {
type Output = Vector;

fn mul(self, other: f32) -> Vector {
Vector {
x: self.x * other,
y: self.y * other,
z: self.z * other,
}
}
}

impl Mul<Vector> for f32 {
type Output = Vector;

fn mul(self, other: Vector) -> Vector {
other * self
}
}

impl Div<f32> for Vector {
type Output = Vector;

fn div(self, other: f32) -> Vector {
Vector {
x: self.x / other,
y: self.y / other,
z: self.z / other,
}
}
}
68 changes: 68 additions & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,72 @@
use raytracer::Vector;

#[test]
fn test_add() {
assert_eq!(3, 3);
}

#[test]
fn test_vector_addition() {
assert!((Vector {
x: 1.0,
y: 1.0,
z: 1.0
} + Vector {
x: 1.0,
y: 2.0,
z: 3.0
})
.almost_equal(&Vector {
x: 2.0,
y: 3.0,
z: 4.0
}));
}

#[test]
fn test_vector_subtraction() {
assert!((Vector {
x: 5.0,
y: 5.0,
z: 5.0
} - Vector {
x: 1.0,
y: 2.0,
z: 3.0
})
.almost_equal(&Vector {
x: 4.0,
y: 3.0,
z: 2.0
}));
}

#[test]
fn test_vector_scalar_multiplication() {
let initial_vector = Vector {
x: 1.0,
y: 2.0,
z: 3.0,
};
let expected_vector = Vector {
x: 2.0,
y: 4.0,
z: 6.0,
};
assert!((initial_vector * 2.0).almost_equal(&expected_vector));
assert!((2.0 * initial_vector).almost_equal(&expected_vector));
}

#[test]
fn test_vector_scalar_division() {
assert!((Vector {
x: 1.0,
y: 2.0,
z: 3.0
} / 2.0)
.almost_equal(&Vector {
x: 0.5,
y: 1.0,
z: 1.5
}));
}

0 comments on commit 89568f0

Please sign in to comment.