Skip to main content

euv_core/game/engine3d/environment/
impl.rs

1use super::*;
2
3/// IBL baking and sampling methods for `EnvironmentIbl3D`.
4impl EnvironmentIbl3D {
5    /// Bakes an `EnvironmentIbl3D` from an equirectangular HDR environment image (`.hdr` / `.exr`).
6    ///
7    /// # Arguments
8    ///
9    /// - `&DecodedHdrImage` - Equirectangular linear HDR image.
10    /// - `u32` - Base octahedral specular map resolution (clamped `>= 8`).
11    /// - `u32` - Split-Sum BRDF LUT resolution (clamped `>= 8`).
12    ///
13    /// # Returns
14    ///
15    /// - `Self` - Precomputed diffuse SH + specular octahedral + BRDF LUT environment.
16    #[must_use]
17    pub fn from_equirectangular_hdr(hdr: &DecodedHdrImage, oct_size: u32, lut_size: u32) -> Self {
18        Self::from_sampler(
19            |dir: Vec3| -> Vec3 { sample_equirectangular_hdr(hdr, dir) },
20            oct_size,
21            lut_size,
22        )
23    }
24
25    /// Bakes an `EnvironmentIbl3D` from the analytical sky dome and sun directional light.
26    ///
27    /// # Arguments
28    ///
29    /// - `&DirectionalLight3D` - Active directional sun and sky colors.
30    /// - `u32` - Base octahedral specular map resolution.
31    /// - `u32` - Split-Sum BRDF LUT resolution.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Precomputed procedural sky IBL environment.
36    #[must_use]
37    pub fn from_procedural_sky(sun: &DirectionalLight3D, oct_size: u32, lut_size: u32) -> Self {
38        let sun_dir: Vec3 = sun.get_direction().normalize();
39        let sun_col: Vec3 = sun.get_color();
40        let horizon: Vec3 = sun.get_sky_horizon();
41        let zenith: Vec3 = sun.get_sky_zenith();
42        Self::from_sampler(
43            |dir: Vec3| -> Vec3 {
44                let sky_t: f32 = (dir.get_y() * 0.5 + 0.5).clamp(0.0, 1.0);
45                let base_sky: Vec3 = horizon.lerp(zenith, sky_t);
46                let sun_dot: f32 = dir.dot(sun_dir).max(0.0);
47                let sun_glow: f32 = sun_dot.powi(32) * 2.5;
48                base_sky.add(sun_col.scale(sun_glow))
49            },
50            oct_size,
51            lut_size,
52        )
53    }
54
55    /// Precomputes SH9 diffuse irradiance, GGX octahedral specular mips, and BRDF LUT from any directional radiance closure.
56    ///
57    /// # Arguments
58    ///
59    /// - `F` - Directional radiance callback mapping unit world direction to linear RGB.
60    /// - `u32` - Base octahedral specular resolution.
61    /// - `u32` - Split-Sum BRDF LUT resolution.
62    ///
63    /// # Returns
64    ///
65    /// - `Self` - Precomputed IBL environment.
66    #[must_use]
67    pub fn from_sampler<F>(sampler: F, oct_size: u32, lut_size: u32) -> Self
68    where
69        F: Fn(Vec3) -> Vec3,
70    {
71        let base_oct: u32 = oct_size.max(8);
72        let lut_dim: u32 = lut_size.max(8);
73        let mut sh_accum: [[f32; 3]; 9] = [[0.0; 3]; 9];
74        let sh_samples: u32 = 256;
75        let sphere_weight: f32 = (4.0 * PI) / (sh_samples as f32);
76        for idx in 0..sh_samples {
77            let xi: [f32; 2] = hammersley_2d(idx, sh_samples);
78            let z: f32 = 1.0 - 2.0 * xi[1];
79            let r_xy: f32 = (1.0 - z * z).max(0.0).sqrt();
80            let phi: f32 = TAU * xi[0];
81            let dir: Vec3 = Vec3::new(r_xy * phi.cos(), z, r_xy * phi.sin()).normalize();
82            let rad: Vec3 = sampler(dir);
83            let basis: [f32; 9] = eval_sh_l2_basis(dir);
84            for band in 0..9usize {
85                let w: f32 = basis[band] * sphere_weight;
86                sh_accum[band][0] += rad.get_x() * w;
87                sh_accum[band][1] += rad.get_y() * w;
88                sh_accum[band][2] += rad.get_z() * w;
89            }
90        }
91        let conv_l0: f32 = PI;
92        let conv_l1: f32 = (2.0 * PI) / 3.0;
93        let conv_l2: f32 = PI * 0.25;
94        let lobe_scales: [f32; 9] = [
95            conv_l0, conv_l1, conv_l1, conv_l1, conv_l2, conv_l2, conv_l2, conv_l2, conv_l2,
96        ];
97        for band in 0..9usize {
98            let s: f32 = lobe_scales[band] / PI;
99            sh_accum[band][0] *= s;
100            sh_accum[band][1] *= s;
101            sh_accum[band][2] *= s;
102        }
103        let mut specular_mips: Vec<Vec<[f32; 3]>> = Vec::with_capacity(IBL_SPECULAR_MIP_COUNT);
104        for mip in 0..IBL_SPECULAR_MIP_COUNT {
105            let dim: usize = ((base_oct >> mip).max(4)) as usize;
106            let roughness: f32 =
107                (mip as f32) / ((IBL_SPECULAR_MIP_COUNT.saturating_sub(1)).max(1) as f32);
108            let ggx_samples: u32 = if mip == 0 { 1 } else { 32 };
109            let mut texels: Vec<[f32; 3]> = Vec::with_capacity(dim * dim);
110            for row in 0..dim {
111                let v: f32 = ((row as f32) + 0.5) / (dim as f32);
112                for col in 0..dim {
113                    let u: f32 = ((col as f32) + 0.5) / (dim as f32);
114                    let normal: Vec3 = octahedral_decode([u, v]);
115                    if mip == 0 {
116                        let c: Vec3 = sampler(normal);
117                        texels.push([c.get_x(), c.get_y(), c.get_z()]);
118                    } else {
119                        let mut sum_rgb: Vec3 = Vec3::zero();
120                        let mut weight_sum: f32 = 0.0;
121                        for s_idx in 0..ggx_samples {
122                            let xi: [f32; 2] = hammersley_2d(s_idx, ggx_samples);
123                            let half_v: Vec3 = importance_sample_ggx(xi, normal, roughness);
124                            let light: Vec3 = half_v
125                                .scale(2.0 * normal.dot(half_v))
126                                .sub(normal)
127                                .normalize();
128                            let n_dot_l: f32 = normal.dot(light).max(0.0);
129                            if n_dot_l > 0.0 {
130                                sum_rgb = sum_rgb.add(sampler(light).scale(n_dot_l));
131                                weight_sum += n_dot_l;
132                            }
133                        }
134                        let inv_w: f32 = 1.0 / weight_sum.max(1e-5);
135                        let filtered: Vec3 = sum_rgb.scale(inv_w);
136                        texels.push([filtered.get_x(), filtered.get_y(), filtered.get_z()]);
137                    }
138                }
139            }
140            specular_mips.push(texels);
141        }
142        let brdf_lut: Vec<[f32; 2]> = compute_brdf_lut(lut_dim, 64);
143        Self {
144            sh_irradiance: sh_accum,
145            specular_oct_size: base_oct,
146            specular_mips,
147            brdf_lut_size: lut_dim,
148            brdf_lut,
149            intensity: 1.0,
150            rotation_y_rad: 0.0,
151        }
152    }
153
154    /// Evaluates L2 9-band Spherical Harmonics diffuse irradiance along world-space `normal`.
155    ///
156    /// # Arguments
157    ///
158    /// - `&Self` - Environment IBL reference.
159    /// - `Vec3` - Unit world-space surface normal.
160    ///
161    /// # Returns
162    ///
163    /// - `Vec3` - Linear HDR diffuse irradiance RGB.
164    #[must_use]
165    pub fn evaluate_sh_diffuse(&self, normal: Vec3) -> Vec3 {
166        let dir: Vec3 = self.rotate_direction(normal.normalize());
167        let basis: [f32; 9] = eval_sh_l2_basis(dir);
168        let sh: [[f32; 3]; 9] = self.get_sh_irradiance();
169        let mut r: f32 = 0.0;
170        let mut g: f32 = 0.0;
171        let mut b: f32 = 0.0;
172        for band in 0..9usize {
173            let w: f32 = basis[band];
174            r += sh[band][0] * w;
175            g += sh[band][1] * w;
176            b += sh[band][2] * w;
177        }
178        let scale: f32 = self.get_intensity().max(0.0);
179        Vec3::new(
180            (r * scale).max(0.0),
181            (g * scale).max(0.0),
182            (b * scale).max(0.0),
183        )
184    }
185
186    /// Samples the octahedral prefiltered specular radiance map along `reflect_dir` at perceptual `roughness`.
187    ///
188    /// # Arguments
189    ///
190    /// - `&Self` - Environment IBL reference.
191    /// - `Vec3` - World-space reflection vector.
192    /// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
193    ///
194    /// # Returns
195    ///
196    /// - `Vec3` - Trilinearly filtered prefiltered specular HDR radiance RGB.
197    #[must_use]
198    pub fn sample_specular_octahedral(&self, reflect_dir: Vec3, roughness: f32) -> Vec3 {
199        let mips: &[Vec<[f32; 3]>] = self.get_specular_mips().as_slice();
200        if mips.is_empty() {
201            return Vec3::zero();
202        }
203        let dir: Vec3 = self.rotate_direction(reflect_dir.normalize());
204        let uv: [f32; 2] = octahedral_encode(dir);
205        let max_mip: f32 = (mips.len() - 1) as f32;
206        let lod: f32 = roughness.clamp(0.0, 1.0) * max_mip;
207        let m0: usize = lod.floor() as usize;
208        let m1: usize = (m0 + 1).min(mips.len() - 1);
209        let frac: f32 = lod - (m0 as f32);
210        let c0: Vec3 = self.sample_specular_mip(m0, uv);
211        let c1: Vec3 = if m0 == m1 {
212            c0
213        } else {
214            self.sample_specular_mip(m1, uv)
215        };
216        c0.lerp(c1, frac).scale(self.get_intensity().max(0.0))
217    }
218
219    /// Looks up the bilinearly interpolated Split-Sum BRDF integration entry `[scale, bias]`.
220    ///
221    /// # Arguments
222    ///
223    /// - `&Self` - Environment IBL reference.
224    /// - `f32` - Clamped view-normal cosine `N·V`.
225    /// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
226    ///
227    /// # Returns
228    ///
229    /// - `[f32; 2]` - Integrated `[scale, bias]` terms.
230    #[must_use]
231    pub fn sample_brdf_lut(&self, n_dot_v: f32, roughness: f32) -> [f32; 2] {
232        let dim: usize = self.get_brdf_lut_size().max(1) as usize;
233        let lut: &[[f32; 2]] = self.get_brdf_lut().as_slice();
234        if lut.len() < dim * dim {
235            return [1.0, 0.0];
236        }
237        let fx: f32 = (n_dot_v.clamp(0.0, 1.0) * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
238        let fy: f32 = (roughness.clamp(0.0, 1.0) * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
239        let x0: usize = fx.floor() as usize;
240        let y0: usize = fy.floor() as usize;
241        let x1: usize = (x0 + 1).min(dim - 1);
242        let y1: usize = (y0 + 1).min(dim - 1);
243        let tx: f32 = fx - (x0 as f32);
244        let ty: f32 = fy - (y0 as f32);
245        let s00: [f32; 2] = lut[y0 * dim + x0];
246        let s10: [f32; 2] = lut[y0 * dim + x1];
247        let s01: [f32; 2] = lut[y1 * dim + x0];
248        let s11: [f32; 2] = lut[y1 * dim + x1];
249        let top0: f32 = s00[0] + (s10[0] - s00[0]) * tx;
250        let bot0: f32 = s01[0] + (s11[0] - s01[0]) * tx;
251        let top1: f32 = s00[1] + (s10[1] - s00[1]) * tx;
252        let bot1: f32 = s01[1] + (s11[1] - s01[1]) * tx;
253        [top0 + (bot0 - top0) * ty, top1 + (bot1 - top1) * ty]
254    }
255
256    /// Applies the optional Y-axis environment rotation to lookup direction `dir`.
257    ///
258    /// # Arguments
259    ///
260    /// - `&Self` - Environment IBL reference.
261    /// - `Vec3` - Input direction vector.
262    ///
263    /// # Returns
264    ///
265    /// - `Vec3` - Rotated direction vector.
266    #[must_use]
267    fn rotate_direction(&self, dir: Vec3) -> Vec3 {
268        let angle: f32 = self.get_rotation_y_rad();
269        if angle.abs() <= 1e-6 {
270            return dir;
271        }
272        let cos_a: f32 = angle.cos();
273        let sin_a: f32 = angle.sin();
274        Vec3::new(
275            dir.get_x() * cos_a + dir.get_z() * sin_a,
276            dir.get_y(),
277            -dir.get_x() * sin_a + dir.get_z() * cos_a,
278        )
279    }
280
281    /// Bilinearly samples a single octahedral specular mip level at `uv`.
282    ///
283    /// # Arguments
284    ///
285    /// - `&Self` - Environment IBL reference.
286    /// - `usize` - Mip level index.
287    /// - `[f32; 2]` - Octahedral UV coordinate.
288    ///
289    /// # Returns
290    ///
291    /// - `Vec3` - Filtered RGB radiance.
292    #[must_use]
293    fn sample_specular_mip(&self, mip_idx: usize, uv: [f32; 2]) -> Vec3 {
294        let mip: &[[f32; 3]] = self.get_specular_mips()[mip_idx].as_slice();
295        let dim: usize = ((self.get_specular_oct_size() >> mip_idx).max(4)) as usize;
296        if mip.len() < dim * dim {
297            return Vec3::zero();
298        }
299        let fx: f32 = (uv[0].clamp(0.0, 1.0) * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
300        let fy: f32 = (uv[1].clamp(0.0, 1.0) * (dim as f32) - 0.5).clamp(0.0, (dim - 1) as f32);
301        let x0: usize = fx.floor() as usize;
302        let y0: usize = fy.floor() as usize;
303        let x1: usize = (x0 + 1).min(dim - 1);
304        let y1: usize = (y0 + 1).min(dim - 1);
305        let tx: f32 = fx - (x0 as f32);
306        let ty: f32 = fy - (y0 as f32);
307        let c00: [f32; 3] = mip[y0 * dim + x0];
308        let c10: [f32; 3] = mip[y0 * dim + x1];
309        let c01: [f32; 3] = mip[y1 * dim + x0];
310        let c11: [f32; 3] = mip[y1 * dim + x1];
311        let top: Vec3 = Vec3::from_array(c00).lerp(Vec3::from_array(c10), tx);
312        let bot: Vec3 = Vec3::from_array(c01).lerp(Vec3::from_array(c11), tx);
313        top.lerp(bot, ty)
314    }
315}