From 01f3e05235d570b22cfd5ec970e177ab7d416746 Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Sun, 9 Jun 2024 12:24:41 -0400 Subject: [PATCH] Create the basic Tuple, Point, and Vector types --- Cargo.lock | 4 +++ Cargo.toml | 2 +- ray-tracer/Cargo.toml | 8 ++++++ ray-tracer/src/lib.rs | 2 ++ ray-tracer/src/types.rs | 62 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 ray-tracer/Cargo.toml create mode 100644 ray-tracer/src/lib.rs create mode 100644 ray-tracer/src/types.rs diff --git a/Cargo.lock b/Cargo.lock index 4118f22..05494a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3331,6 +3331,10 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "ray-tracer" +version = "0.1.0" + [[package]] name = "rayon" version = "1.8.0" diff --git a/Cargo.toml b/Cargo.toml index 538b62b..3412c85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,5 +27,5 @@ members = [ "sgf", "timezone-testing", "tree", - "visions/server", + "visions/server", "ray-tracer", ] diff --git a/ray-tracer/Cargo.toml b/ray-tracer/Cargo.toml new file mode 100644 index 0000000..a367ea5 --- /dev/null +++ b/ray-tracer/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "ray-tracer" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/ray-tracer/src/lib.rs b/ray-tracer/src/lib.rs new file mode 100644 index 0000000..fc1a2f5 --- /dev/null +++ b/ray-tracer/src/lib.rs @@ -0,0 +1,2 @@ +mod types; + diff --git a/ray-tracer/src/types.rs b/ray-tracer/src/types.rs new file mode 100644 index 0000000..b253756 --- /dev/null +++ b/ray-tracer/src/types.rs @@ -0,0 +1,62 @@ + +const EPSILON: f64 = 0.00001; + +fn eq_f64(l: f64, r: f64) -> bool { + (l-r).abs() < EPSILON +} + +struct Tuple { + x: f64, + y: f64, + z: f64, + w: f64, // Used for very low-level math. w = 1.0 indicates a point, w = 0.0 indicates a vector. + // Theoretically the type system should make this redundant, so operations on points + // and vectors can always assert the correct value. +} + +impl PartialEq for Tuple { + fn eq(&self, r: &Tuple) -> bool { + eq_f64(self.x, r.x) && eq_f64(self.y, r.y) && eq_f64(self.z, r.z) && eq_f64(self.w, r.w) + } +} + +struct Point(Tuple); + +impl Point { + fn new(x: f64, y: f64, z: f64) -> Self { + Self(Tuple{ x, y, z, w: 1.0 }) + } +} + +impl Default for Point { + fn default() -> Self { + Self::new(0., 0., 0.) + } +} + +struct Vector(Tuple); + +impl Vector { + fn new(x: f64, y: f64, z: f64) -> Self { + Self(Tuple{ x, y, z, w: 0.0 }) + } +} + +impl Default for Vector { + fn default() -> Self { + Self::new(0., 0., 0.) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn eq_f64_compares_values() { + assert!(eq_f64(1.0, 1.0)); + assert!(eq_f64(0.9994, 0.9994)); + assert!(eq_f64(0.9999994, 0.9999995)); + assert!(!eq_f64(0.9995, 0.9994)); + } +}