Add ray and sphere structs and impl
This commit is contained in:
parent
49eb7ab094
commit
9a00830460
52
src/main.rs
52
src/main.rs
|
@ -1,5 +1,6 @@
|
|||
use std::ops::{Add, Div, Mul, Sub};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Vec3 {
|
||||
x: f64,
|
||||
y: f64,
|
||||
|
@ -61,5 +62,54 @@ impl Div for Vec3 {
|
|||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Aliased for use in arguments, no functional difference
|
||||
type Point = Vec3;
|
||||
type Color = Vec3;
|
||||
|
||||
struct Ray {
|
||||
origin: Point,
|
||||
direction: Vec3,
|
||||
}
|
||||
|
||||
struct Sphere {
|
||||
center: Vec3,
|
||||
radius: f64,
|
||||
color: Color,
|
||||
}
|
||||
|
||||
impl Sphere {
|
||||
fn new(center: Vec3, radius: f64, color: Color) -> Self {
|
||||
Self { center, radius, color }
|
||||
}
|
||||
|
||||
// Ray/sphere intersection
|
||||
// See: https://viclw17.github.io/2018/07/16/raytracing-ray-sphere-intersection/
|
||||
fn intersect(&self, ray: &Ray) -> Option<f64> {
|
||||
let epsilon = 1e-4;
|
||||
let oc = ray.origin - self.center;
|
||||
let a = ray.direction.dot(&ray.direction);
|
||||
let b = 2. * oc.dot(&ray.direction);
|
||||
let c = oc.dot(&oc) - self.radius * self.radius;
|
||||
let discrimiant = b * b - 4. * a * c;
|
||||
|
||||
// The ray missed the sphere
|
||||
if discrimiant < 0. {
|
||||
None
|
||||
} else {
|
||||
let mut numerator = -b - discrimiant.sqrt();
|
||||
if numerator > epsilon {
|
||||
return Some(numerator / (2. * a));
|
||||
}
|
||||
|
||||
numerator = -b + discrimiant.sqrt();
|
||||
if numerator > epsilon {
|
||||
Some(numerator / (2. * a))
|
||||
} else {
|
||||
// The intersection happened behind the ray's origin
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
|
Loading…
Reference in New Issue