From 00357f94900f05f304f83b96b168d433e3fb3a69 Mon Sep 17 00:00:00 2001 From: gbrochar Date: Thu, 10 Dec 2020 21:38:07 +0100 Subject: [PATCH] sphere intersection --- Cargo.toml | 4 +++- src/lib.rs | 7 +++++++ src/object.rs | 7 +++++++ src/ray.rs | 6 ++++++ src/sphere.rs | 37 +++++++++++++++++++++++++++++++++++++ 5 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 src/lib.rs create mode 100644 src/object.rs create mode 100644 src/ray.rs create mode 100644 src/sphere.rs diff --git a/Cargo.toml b/Cargo.toml index ae2bd15..a9ebd40 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,4 +7,6 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -mat4 = "0.2.1" \ No newline at end of file +mat4 = "0.2.1" +vec3 = "0.2.1" +arrayvec = "0.5.2" \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..4a3e8c1 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,7 @@ +mod object; +mod ray; +mod sphere; + +pub use self::object::*; +pub use self::ray::*; +pub use self::sphere::*; diff --git a/src/object.rs b/src/object.rs new file mode 100644 index 0000000..5dcd436 --- /dev/null +++ b/src/object.rs @@ -0,0 +1,7 @@ +use super::Ray; +use arrayvec::ArrayVec; + +pub trait Object { + fn get_intersection(&self, ray: Ray) -> Option; + fn get_normal(&self) -> ArrayVec<[f64; 3]>; +} diff --git a/src/ray.rs b/src/ray.rs new file mode 100644 index 0000000..3283fa9 --- /dev/null +++ b/src/ray.rs @@ -0,0 +1,6 @@ +use arrayvec::ArrayVec; + +pub struct Ray { + pub origin: ArrayVec<[f64; 3]>, + pub direction: ArrayVec<[f64; 3]>, +} diff --git a/src/sphere.rs b/src/sphere.rs new file mode 100644 index 0000000..bb04767 --- /dev/null +++ b/src/sphere.rs @@ -0,0 +1,37 @@ +use super::Object; +use super::Ray; +use arrayvec::ArrayVec; + +struct Sphere {} + +fn return_min(root1: f64, root2: f64) -> Option { + if root1 < root2 && root1 > 0. { + Some(root1) + } else if root2 < root1 && root2 > 0. { + Some(root2) + } else { + None + } +} + +impl Object for Sphere { + fn get_intersection(&self, ray: Ray) -> Option { + let a = ray.direction[0].powi(2) + ray.direction[1].powi(2) + ray.direction[2].powi(2); + let b = (2. * ray.origin[0] * ray.direction[0]) + + (2. * ray.origin[1] * ray.direction[1]) + + (2. * ray.origin[2] * ray.direction[2]); + let c = ray.origin[0].powi(2) + ray.origin[1].powi(2) + ray.origin[2].powi(2) - 1.; + let delta = b * b - 4. * a * c; + + if delta > 0. { + let root1 = ((-1. * b - delta.sqrt()) / (a + a)) - 0.00001; + let root2 = ((-1. * b + delta.sqrt()) / (a + a)) - 0.00001; + return_min(root1, root2) + } else { + None + } + } + fn get_normal(&self) -> ArrayVec<[f64; 3]> { + ArrayVec::<[f64; 3]>::new() + } +}