euv-core 0.52.1

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::*;

/// IBL baking and sampling methods for `EnvironmentIbl3D`.
impl EnvironmentIbl3D {
    /// Bakes an `EnvironmentIbl3D` from an equirectangular HDR environment image (`.hdr` / `.exr`).
    ///
    /// # Arguments
    ///
    /// - `&DecodedHdrImage` - Equirectangular linear HDR image.
    /// - `u32` - Base octahedral specular map resolution (clamped `>= 8`).
    /// - `u32` - Split-Sum BRDF LUT resolution (clamped `>= 8`).
    ///
    /// # Returns
    ///
    /// - `Self` - Precomputed diffuse SH + specular octahedral + BRDF LUT environment.
    #[must_use]
    pub fn from_equirectangular_hdr(hdr: &DecodedHdrImage, oct_size: u32, lut_size: u32) -> Self {
        Self::from_sampler(
            |dir: Vec3| -> Vec3 { sample_equirectangular_hdr(hdr, dir) },
            oct_size,
            lut_size,
        )
    }

    /// Bakes an `EnvironmentIbl3D` from the analytical sky dome and sun directional light.
    ///
    /// # Arguments
    ///
    /// - `&DirectionalLight3D` - Active directional sun and sky colors.
    /// - `u32` - Base octahedral specular map resolution.
    /// - `u32` - Split-Sum BRDF LUT resolution.
    ///
    /// # Returns
    ///
    /// - `Self` - Precomputed procedural sky IBL environment.
    #[must_use]
    pub fn from_procedural_sky(sun: &DirectionalLight3D, oct_size: u32, lut_size: u32) -> Self {
        let sun_dir: Vec3 = sun.get_direction().normalize();
        let sun_col: Vec3 = sun.get_color();
        let horizon: Vec3 = sun.get_sky_horizon();
        let zenith: Vec3 = sun.get_sky_zenith();
        Self::from_sampler(
            |dir: Vec3| -> Vec3 {
                let sky_t: f32 = (dir.get_y() * 0.5 + 0.5).clamp(0.0, 1.0);
                let base_sky: Vec3 = horizon.lerp(zenith, sky_t);
                let sun_dot: f32 = dir.dot(sun_dir).max(0.0);
                let sun_glow: f32 = sun_dot.powi(32) * 2.5;
                base_sky.add(sun_col.scale(sun_glow))
            },
            oct_size,
            lut_size,
        )
    }

