Skip to main content

euv_core/game/engine3d/environment/
fn.rs

1use super::*;
2
3/// Encodes a unit 3D direction vector onto a `[0.0, 1.0]^2` octahedral UV map.
4///
5/// # Arguments
6///
7/// - `Vec3` - Input direction vector.
8///
9/// # Returns
10///
11/// - `[f32; 2]` - Octahedral UV coordinate in `[0.0, 1.0]^2`.
12#[must_use]
13pub fn octahedral_encode(direction: Vec3) -> [f32; 2] {
14    let dir: Vec3 = direction.normalize();
15    let l1: f32 = (dir.get_x().abs() + dir.get_y().abs() + dir.get_z().abs()).max(1e-6);
16    let mut ox: f32 = dir.get_x() / l1;
17    let mut oz: f32 = dir.get_z() / l1;
18    if dir.get_y() < 0.0 {
19        let prev_x: f32 = ox;
20        let prev_z: f32 = oz;
21        let sign_x: f32 = if prev_x >= 0.0 { 1.0 } else { -1.0 };
22        let sign_z: f32 = if prev_z >= 0.0 { 1.0 } else { -1.0 };
23        ox = (1.0 - prev_z.abs()) * sign_x;
24        oz = (1.0 - prev_x.abs()) * sign_z;
25    }
26    [ox * 0.5 + 0.5, oz * 0.5 + 0.5]
27}
28
29/// Decodes a `[0.0, 1.0]^2` octahedral UV coordinate back into a unit 3D direction vector.
30///
31/// # Arguments
32///
33/// - `[f32; 2]` - Octahedral UV coordinate in `[0.0, 1.0]^2`.
34///
35/// # Returns
36///
37/// - `Vec3` - Reconstructed unit 3D direction vector.
38#[must_use]
39pub fn octahedral_decode(uv: [f32; 2]) -> Vec3 {
40    let fx: f32 = uv[0] * 2.0 - 1.0;
41    let fz: f32 = uv[1] * 2.0 - 1.0;
42    let fy: f32 = 1.0 - fx.abs() - fz.abs();
43    let (ox, oz): (f32, f32) = if fy < 0.0 {
44        let sign_x: f32 = if fx >= 0.0 { 1.0 } else { -1.0 };
45        let sign_z: f32 = if fz >= 0.0 { 1.0 } else { -1.0 };
46        ((1.0 - fz.abs()) * sign_x, (1.0 - fx.abs()) * sign_z)
47    } else {
48        (fx, fz)
49    };
50    Vec3::new(ox, fy, oz).normalize()
51}
52
53/// Evaluates the 2D Hammersley low-discrepancy quasi-Monte Carlo point at `index / count`.
54///
55/// # Arguments
56///
57/// - `u32` - Sample index (`0..count`).
58/// - `u32` - Total sample count (`>= 1`).
59///
60/// # Returns
61///
62/// - `[f32; 2]` - Quasi-random unit square sample in `[0.0, 1.0)^2`.
63#[must_use]
64pub fn hammersley_2d(index: u32, count: u32) -> [f32; 2] {
65    let radical: f32 = (index.reverse_bits() as f32) * 2.328_306_4e-10;
66    [(index as f32) / (count.max(1) as f32), radical]
67}
68
69/// Importance-samples a GGX microfacet half-vector around `normal` for perceptual `roughness`.
70///
71/// # Arguments
72///
73/// - `[f32; 2]` - Uniform sample in `[0.0, 1.0)^2`.
74/// - `Vec3` - Surface normal direction.
75/// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
76///
77/// # Returns
78///
79/// - `Vec3` - Importance-sampled unit half-vector.
80#[must_use]
81pub fn importance_sample_ggx(xi: [f32; 2], normal: Vec3, roughness: f32) -> Vec3 {
82    let alpha: f32 = roughness * roughness;
83    let alpha2: f32 = alpha * alpha;
84    let phi: f32 = TAU * xi[0];
85    let cos_theta: f32 = ((1.0 - xi[1]) / (1.0 + (alpha2 - 1.0) * xi[1]).max(1e-6))
86        .max(0.0)
87        .sqrt();
88    let sin_theta: f32 = (1.0 - cos_theta * cos_theta).max(0.0).sqrt();
89    let h_local: Vec3 = Vec3::new(phi.cos() * sin_theta, phi.sin() * sin_theta, cos_theta);
90    let up: Vec3 = if normal.get_z().abs() < 0.999 {
91        Vec3::new(0.0, 0.0, 1.0)
92    } else {
93        Vec3::new(1.0, 0.0, 0.0)
94    };
95    let tangent: Vec3 = up.cross(normal).normalize();
96    let bitangent: Vec3 = normal.cross(tangent);
97    tangent
98        .scale(h_local.get_x())
99        .add(bitangent.scale(h_local.get_y()))
100        .add(normal.scale(h_local.get_z()))
101        .normalize()
102}
103
104/// Evaluates the Smith GGX geometry shadowing-masking term `G(NdotV, NdotL)` for IBL integration.
105///
106/// # Arguments
107///
108/// - `f32` - Clamped `N·V`.
109/// - `f32` - Clamped `N·L`.
110/// - `f32` - Perceptual roughness.
111///
112/// # Returns
113///
114/// - `f32` - Smith geometry attenuation term.
115#[cfg_attr(not(target_arch = "wasm32"), inline)]
116#[must_use]
117fn geometry_smith_ibl(n_dot_v: f32, n_dot_l: f32, roughness: f32) -> f32 {
118    let k: f32 = (roughness * roughness) * 0.5;
119    let gv: f32 = n_dot_v / (n_dot_v * (1.0 - k) + k).max(1e-5);
120    let gl: f32 = n_dot_l / (n_dot_l * (1.0 - k) + k).max(1e-5);
121    gv * gl
122}
123
124/// Integrates the Split-Sum GGX BRDF lookup table `[scale, bias]` across `(N·V, roughness)`.
125///
126/// # Arguments
127///
128/// - `u32` - Square LUT dimension (`size x size`).
129/// - `u32` - Hammersley Monte Carlo sample count per texel.
130///
131/// # Returns
132///
133/// - `Vec<[f32; 2]>` - Row-major `[scale, bias]` pairs (`len == size * size`).
134#[must_use]
135pub fn compute_brdf_lut(size: u32, samples: u32) -> Vec<[f32; 2]> {
136    let dim: usize = size.max(4) as usize;
137    let sample_count: u32 = samples.max(16);
138    let mut lut: Vec<[f32; 2]> = Vec::with_capacity(dim * dim);
139    let normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
140    for row in 0..dim {
141        let roughness: f32 = (((row as f32) + 0.5) / (dim as f32)).clamp(0.02, 1.0);
142        for col in 0..dim {
143            let n_dot_v: f32 = (((col as f32) + 0.5) / (dim as f32)).clamp(0.01, 1.0);
144            let view: Vec3 = Vec3::new((1.0 - n_dot_v * n_dot_v).max(0.0).sqrt(), 0.0, n_dot_v);
145            let mut sum_a: f32 = 0.0;
146            let mut sum_b: f32 = 0.0;
147            for idx in 0..sample_count {
148                let xi: [f32; 2] = hammersley_2d(idx, sample_count);
149                let half_v: Vec3 = importance_sample_ggx(xi, normal, roughness);
150                let v_dot_h: f32 = view.dot(half_v).max(0.0);
151                let light: Vec3 = half_v.scale(2.0 * v_dot_h).sub(view).normalize();
152                let n_dot_l: f32 = light.get_z().max(0.0);
153                let n_dot_h: f32 = half_v.get_z().max(0.0);
154                if n_dot_l > 0.0 {
155                    let g_val: f32 = geometry_smith_ibl(n_dot_v, n_dot_l, roughness);
156                    let g_vis: f32 = (g_val * v_dot_h) / (n_dot_h * n_dot_v).max(1e-5);
157                    let fc: f32 = (1.0 - v_dot_h).powi(5);
158                    sum_a += (1.0 - fc) * g_vis;
159                    sum_b += fc * g_vis;
160                }
161            }
162            let inv_s: f32 = 1.0 / (sample_count as f32);
163            lut.push([
164                (sum_a * inv_s).clamp(0.0, 1.0),
165                (sum_b * inv_s).clamp(0.0, 1.0),
166            ]);
167        }
168    }
169    lut
170}
171
172/// Evaluates Kulla-Conty multi-scattering energy compensation factor `1 + F0 * (1 / E_ss - 1)`.
173///
174/// # Arguments
175///
176/// - `Vec3` - Surface base Fresnel reflectance `F0`.
177/// - `f32` - Single-scattering directional albedo `brdf_scale + brdf_bias`.
178///
179/// # Returns
180///
181/// - `Vec3` - Multi-scattering RGB boost factor (`>= 1.0`).
182#[must_use]
183pub fn kulla_conty_multiscatter_factor(f0: Vec3, single_scatter_albedo: f32) -> Vec3 {
184    let inv_e: f32 = (1.0 / single_scatter_albedo.clamp(0.05, 1.0)) - 1.0;
185    Vec3::new(
186        1.0 + f0.get_x() * inv_e,
187        1.0 + f0.get_y() * inv_e,
188        1.0 + f0.get_z() * inv_e,
189    )
190}
191
192/// Evaluates the 9 real L2 Spherical Harmonics basis functions for unit direction `dir`.
193///
194/// # Arguments
195///
196/// - `Vec3` - Unit direction vector.
197///
198/// # Returns
199///
200/// - `[f32; 9]` - L2 SH basis values `[Y00, Y1-1, Y10, Y11, Y2-2, Y2-1, Y20, Y21, Y22]`.
201#[must_use]
202pub fn eval_sh_l2_basis(dir: Vec3) -> [f32; 9] {
203    let x: f32 = dir.get_x();
204    let y: f32 = dir.get_y();
205    let z: f32 = dir.get_z();
206    [
207        SH_C0,
208        SH_C1 * y,
209        SH_C1 * z,
210        SH_C1 * x,
211        SH_C2_0 * x * y,
212        SH_C2_0 * y * z,
213        SH_C2_1 * (3.0 * z * z - 1.0),
214        SH_C2_0 * x * z,
215        SH_C2_2 * (x * x - y * y),
216    ]
217}
218
219/// Evaluates the 6th-order Blender AgX sigmoid contrast curve on normalized log2 channels `[0..1]`.
220///
221/// # Arguments
222///
223/// - `f32` - Normalized log2 input channel in `[0.0, 1.0]`.
224///
225/// # Returns
226///
227/// - `f32` - Sigmoid-mapped AgX channel in `[0.0, 1.0]`.
228#[cfg_attr(not(target_arch = "wasm32"), inline)]
229#[must_use]
230fn agx_default_contrast_approx(x: f32) -> f32 {
231    let x2: f32 = x * x;
232    let x4: f32 = x2 * x2;
233    let poly: f32 =
234        15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.429_8 * x2 + 0.119_1 * x
235            - 0.002_32;
236    poly.clamp(0.0, 1.0)
237}
238
239/// Applies Blender 4.0+/5.x **AgX** filmic view-transform tone mapping from linear HDR RGB to linear display RGB `[0..1]`.
240///
241/// # Arguments
242///
243/// - `Vec3` - Linear scene-referred HDR RGB radiance.
244///
245/// # Returns
246///
247/// - `Vec3` - Display-referred linear RGB color in `[0.0, 1.0]`.
248#[must_use]
249pub fn agx_tonemap(hdr: Vec3) -> Vec3 {
250    let r: f32 = hdr.get_x().max(1e-6);
251    let g: f32 = hdr.get_y().max(1e-6);
252    let b: f32 = hdr.get_z().max(1e-6);
253    let inset_r: f32 =
254        AGX_INSET_MATRIX[0][0] * r + AGX_INSET_MATRIX[0][1] * g + AGX_INSET_MATRIX[0][2] * b;
255    let inset_g: f32 =
256        AGX_INSET_MATRIX[1][0] * r + AGX_INSET_MATRIX[1][1] * g + AGX_INSET_MATRIX[1][2] * b;
257    let inset_b: f32 =
258        AGX_INSET_MATRIX[2][0] * r + AGX_INSET_MATRIX[2][1] * g + AGX_INSET_MATRIX[2][2] * b;
259    let ev_span: f32 = AGX_MAX_EV - AGX_MIN_EV;
260    let cr: f32 = agx_default_contrast_approx(
261        (inset_r.max(1e-6).log2().clamp(AGX_MIN_EV, AGX_MAX_EV) - AGX_MIN_EV) / ev_span,
262    );
263    let cg: f32 = agx_default_contrast_approx(
264        (inset_g.max(1e-6).log2().clamp(AGX_MIN_EV, AGX_MAX_EV) - AGX_MIN_EV) / ev_span,
265    );
266    let cb: f32 = agx_default_contrast_approx(
267        (inset_b.max(1e-6).log2().clamp(AGX_MIN_EV, AGX_MAX_EV) - AGX_MIN_EV) / ev_span,
268    );
269    let out_r: f32 =
270        AGX_OUTSET_MATRIX[0][0] * cr + AGX_OUTSET_MATRIX[0][1] * cg + AGX_OUTSET_MATRIX[0][2] * cb;
271    let out_g: f32 =
272        AGX_OUTSET_MATRIX[1][0] * cr + AGX_OUTSET_MATRIX[1][1] * cg + AGX_OUTSET_MATRIX[1][2] * cb;
273    let out_b: f32 =
274        AGX_OUTSET_MATRIX[2][0] * cr + AGX_OUTSET_MATRIX[2][1] * cg + AGX_OUTSET_MATRIX[2][2] * cb;
275    Vec3::new(
276        out_r.clamp(0.0, 1.0).powf(2.2),
277        out_g.clamp(0.0, 1.0).powf(2.2),
278        out_b.clamp(0.0, 1.0).powf(2.2),
279    )
280}
281
282/// Applies Narkowicz ACES Filmic tone mapping from linear HDR RGB to display linear RGB `[0..1]`.
283///
284/// # Arguments
285///
286/// - `Vec3` - Linear scene-referred HDR RGB radiance.
287///
288/// # Returns
289///
290/// - `Vec3` - Display-referred linear RGB color in `[0.0, 1.0]`.
291#[must_use]
292pub fn aces_filmic_tonemap(hdr: Vec3) -> Vec3 {
293    let map_ch: fn(f32) -> f32 = |val: f32| -> f32 {
294        let v: f32 = val.max(0.0);
295        let num: f32 = v * (2.51 * v + 0.03);
296        let den: f32 = v * (2.43 * v + 0.59) + 0.14;
297        (num / den.max(1e-4)).clamp(0.0, 1.0)
298    };
299    Vec3::new(
300        map_ch(hdr.get_x()),
301        map_ch(hdr.get_y()),
302        map_ch(hdr.get_z()),
303    )
304}
305
306/// Samples an equirectangular HDR image in direction `dir` using bilinear interpolation.
307///
308/// # Arguments
309///
310/// - `&DecodedHdrImage` - Equirectangular linear HDR image.
311/// - `Vec3` - Unit world-space lookup direction.
312///
313/// # Returns
314///
315/// - `Vec3` - Bilinearly filtered linear HDR RGB radiance.
316#[must_use]
317pub fn sample_equirectangular_hdr(hdr: &DecodedHdrImage, direction: Vec3) -> Vec3 {
318    let w: usize = hdr.get_width().max(1) as usize;
319    let h: usize = hdr.get_height().max(1) as usize;
320    let px: &[f32] = hdr.get_pixels().as_slice();
321    if px.len() < w * h * 4 {
322        return Vec3::zero();
323    }
324    let dir: Vec3 = direction.normalize();
325    let phi: f32 = dir.get_z().atan2(dir.get_x());
326    let u: f32 = (phi / TAU + 0.5).rem_euclid(1.0);
327    let v: f32 = (dir.get_y().clamp(-1.0, 1.0).acos() / PI).clamp(0.0, 1.0);
328    let fx: f32 = u * (w as f32) - 0.5;
329    let fy: f32 = (v * (h as f32) - 0.5).clamp(0.0, (h - 1) as f32);
330    let x0: usize = (fx.floor() as isize).rem_euclid(w as isize) as usize;
331    let x1: usize = (x0 + 1) % w;
332    let y0: usize = fy.floor() as usize;
333    let y1: usize = (y0 + 1).min(h - 1);
334    let tx: f32 = fx - fx.floor();
335    let ty: f32 = fy - (y0 as f32);
336    let o00: usize = (y0 * w + x0) * 4;
337    let o10: usize = (y0 * w + x1) * 4;
338    let o01: usize = (y1 * w + x0) * 4;
339    let o11: usize = (y1 * w + x1) * 4;
340    let c00: Vec3 = Vec3::new(px[o00], px[o00 + 1], px[o00 + 2]);
341    let c10: Vec3 = Vec3::new(px[o10], px[o10 + 1], px[o10 + 2]);
342    let c01: Vec3 = Vec3::new(px[o01], px[o01 + 1], px[o01 + 2]);
343    let c11: Vec3 = Vec3::new(px[o11], px[o11 + 1], px[o11 + 2]);
344    let top: Vec3 = c00.lerp(c10, tx);
345    let bot: Vec3 = c01.lerp(c11, tx);
346    top.lerp(bot, ty)
347}