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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use crate::vol::ReadVol;
use vek::*;

pub trait RayForEach<V> = FnMut(&V, Vec3<i32>);

pub struct Ray<'a, V: ReadVol, F: FnMut(&V::Vox) -> bool, G: RayForEach<V::Vox>> {
    vol: &'a V,
    from: Vec3<f32>,
    to: Vec3<f32>,
    until: F,
    is_while: bool,
    for_each: Option<G>,
    max_iter: usize,
    ignore_error: bool,
}

impl<'a, V, F, G> Ray<'a, V, F, G>
where
    V: ReadVol,
    F: FnMut(&V::Vox) -> bool,
    G: RayForEach<V::Vox>,
{
    pub fn new(vol: &'a V, from: Vec3<f32>, to: Vec3<f32>, until: F) -> Self {
        Self {
            vol,
            from,
            to,
            until,
            is_while: false,
            for_each: None,
            max_iter: 100,
            ignore_error: false,
        }
    }

    pub fn until<H: FnMut(&V::Vox) -> bool>(self, f: H) -> Ray<'a, V, H, G> {
        Ray {
            vol: self.vol,
            from: self.from,
            to: self.to,
            until: f,
            is_while: false,
            for_each: self.for_each,
            max_iter: self.max_iter,
            ignore_error: self.ignore_error,
        }
    }

    pub fn while_<H: FnMut(&V::Vox) -> bool>(self, f: H) -> Ray<'a, V, H, G> {
        Ray {
            vol: self.vol,
            from: self.from,
            to: self.to,
            until: f,
            is_while: true,
            for_each: self.for_each,
            max_iter: self.max_iter,
            ignore_error: self.ignore_error,
        }
    }

    pub fn for_each<H: RayForEach<V::Vox>>(self, f: H) -> Ray<'a, V, F, H> {
        Ray {
            for_each: Some(f),
            vol: self.vol,
            from: self.from,
            to: self.to,
            is_while: self.is_while,
            until: self.until,
            max_iter: self.max_iter,
            ignore_error: self.ignore_error,
        }
    }

    #[must_use]
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }

    #[must_use]
    pub fn ignore_error(mut self) -> Self {
        self.ignore_error = true;
        self
    }

    pub fn cast(mut self) -> (f32, Result<Option<&'a V::Vox>, V::Error>) {
        // TODO: Fully test this!

        const PLANCK: f32 = 0.001;

        let mut dist = 0.0;
        let dir = (self.to - self.from).normalized();
        let max = (self.to - self.from).magnitude();

        for _ in 0..self.max_iter {
            // Allow one iteration above max.
            if dist > max {
                break;
            }
            let pos = self.from + dir * dist;
            let ipos = pos.map(|e| e.floor() as i32);

            let vox = self.vol.get(ipos);

            if self.is_while {
                let vox = match vox.map(|vox| (vox, (self.until)(vox))) {
                    Ok((vox, true)) => return (dist, Ok(Some(vox))),
                    Ok((vox, _)) => Some(vox),
                    Err(err) if !self.ignore_error => return (dist, Err(err)),
                    _ => None,
                };

                if let Some((vox, g)) = vox.zip(self.for_each.as_mut()) {
                    g(vox, ipos);
                }
            } else {
                // for_each
                if let Some((vox, g)) = vox.as_ref().ok().zip(self.for_each.as_mut()) {
                    g(vox, ipos);
                }

                match vox.map(|vox| (vox, (self.until)(vox))) {
                    Ok((vox, true)) => return (dist, Ok(Some(vox))),
                    Err(err) if !self.ignore_error => return (dist, Err(err)),
                    _ => {},
                }
            }

            let deltas =
                (dir.map(|e| if e < 0.0 { 0.0 } else { 1.0 }) - pos.map(|e| e.abs().fract())) / dir;

            dist += deltas.reduce(f32::min).max(PLANCK);
        }

        // The ray can go over the maximum magnitude in the last iteration
        dist = dist.min(max);

        (dist, Ok(None))
    }
}