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
use rust_gpu_bridge::prelude::Vec3;

use crate::prelude::{Distance, SignedDistanceField};

use super::{Raymarch, RaymarchOutput};

#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct SphereTraceNaive;

impl Raymarch for SphereTraceNaive {
    type Output = RaymarchOutput;

    fn raymarch<Sdf, const MAX_STEPS: u32>(
        &self,
        sdf: &Sdf,
        start: f32,
        end: f32,
        eye: Vec3,
        dir: Vec3,
        epsilon: f32,
    ) -> Self::Output
    where
        Sdf: SignedDistanceField<Vec3, Distance>,
    {
        let mut out = RaymarchOutput::default();
        let mut t = start;

        for _ in 0..MAX_STEPS {
            let p = eye + dir * t;
            let dist = *sdf.evaluate(p);

            out.steps += 1;

            if dist < 0.0 {
                out.hit = true;
                out.dist = t;
                break;
            }

            t += epsilon.max(dist.abs());

            if t > end {
                out.dist = end;
                break;
            }
        }

        out
    }
}