    /// Precomputes SH9 diffuse irradiance, GGX octahedral specular mips, and BRDF LUT from any directional radiance closure.
    ///
    /// # Arguments
    ///
    /// - `F` - Directional radiance callback mapping unit world direction to linear RGB.
    /// - `u32` - Base octahedral specular resolution.
    /// - `u32` - Split-Sum BRDF LUT resolution.
    ///
    /// # Returns
    ///
    /// - `Self` - Precomputed IBL environment.
    #[must_use]
    pub fn from_sampler<F>(sampler: F, oct_size: u32, lut_size: u32) -> Self
    where
        F: Fn(Vec3) -> Vec3,
    {
        let base_oct: u32 = oct_size.max(8);
        let lut_dim: u32 = lut_size.max(8);
        let mut sh_accum: [[f32; 3]; 9] = [[0.0; 3]; 9];
        let sh_samples: u32 = 256;
        let sphere_weight: f32 = (4.0 * PI) / (sh_samples as f32);
        for idx in 0..sh_samples {
            let xi: [f32; 2] = hammersley_2d(idx, sh_samples);
            let z: f32 = 1.0 - 2.0 * xi[1];
            let r_xy: f32 = (1.0 - z * z).max(0.0).sqrt();
            let phi: f32 = TAU * xi[0];
            let dir: Vec3 = Vec3::new(r_xy * phi.cos(), z, r_xy * phi.sin()).normalize();
            let rad: Vec3 = sampler(dir);
            let basis: [f32; 9] = eval_sh_l2_basis(dir);
            for band in 0..9usize {
                let w: f32 = basis[band] * sphere_weight;
                sh_accum[band][0] += rad.get_x() * w;
                sh_accum[band][1] += rad.get_y() * w;
                sh_accum[band][2] += rad.get_z() * w;
            }
        }
        let conv_l0: f32 = PI;
        let conv_l1: f32 = (2.0 * PI) / 3.0;
        let conv_l2: f32 = PI * 0.25;
        let lobe_scales: [f32; 9] = [
            conv_l0, conv_l1, conv_l1, conv_l1, conv_l2, conv_l2, conv_l2, conv_l2, conv_l2,
        ];
        for band in 0..9usize {
            let s: f32 = lobe_scales[band] / PI;
            sh_accum[band][0] *= s;
            sh_accum[band][1] *= s;
            sh_accum[band][2] *= s;
        }
        let mut specular_mips: Vec<Vec<[f32; 3]>> = Vec::with_capacity(IBL_SPECULAR_MIP_COUNT);
        for mip in 0..IBL_SPECULAR_MIP_COUNT {
            let dim: usize = ((base_oct >> mip).max(4)) as usize;
            let roughness: f32 =
                (mip as f32) / ((IBL_SPECULAR_MIP_COUNT.saturating_sub(1)).max(1) as f32);
            let ggx_samples: u32 = if mip == 0 { 1 } else { 32 };
            let mut texels: Vec<[f32; 3]> = Vec::with_capacity(dim * dim);
            for row in 0..dim {
                let v: f32 = ((row as f32) + 0.5) / (dim as f32);
                for col in 0..dim {
                    let u: f32 = ((col as f32) + 0.5) / (dim as f32);
                    let normal: Vec3 = octahedral_decode([u, v]);
                    if mip == 0 {
                        let c: Vec3 = sampler(normal);
                        texels.push([c.get_x(), c.get_y(), c.get_z()]);
                    } else {
                        let mut sum_rgb: Vec3 = Vec3::zero();
                        let mut weight_sum: f32 = 0.0;
                        for s_idx in 0..ggx_samples {
                            let xi: [f32; 2] = hammersley_2d(s_idx, ggx_samples);
                            let half_v: Vec3 = importance_sample_ggx(xi, normal, roughness);
                            let light: Vec3 = half_v
                                .scale(2.0 * normal.dot(half_v))
                                .sub(normal)
                                .normalize();
                            let n_dot_l: f32 = normal.dot(light).max(0.0);
                            if n_dot_l > 0.0 {
                                sum_rgb = sum_rgb.add(sampler(light).scale(n_dot_l));
                                weight_sum += n_dot_l;
                            }
                        }
                        let inv_w: f32 = 1.0 / weight_sum.max(1e-5);
                        let filtered: Vec3 = sum_rgb.scale(inv_w);
                        texels.push([filtered.get_x(), filtered.get_y(), filtered.get_z()]);
                    }
                }
            }
            specular_mips.push(texels);
        }
        let brdf_lut: Vec<[f32; 2]> = compute_brdf_lut(lut_dim, 64);
        Self {
            sh_irradiance: sh_accum,
            specular_oct_size: base_oct,
            specular_mips,
            brdf_lut_size: lut_dim,
            brdf_lut,
            intensity: 1.0,
            rotation_y_rad: 0.0,
        }
    }

    /// Evaluates L2 9-band Spherical Harmonics diffuse irradiance along world-space `normal`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Environment IBL reference.
    /// - `Vec3` - Unit world-space surface normal.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linear HDR diffuse irradiance RGB.
    #[must_use]
    pub fn evaluate_sh_diffuse(&self, normal: Vec3) -> Vec3 {
        let dir: Vec3 = self.rotate_direction(normal.normalize());
        let basis: [f32; 9] = eval_sh_l2_basis(dir);
        let sh: [[f32; 3]; 9] = self.get_sh_irradiance();
        let mut r: f32 = 0.0;
        let mut g: f32 = 0.0;
        let mut b: f32 = 0.0;
        for band in 0..9usize {
            let w: f32 = basis[band];
            r += sh[band][0] * w;
            g += sh[band][1] * w;
            b += sh[band][2] * w;
        }
        let scale: f32 = self.get_intensity().max(0.0);
        Vec3::new(
            (r * scale).max(0.0),
            (g * scale).max(0.0),
            (b * scale).max(0.0),
        )
    }

    /// Samples the octahedral prefiltered specular radiance map along `reflect_dir` at perceptual `roughness`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Environment IBL reference.
    /// - `Vec3` - World-space reflection vector.
    /// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Trilinearly filtered prefiltered specular HDR radiance RGB.
    #[must_use]
    pub fn sample_specular_octahedral(&self, reflect_dir: Vec3, roughness: f32) -> Vec3 {
        let mips: &[Vec<[f32; 3]>] = self.get_specular_mips().as_slice();
        if mips.is_empty() {
            return Vec3::zero();
        }
        let dir: Vec3 = self.rotate_direction(reflect_dir.normalize());
        let uv: [f32; 2] = octahedral_encode(dir);
        let max_mip: f32 = (mips.len() - 1) as f32;
        let lod: f32 = roughness.clamp(0.0, 1.0) * max_mip;
        let m0: usize = lod.floor() as usize;
        let m1: usize = (m0 + 1).min(mips.len() - 1);
        let frac: f32 = lod - (m0 as f32);
        let c0: Vec3 = self.sample_specular_mip(m0, uv);
        let c1: Vec3 = if m0 == m1 {
            c0
        } else {
            self.sample_specular_mip(m1, uv)
        };
        c0.lerp(c1, frac).scale(self.get_intensity().max(0.0))
    }

