sphere intersection

This commit is contained in:
gbrochar 2020-12-10 21:38:07 +01:00
parent 2d25498769
commit 00357f9490
5 changed files with 60 additions and 1 deletions

View File

@ -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"
mat4 = "0.2.1"
vec3 = "0.2.1"
arrayvec = "0.5.2"

7
src/lib.rs Normal file
View File

@ -0,0 +1,7 @@
mod object;
mod ray;
mod sphere;
pub use self::object::*;
pub use self::ray::*;
pub use self::sphere::*;

7
src/object.rs Normal file
View File

@ -0,0 +1,7 @@
use super::Ray;
use arrayvec::ArrayVec;
pub trait Object {
fn get_intersection(&self, ray: Ray) -> Option<f64>;
fn get_normal(&self) -> ArrayVec<[f64; 3]>;
}

6
src/ray.rs Normal file
View File

@ -0,0 +1,6 @@
use arrayvec::ArrayVec;
pub struct Ray {
pub origin: ArrayVec<[f64; 3]>,
pub direction: ArrayVec<[f64; 3]>,
}

37
src/sphere.rs Normal file
View File

@ -0,0 +1,37 @@
use super::Object;
use super::Ray;
use arrayvec::ArrayVec;
struct Sphere {}
fn return_min(root1: f64, root2: f64) -> Option<f64> {
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<f64> {
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()
}
}