1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use super::scene_object::SceneObject;
use crate::{color::Color, vec3::Vec3};
const MAX_STEPS: u32 = 200;
const HIT_THRESHOLD: f64 = 1E-4;
#[derive(Debug)]
pub struct RayResult {
pub len: f64,
pub hit_point: Vec3,
}
pub fn cast_ray<C: Color, O: SceneObject<C>>(
object: &O,
point: Vec3,
dir: Vec3,
backplanes: Vec3,
t: f64,
) -> Option<RayResult> {
let dir = dir.normalized();
let mut current_point = point.clone();
let mut iterations = 0u32;
let mut ray_len = 0.0;
loop {
let radius = object.distance_to(current_point, t);
ray_len += radius;
iterations += 1;
current_point = point + ray_len * dir;
if radius < HIT_THRESHOLD {
return Some(RayResult {
len: ray_len,
hit_point: current_point,
});
}
if iterations > MAX_STEPS {
return None;
}
if current_point.x.abs() > backplanes.x
|| current_point.y.abs() > backplanes.y
|| current_point.z.abs() > backplanes.z
{
return None;
}
}
}