euv-core 0.53.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Default 8,192-slot two-cascade `LumenRadianceCache`.
impl Default for LumenRadianceCache {
    /// Creates an empty pre-allocated `LumenRadianceCache` with `LUMEN_RADIANCE_CACHE_SLOTS` slots.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready world-space radiance cache.
    fn default() -> Self {
        Self::with_capacity(LUMEN_RADIANCE_CACHE_SLOTS)
    }
}

/// World-space quantization, O(1) multi-bounce irradiance lookup, temporal EMA accumulation, and motion-vector reprojection for `LumenRadianceCache`.
impl LumenRadianceCache {
    /// Constructs a `LumenRadianceCache` rounded up to a power-of-two capacity (`>= 64`).
    ///
    /// # Arguments
    ///
    /// - `usize` - Requested minimum slot capacity.
    ///
    /// # Returns
    ///
    /// - `Self` - Zero-allocation-after-init radiance cache.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        let slots: usize = capacity.max(64).next_power_of_two();
        Self {
            slot_mask: slots - 1,
            current_frame: 0,
            cached_sun_dir: Vec3::new(0.0, 1.0, 0.0),
            active_cells: 0,
            total_updates: 0,
            cells: vec![LumenCacheCell::default(); slots],
        }
    }

    /// Clears every spatial hash cell in-place without freeing backing memory (e.g. on sun change or world reset).
    pub fn invalidate(&mut self) {
        let Self { cells, .. } = self;
        for cell in cells.iter_mut() {
            cell.set_key(0);
            cell.set_sample_weight(0.0);
        }
        self.set_active_cells(0);
    }

    /// Begins a new frame, invalidating cached indirect radiance automatically if the directional sun shifted meaningfully.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Current active unit directional sun vector.
    pub fn begin_frame(&mut self, sun_direction: Vec3) {
        let next_frame: u32 = self.get_current_frame().wrapping_add(1);
        self.set_current_frame(next_frame);
        let prev_sun: Vec3 = self.get_cached_sun_dir();
        if prev_sun.dot(sun_direction) < 0.9995 {
            self.invalidate();
            self.set_cached_sun_dir(sun_direction);
        }
    }

    /// Quantizes a world position, surface normal, and camera distance into a deterministic non-zero 64-bit spatial key and primary bucket index.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `Vec3` - Active camera world position selecting near vs far cascade.
    ///
    /// # Returns
    ///
    /// - `(u64, usize)` - `(non_zero_spatial_key, base_bucket_index)`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn quantize_key(&self, world_pos: Vec3, normal: Vec3, camera_pos: Vec3) -> (u64, usize) {
        let dist_sq: f32 = world_pos.sub(camera_pos).length_sq();
        let near_sq: f32 = LUMEN_NEAR_CASCADE_RADIUS_M * LUMEN_NEAR_CASCADE_RADIUS_M;
        let (cascade_bit, inv_voxel): (u64, f32) = if dist_sq <= near_sq {
            (0_u64, 1.0 / LUMEN_NEAR_VOXEL_METERS)
        } else {
            (1_u64, 1.0 / LUMEN_FAR_VOXEL_METERS)
        };
        let qx: i64 = (world_pos.get_x() * inv_voxel).floor() as i64;
        let qy: i64 = (world_pos.get_y() * inv_voxel).floor() as i64;
        let qz: i64 = (world_pos.get_z() * inv_voxel).floor() as i64;
        let ax: f32 = normal.get_x().abs();
        let ay: f32 = normal.get_y().abs();
        let az: f32 = normal.get_z().abs();
        let normal_bucket: u64 = if ax >= ay && ax >= az {
            if normal.get_x() >= 0.0 { 0 } else { 1 }
        } else if ay >= az {
            if normal.get_y() >= 0.0 { 2 } else { 3 }
        } else if normal.get_z() >= 0.0 {
            4
        } else {
            5
        };
        let px: u64 = (qx as u64) & 0x3_FFFF;
        let py: u64 = (qy as u64) & 0x3_FFFF;
        let pz: u64 = (qz as u64) & 0x3_FFFF;
        let raw_key: u64 =
            1_u64 | (cascade_bit << 1) | (normal_bucket << 2) | (px << 5) | (py << 23) | (pz << 41);
        let mut mixed: u64 = raw_key.wrapping_mul(LUMEN_HASH_MIX_A);
        mixed ^= mixed >> 30;
        mixed = mixed.wrapping_mul(LUMEN_HASH_MIX_B);
        mixed ^= mixed >> 27;
        let bucket: usize = (mixed as usize) & self.get_slot_mask();
        (raw_key, bucket)
    }

    /// Queries the world-space radiance cache in O(1) for temporally accumulated `(irradiance, ao, sun_visibility)`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `Vec3` - Active camera world position.
    ///
    /// # Returns
    ///
    /// - `Option<(Vec3, f32, f32)>` - Cached `(indirect_irradiance, ao, sun_visibility)` when present and fresh.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn lookup(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        camera_pos: Vec3,
    ) -> Option<(Vec3, f32, f32)> {
        let (key, base_bucket): (u64, usize) = self.quantize_key(world_pos, normal, camera_pos);
        let mask: usize = self.get_slot_mask();
        let Self { cells, .. } = self;
        for probe_offset in 0..LUMEN_CACHE_PROBE_WINDOW {
            let slot: usize = (base_bucket + probe_offset) & mask;
            let cell: LumenCacheCell = cells[slot];
            if cell.get_key() == key && cell.get_sample_weight() > 0.0 {
                return Some((
                    Vec3::new(
                        cell.get_irradiance_r(),
                        cell.get_irradiance_g(),
                        cell.get_irradiance_b(),
                    ),
                    cell.get_ambient_occlusion(),
                    cell.get_sun_visibility(),
                ));
            }
            if cell.get_key() == 0 {
                break;
            }
        }
        None
    }

    /// Accumulates a freshly traced surface lighting sample into the world-space radiance cache via damped temporal EMA.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `Vec3` - Active camera world position.
    /// - `Vec3` - Measured linear HDR indirect irradiance RGB.
    /// - `f32` - Measured ambient occlusion in `[0.35, 1.0]`.
    /// - `f32` - Measured directional sun visibility in `[0.0, 1.0]`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    pub fn accumulate_sample(
        &mut self,
        world_pos: Vec3,
        normal: Vec3,
        camera_pos: Vec3,
        irradiance: Vec3,
        ambient_occlusion: f32,
        sun_visibility: f32,
    ) {
        let (key, base_bucket): (u64, usize) = self.quantize_key(world_pos, normal, camera_pos);
        let mask: usize = self.get_slot_mask();
        let frame_now: u32 = self.get_current_frame();
        let mut target_slot: usize = base_bucket;
        let mut matched: bool = false;
        let mut inserted_new: bool = false;
        {
            let Self { cells, .. } = self;
            let mut oldest_slot: usize = base_bucket;
            let mut oldest_age: u32 = 0;
            for probe_offset in 0..LUMEN_CACHE_PROBE_WINDOW {
                let slot: usize = (base_bucket + probe_offset) & mask;
                let cell: LumenCacheCell = cells[slot];
                if cell.get_key() == key {
                    target_slot = slot;
                    matched = true;
                    break;
                }
                if cell.get_key() == 0 {
                    target_slot = slot;
                    inserted_new = true;
                    break;
                }
                let age: u32 = frame_now.wrapping_sub(cell.get_last_frame());
                if age >= oldest_age {
                    oldest_age = age;
                    oldest_slot = slot;
                }
            }
            if !matched && !inserted_new {
                if oldest_age >= LUMEN_STALE_FRAME_AGE
                    || cells[oldest_slot].get_sample_weight() <= 1.0
                {
                    target_slot = oldest_slot;
                } else {
                    return;
                }
            }
            let cell: &mut LumenCacheCell = &mut cells[target_slot];
            if matched {
                let next_weight: f32 =
                    (cell.get_sample_weight() + 1.0).min(LUMEN_MAX_TEMPORAL_WEIGHT);
                let blend: f32 = 1.0 / next_weight;
                let keep: f32 = 1.0 - blend;
                cell.set_irradiance_r(cell.get_irradiance_r() * keep + irradiance.get_x() * blend);
                cell.set_irradiance_g(cell.get_irradiance_g() * keep + irradiance.get_y() * blend);
                cell.set_irradiance_b(cell.get_irradiance_b() * keep + irradiance.get_z() * blend);
                cell.set_ambient_occlusion(
                    cell.get_ambient_occlusion() * keep + ambient_occlusion * blend,
                );
                cell.set_sun_visibility(cell.get_sun_visibility() * keep + sun_visibility * blend);
                cell.set_sample_weight(next_weight);
                cell.set_last_frame(frame_now);
            } else {
                cell.set_key(key);
                cell.set_irradiance_r(irradiance.get_x());
                cell.set_irradiance_g(irradiance.get_y());
                cell.set_irradiance_b(irradiance.get_z());
                cell.set_ambient_occlusion(ambient_occlusion);
                cell.set_sun_visibility(sun_visibility);
                cell.set_sample_weight(1.0);
                cell.set_last_frame(frame_now);
            }
        }
        if inserted_new {
            self.set_active_cells(self.get_active_cells().saturating_add(1));
        }
        self.set_total_updates(self.get_total_updates().saturating_add(1));
    }

    /// Analytically reprojects a world-space probe point into the previous frame's coarse RT probe grid using `prev_view_proj`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Current-frame world-space surface position.
    /// - `&Mat4` - Previous frame's view-projection matrix.
    /// - `(usize, usize)` - Previous frame internal framebuffer `(width, height)` in pixels.
    /// - `(usize, usize, usize)` - `(rt_step, prev_grid_width, prev_grid_height)`.
    ///
    /// # Returns
    ///
    /// - `Option<LumenReprojectedProbe>` - Valid previous-frame probe index and depth when inside previous viewport bounds.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn reproject_world_to_prev_probe(
        world_pos: Vec3,
        prev_view_proj: &Mat4,
        prev_viewport: (usize, usize),
        grid_layout: (usize, usize, usize),
    ) -> Option<LumenReprojectedProbe> {
        let (prev_w, prev_h): (usize, usize) = prev_viewport;
        let (rt_step, prev_gw, prev_gh): (usize, usize, usize) = grid_layout;
        if rt_step == 0 || prev_gw == 0 || prev_gh == 0 || prev_w == 0 || prev_h == 0 {
            return None;
        }
        let prev_clip: [f32; 4] = prev_view_proj.mul_point4(world_pos);
        if prev_clip[3] <= 0.15 {
            return None;
        }
        let inv_w: f32 = 1.0 / prev_clip[3];
        let ndc_x: f32 = prev_clip[0] * inv_w;
        let ndc_y: f32 = prev_clip[1] * inv_w;
        if !(-1.0..=1.0).contains(&ndc_x) || !(-1.0..=1.0).contains(&ndc_y) {
            return None;
        }
        let prev_px: f32 = (ndc_x * 0.5 + 0.5) * (prev_w as f32);
        let prev_py: f32 = (0.5 - ndc_y * 0.5) * (prev_h as f32);
        let inv_step: f32 = 1.0 / (rt_step as f32);
        let prev_gx_f: f32 = (prev_px * inv_step - 0.5).round();
        let prev_gy_f: f32 = (prev_py * inv_step - 0.5).round();
        if prev_gx_f < 0.0 || prev_gy_f < 0.0 {
            return None;
        }
        let prev_gx: usize = prev_gx_f as usize;
        let prev_gy: usize = prev_gy_f as usize;
        if prev_gx >= prev_gw || prev_gy >= prev_gh {
            return None;
        }
        Some(LumenReprojectedProbe::new(
            prev_gy * prev_gw + prev_gx,
            prev_gx,
            prev_gy,
            prev_clip[3],
        ))
    }

    /// Returns a snapshot of current radiance cache telemetry.
    ///
    /// # Returns
    ///
    /// - `LumenCacheStats` - Active cell count and cumulative update statistics.
    #[must_use]
    pub fn stats(&self) -> LumenCacheStats {
        LumenCacheStats {
            active_cells: self.get_active_cells(),
            frame_hits: 0,
            frame_misses: 0,
            total_updates: self.get_total_updates(),
        }
    }
}