    /// Looks up the bilinearly interpolated Split-Sum BRDF integration entry `[scale, bias]`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Environment IBL reference.
    /// - `f32` - Clamped view-normal cosine `N·V`.
    /// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `[f32; 2]` - Integrated `[scale, bias]` terms.
    #[must_use]
    pub fn sample_brdf_lut(&self, n_dot_v: f32, roughness: f32) -> [f32; 2] {
        let dim: usize = self.get_brdf_lut_size().max(1) as usize;
        let lut: &[[f32; 2]] = self.get_brdf_lut().as_slice();
        if lut.len() < dim * dim {
            return [1.0, 0.0];
        }
        let fx: f32 = (n_dot_v.clamp(0.0, 1.0) * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
        let fy: f32 = (roughness.clamp(0.0, 1.0) * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
        let x0: usize = fx.floor() as usize;
        let y0: usize = fy.floor() as usize;
        let x1: usize = (x0 + 1).min(dim - 1);
        let y1: usize = (y0 + 1).min(dim - 1);
        let tx: f32 = fx - (x0 as f32);
        let ty: f32 = fy - (y0 as f32);
        let s00: [f32; 2] = lut[y0 * dim + x0];
        let s10: [f32; 2] = lut[y0 * dim + x1];
        let s01: [f32; 2] = lut[y1 * dim + x0];
        let s11: [f32; 2] = lut[y1 * dim + x1];
        let top0: f32 = s00[0] + (s10[0] - s00[0]) * tx;
        let bot0: f32 = s01[0] + (s11[0] - s01[0]) * tx;
        let top1: f32 = s00[1] + (s10[1] - s00[1]) * tx;
        let bot1: f32 = s01[1] + (s11[1] - s01[1]) * tx;
        [top0 + (bot0 - top0) * ty, top1 + (bot1 - top1) * ty]
    }

    /// Applies the optional Y-axis environment rotation to lookup direction `dir`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Environment IBL reference.
    /// - `Vec3` - Input direction vector.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Rotated direction vector.
    #[must_use]
    fn rotate_direction(&self, dir: Vec3) -> Vec3 {
        let angle: f32 = self.get_rotation_y_rad();
        if angle.abs() <= 1e-6 {
            return dir;
        }
        let cos_a: f32 = angle.cos();
        let sin_a: f32 = angle.sin();
        Vec3::new(
            dir.get_x() * cos_a + dir.get_z() * sin_a,
            dir.get_y(),
            -dir.get_x() * sin_a + dir.get_z() * cos_a,
        )
    }

    /// Bilinearly samples a single octahedral specular mip level at `uv`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Environment IBL reference.
    /// - `usize` - Mip level index.
    /// - `[f32; 2]` - Octahedral UV coordinate.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Filtered RGB radiance.
    #[must_use]
    fn sample_specular_mip(&self, mip_idx: usize, uv: [f32; 2]) -> Vec3 {
        let mip: &[[f32; 3]] = self.get_specular_mips()[mip_idx].as_slice();
        let dim: usize = ((self.get_specular_oct_size() >> mip_idx).max(4)) as usize;
        if mip.len() < dim * dim {
            return Vec3::zero();
        }
        let fx: f32 = (uv[0].clamp(0.0, 1.0) * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
        let fy: f32 = (uv[1].clamp(0.0, 1.0) * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
        let x0: usize = fx.floor() as usize;
        let y0: usize = fy.floor() as usize;
        let x1: usize = (x0 + 1).min(dim - 1);
        let y1: usize = (y0 + 1).min(dim - 1);
        let tx: f32 = fx - (x0 as f32);
        let ty: f32 = fy - (y0 as f32);
        let c00: [f32; 3] = mip[y0 * dim + x0];
        let c10: [f32; 3] = mip[y0 * dim + x1];
        let c01: [f32; 3] = mip[y1 * dim + x0];
        let c11: [f32; 3] = mip[y1 * dim + x1];
        let top: Vec3 = Vec3::from_array(c00).lerp(Vec3::from_array(c10), tx);
        let bot: Vec3 = Vec3::from_array(c01).lerp(Vec3::from_array(c11), tx);
        top.lerp(bot, ty)
    }
}