Skip to main content

euv_core/game/engine3d/lumen/
impl.rs

1use super::*;
2
3/// Default 8,192-slot two-cascade `LumenRadianceCache`.
4impl Default for LumenRadianceCache {
5    /// Creates an empty pre-allocated `LumenRadianceCache` with `LUMEN_RADIANCE_CACHE_SLOTS` slots.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Ready world-space radiance cache.
10    fn default() -> Self {
11        Self::with_capacity(LUMEN_RADIANCE_CACHE_SLOTS)
12    }
13}
14
15/// World-space quantization, O(1) multi-bounce irradiance lookup, temporal EMA accumulation, and motion-vector reprojection for `LumenRadianceCache`.
16impl LumenRadianceCache {
17    /// Constructs a `LumenRadianceCache` rounded up to a power-of-two capacity (`>= 64`).
18    ///
19    /// # Arguments
20    ///
21    /// - `usize` - Requested minimum slot capacity.
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Zero-allocation-after-init radiance cache.
26    #[must_use]
27    pub fn with_capacity(capacity: usize) -> Self {
28        let slots: usize = capacity.max(64).next_power_of_two();
29        Self {
30            slot_mask: slots - 1,
31            current_frame: 0,
32            cached_sun_dir: Vec3::new(0.0, 1.0, 0.0),
33            active_cells: 0,
34            total_updates: 0,
35            cells: vec![LumenCacheCell::default(); slots],
36        }
37    }
38
39    /// Clears every spatial hash cell in-place without freeing backing memory (e.g. on sun change or world reset).
40    pub fn invalidate(&mut self) {
41        let Self { cells, .. } = self;
42        for cell in cells.iter_mut() {
43            cell.set_key(0);
44            cell.set_sample_weight(0.0);
45        }
46        self.set_active_cells(0);
47    }
48
49    /// Begins a new frame, invalidating cached indirect radiance automatically if the directional sun shifted meaningfully.
50    ///
51    /// # Arguments
52    ///
53    /// - `Vec3` - Current active unit directional sun vector.
54    pub fn begin_frame(&mut self, sun_direction: Vec3) {
55        let next_frame: u32 = self.get_current_frame().wrapping_add(1);
56        self.set_current_frame(next_frame);
57        let prev_sun: Vec3 = self.get_cached_sun_dir();
58        if prev_sun.dot(sun_direction) < 0.9995 {
59            self.invalidate();
60            self.set_cached_sun_dir(sun_direction);
61        }
62    }
63
64    /// Quantizes a world position, surface normal, and camera distance into a deterministic non-zero 64-bit spatial key and primary bucket index.
65    ///
66    /// # Arguments
67    ///
68    /// - `Vec3` - World-space surface position.
69    /// - `Vec3` - Unit outward surface normal.
70    /// - `Vec3` - Active camera world position selecting near vs far cascade.
71    ///
72    /// # Returns
73    ///
74    /// - `(u64, usize)` - `(non_zero_spatial_key, base_bucket_index)`.
75    #[cfg_attr(not(target_arch = "wasm32"), inline)]
76    #[must_use]
77    pub fn quantize_key(&self, world_pos: Vec3, normal: Vec3, camera_pos: Vec3) -> (u64, usize) {
78        let dist_sq: f32 = world_pos.sub(camera_pos).length_sq();
79        let near_sq: f32 = LUMEN_NEAR_CASCADE_RADIUS_M * LUMEN_NEAR_CASCADE_RADIUS_M;
80        let (cascade_bit, inv_voxel): (u64, f32) = if dist_sq <= near_sq {
81            (0_u64, 1.0 / LUMEN_NEAR_VOXEL_METERS)
82        } else {
83            (1_u64, 1.0 / LUMEN_FAR_VOXEL_METERS)
84        };
85        let qx: i64 = (world_pos.get_x() * inv_voxel).floor() as i64;
86        let qy: i64 = (world_pos.get_y() * inv_voxel).floor() as i64;
87        let qz: i64 = (world_pos.get_z() * inv_voxel).floor() as i64;
88        let ax: f32 = normal.get_x().abs();
89        let ay: f32 = normal.get_y().abs();
90        let az: f32 = normal.get_z().abs();
91        let normal_bucket: u64 = if ax >= ay && ax >= az {
92            if normal.get_x() >= 0.0 { 0 } else { 1 }
93        } else if ay >= az {
94            if normal.get_y() >= 0.0 { 2 } else { 3 }
95        } else if normal.get_z() >= 0.0 {
96            4
97        } else {
98            5
99        };
100        let px: u64 = (qx as u64) & 0x3_FFFF;
101        let py: u64 = (qy as u64) & 0x3_FFFF;
102        let pz: u64 = (qz as u64) & 0x3_FFFF;
103        let raw_key: u64 =
104            1_u64 | (cascade_bit << 1) | (normal_bucket << 2) | (px << 5) | (py << 23) | (pz << 41);
105        let mut mixed: u64 = raw_key.wrapping_mul(LUMEN_HASH_MIX_A);
106        mixed ^= mixed >> 30;
107        mixed = mixed.wrapping_mul(LUMEN_HASH_MIX_B);
108        mixed ^= mixed >> 27;
109        let bucket: usize = (mixed as usize) & self.get_slot_mask();
110        (raw_key, bucket)
111    }
112
113    /// Queries the world-space radiance cache in O(1) for temporally accumulated `(irradiance, ao, sun_visibility)`.
114    ///
115    /// # Arguments
116    ///
117    /// - `Vec3` - World-space surface position.
118    /// - `Vec3` - Unit outward surface normal.
119    /// - `Vec3` - Active camera world position.
120    ///
121    /// # Returns
122    ///
123    /// - `Option<(Vec3, f32, f32)>` - Cached `(indirect_irradiance, ao, sun_visibility)` when present and fresh.
124    #[cfg_attr(not(target_arch = "wasm32"), inline)]
125    #[must_use]
126    pub fn lookup(
127        &self,
128        world_pos: Vec3,
129        normal: Vec3,
130        camera_pos: Vec3,
131    ) -> Option<(Vec3, f32, f32)> {
132        let (key, base_bucket): (u64, usize) = self.quantize_key(world_pos, normal, camera_pos);
133        let mask: usize = self.get_slot_mask();
134        let Self { cells, .. } = self;
135        for probe_offset in 0..LUMEN_CACHE_PROBE_WINDOW {
136            let slot: usize = (base_bucket + probe_offset) & mask;
137            let cell: LumenCacheCell = cells[slot];
138            if cell.get_key() == key && cell.get_sample_weight() > 0.0 {
139                return Some((
140                    Vec3::new(
141                        cell.get_irradiance_r(),
142                        cell.get_irradiance_g(),
143                        cell.get_irradiance_b(),
144                    ),
145                    cell.get_ambient_occlusion(),
146                    cell.get_sun_visibility(),
147                ));
148            }
149            if cell.get_key() == 0 {
150                break;
151            }
152        }
153        None
154    }
155
156    /// Accumulates a freshly traced surface lighting sample into the world-space radiance cache via damped temporal EMA.
157    ///
158    /// # Arguments
159    ///
160    /// - `Vec3` - World-space surface position.
161    /// - `Vec3` - Unit outward surface normal.
162    /// - `Vec3` - Active camera world position.
163    /// - `Vec3` - Measured linear HDR indirect irradiance RGB.
164    /// - `f32` - Measured ambient occlusion in `[0.35, 1.0]`.
165    /// - `f32` - Measured directional sun visibility in `[0.0, 1.0]`.
166    #[cfg_attr(not(target_arch = "wasm32"), inline)]
167    pub fn accumulate_sample(
168        &mut self,
169        world_pos: Vec3,
170        normal: Vec3,
171        camera_pos: Vec3,
172        irradiance: Vec3,
173        ambient_occlusion: f32,
174        sun_visibility: f32,
175    ) {
176        let (key, base_bucket): (u64, usize) = self.quantize_key(world_pos, normal, camera_pos);
177        let mask: usize = self.get_slot_mask();
178        let frame_now: u32 = self.get_current_frame();
179        let mut target_slot: usize = base_bucket;
180        let mut matched: bool = false;
181        let mut inserted_new: bool = false;
182        {
183            let Self { cells, .. } = self;
184            let mut oldest_slot: usize = base_bucket;
185            let mut oldest_age: u32 = 0;
186            for probe_offset in 0..LUMEN_CACHE_PROBE_WINDOW {
187                let slot: usize = (base_bucket + probe_offset) & mask;
188                let cell: LumenCacheCell = cells[slot];
189                if cell.get_key() == key {
190                    target_slot = slot;
191                    matched = true;
192                    break;
193                }
194                if cell.get_key() == 0 {
195                    target_slot = slot;
196                    inserted_new = true;
197                    break;
198                }
199                let age: u32 = frame_now.wrapping_sub(cell.get_last_frame());
200                if age >= oldest_age {
201                    oldest_age = age;
202                    oldest_slot = slot;
203                }
204            }
205            if !matched && !inserted_new {
206                if oldest_age >= LUMEN_STALE_FRAME_AGE
207                    || cells[oldest_slot].get_sample_weight() <= 1.0
208                {
209                    target_slot = oldest_slot;
210                } else {
211                    return;
212                }
213            }
214            let cell: &mut LumenCacheCell = &mut cells[target_slot];
215            if matched {
216                let next_weight: f32 =
217                    (cell.get_sample_weight() + 1.0).min(LUMEN_MAX_TEMPORAL_WEIGHT);
218                let blend: f32 = 1.0 / next_weight;
219                let keep: f32 = 1.0 - blend;
220                cell.set_irradiance_r(cell.get_irradiance_r() * keep + irradiance.get_x() * blend);
221                cell.set_irradiance_g(cell.get_irradiance_g() * keep + irradiance.get_y() * blend);
222                cell.set_irradiance_b(cell.get_irradiance_b() * keep + irradiance.get_z() * blend);
223                cell.set_ambient_occlusion(
224                    cell.get_ambient_occlusion() * keep + ambient_occlusion * blend,
225                );
226                cell.set_sun_visibility(cell.get_sun_visibility() * keep + sun_visibility * blend);
227                cell.set_sample_weight(next_weight);
228                cell.set_last_frame(frame_now);
229            } else {
230                cell.set_key(key);
231                cell.set_irradiance_r(irradiance.get_x());
232                cell.set_irradiance_g(irradiance.get_y());
233                cell.set_irradiance_b(irradiance.get_z());
234                cell.set_ambient_occlusion(ambient_occlusion);
235                cell.set_sun_visibility(sun_visibility);
236                cell.set_sample_weight(1.0);
237                cell.set_last_frame(frame_now);
238            }
239        }
240        if inserted_new {
241            self.set_active_cells(self.get_active_cells().saturating_add(1));
242        }
243        self.set_total_updates(self.get_total_updates().saturating_add(1));
244    }
245
246    /// Analytically reprojects a world-space probe point into the previous frame's coarse RT probe grid using `prev_view_proj`.
247    ///
248    /// # Arguments
249    ///
250    /// - `Vec3` - Current-frame world-space surface position.
251    /// - `&Mat4` - Previous frame's view-projection matrix.
252    /// - `(usize, usize)` - Previous frame internal framebuffer `(width, height)` in pixels.
253    /// - `(usize, usize, usize)` - `(rt_step, prev_grid_width, prev_grid_height)`.
254    ///
255    /// # Returns
256    ///
257    /// - `Option<LumenReprojectedProbe>` - Valid previous-frame probe index and depth when inside previous viewport bounds.
258    #[cfg_attr(not(target_arch = "wasm32"), inline)]
259    #[must_use]
260    pub fn reproject_world_to_prev_probe(
261        world_pos: Vec3,
262        prev_view_proj: &Mat4,
263        prev_viewport: (usize, usize),
264        grid_layout: (usize, usize, usize),
265    ) -> Option<LumenReprojectedProbe> {
266        let (prev_w, prev_h): (usize, usize) = prev_viewport;
267        let (rt_step, prev_gw, prev_gh): (usize, usize, usize) = grid_layout;
268        if rt_step == 0 || prev_gw == 0 || prev_gh == 0 || prev_w == 0 || prev_h == 0 {
269            return None;
270        }
271        let prev_clip: [f32; 4] = prev_view_proj.mul_point4(world_pos);
272        if prev_clip[3] <= 0.15 {
273            return None;
274        }
275        let inv_w: f32 = 1.0 / prev_clip[3];
276        let ndc_x: f32 = prev_clip[0] * inv_w;
277        let ndc_y: f32 = prev_clip[1] * inv_w;
278        if !(-1.0..=1.0).contains(&ndc_x) || !(-1.0..=1.0).contains(&ndc_y) {
279            return None;
280        }
281        let prev_px: f32 = (ndc_x * 0.5 + 0.5) * (prev_w as f32);
282        let prev_py: f32 = (0.5 - ndc_y * 0.5) * (prev_h as f32);
283        let inv_step: f32 = 1.0 / (rt_step as f32);
284        let prev_gx_f: f32 = (prev_px * inv_step - 0.5).round();
285        let prev_gy_f: f32 = (prev_py * inv_step - 0.5).round();
286        if prev_gx_f < 0.0 || prev_gy_f < 0.0 {
287            return None;
288        }
289        let prev_gx: usize = prev_gx_f as usize;
290        let prev_gy: usize = prev_gy_f as usize;
291        if prev_gx >= prev_gw || prev_gy >= prev_gh {
292            return None;
293        }
294        Some(LumenReprojectedProbe::new(
295            prev_gy * prev_gw + prev_gx,
296            prev_gx,
297            prev_gy,
298            prev_clip[3],
299        ))
300    }
301
302    /// Returns a snapshot of current radiance cache telemetry.
303    ///
304    /// # Returns
305    ///
306    /// - `LumenCacheStats` - Active cell count and cumulative update statistics.
307    #[must_use]
308    pub fn stats(&self) -> LumenCacheStats {
309        LumenCacheStats {
310            active_cells: self.get_active_cells(),
311            frame_hits: 0,
312            frame_misses: 0,
313            total_updates: self.get_total_updates(),
314        }
315    }
316}