euv-core 0.53.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::*;

/// Encodes a unit 3D direction vector onto a `[0.0, 1.0]^2` octahedral UV map.
///
/// # Arguments
///
/// - `Vec3` - Input direction vector.
///
/// # Returns
///
/// - `[f32; 2]` - Octahedral UV coordinate in `[0.0, 1.0]^2`.
#[must_use]
pub fn octahedral_encode(direction: Vec3) -> [f32; 2] {
    let dir: Vec3 = direction.normalize();
    let l1: f32 = (dir.get_x().abs() + dir.get_y().abs() + dir.get_z().abs()).max(1e-6);
    let mut ox: f32 = dir.get_x() / l1;
    let mut oz: f32 = dir.get_z() / l1;
    if dir.get_y() < 0.0 {
        let prev_x: f32 = ox;
        let prev_z: f32 = oz;
        let sign_x: f32 = if prev_x >= 0.0 { 1.0 } else { -1.0 };
        let sign_z: f32 = if prev_z >= 0.0 { 1.0 } else { -1.0 };
        ox = (1.0 - prev_z.abs()) * sign_x;
        oz = (1.0 - prev_x.abs()) * sign_z;
    }
    [ox * 0.5 + 0.5, oz * 0.5 + 0.5]
}

/// Decodes a `[0.0, 1.0]^2` octahedral UV coordinate back into a unit 3D direction vector.
///
/// # Arguments
///
/// - `[f32; 2]` - Octahedral UV coordinate in `[0.0, 1.0]^2`.
///
/// # Returns
///
/// - `Vec3` - Reconstructed unit 3D direction vector.
#[must_use]
pub fn octahedral_decode(uv: [f32; 2]) -> Vec3 {
    let fx: f32 = uv[0] * 2.0 - 1.0;
    let fz: f32 = uv[1] * 2.0 - 1.0;
    let fy: f32 = 1.0 - fx.abs() - fz.abs();
    let (ox, oz): (f32, f32) = if fy < 0.0 {
        let sign_x: f32 = if fx >= 0.0 { 1.0 } else { -1.0 };
        let sign_z: f32 = if fz >= 0.0 { 1.0 } else { -1.0 };
        ((1.0 - fz.abs()) * sign_x, (1.0 - fx.abs()) * sign_z)
    } else {
        (fx, fz)
    };
    Vec3::new(ox, fy, oz).normalize()
}

/// Evaluates the 2D Hammersley low-discrepancy quasi-Monte Carlo point at `index / count`.
///
/// # Arguments
///
/// - `u32` - Sample index (`0..count`).
/// - `u32` - Total sample count (`>= 1`).
///
/// # Returns
///
/// - `[f32; 2]` - Quasi-random unit square sample in `[0.0, 1.0)^2`.
#[must_use]
pub fn hammersley_2d(index: u32, count: u32) -> [f32; 2] {
    let radical: f32 = (index.reverse_bits() as f32) * 2.328_306_4e-10;
    [(index as f32) / (count.max(1) as f32), radical]
}

/// Importance-samples a GGX microfacet half-vector around `normal` for perceptual `roughness`.
///
/// # Arguments
///
/// - `[f32; 2]` - Uniform sample in `[0.0, 1.0)^2`.
/// - `Vec3` - Surface normal direction.
/// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
///
/// # Returns
///
/// - `Vec3` - Importance-sampled unit half-vector.
#[must_use]
pub fn importance_sample_ggx(xi: [f32; 2], normal: Vec3, roughness: f32) -> Vec3 {
    let alpha: f32 = roughness * roughness;
    let alpha2: f32 = alpha * alpha;
    let phi: f32 = TAU * xi[0];
    let cos_theta: f32 = ((1.0 - xi[1]) / (1.0 + (alpha2 - 1.0) * xi[1]).max(1e-6))
        .max(0.0)
        .sqrt();
    let sin_theta: f32 = (1.0 - cos_theta * cos_theta).max(0.0).sqrt();
    let h_local: Vec3 = Vec3::new(phi.cos() * sin_theta, phi.sin() * sin_theta, cos_theta);
    let up: Vec3 = if normal.get_z().abs() < 0.999 {
        Vec3::new(0.0, 0.0, 1.0)
    } else {
        Vec3::new(1.0, 0.0, 0.0)
    };
    let tangent: Vec3 = up.cross(normal).normalize();
    let bitangent: Vec3 = normal.cross(tangent);
    tangent
        .scale(h_local.get_x())
        .add(bitangent.scale(h_local.get_y()))
        .add(normal.scale(h_local.get_z()))
        .normalize()
}

/// Evaluates the Smith GGX geometry shadowing-masking term `G(NdotV, NdotL)` for IBL integration.
///
/// # Arguments
///
/// - `f32` - Clamped `N·V`.
/// - `f32` - Clamped `N·L`.
/// - `f32` - Perceptual roughness.
///
/// # Returns
///
/// - `f32` - Smith geometry attenuation term.
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn geometry_smith_ibl(n_dot_v: f32, n_dot_l: f32, roughness: f32) -> f32 {
    let k: f32 = (roughness * roughness) * 0.5;
    let gv: f32 = n_dot_v / (n_dot_v * (1.0 - k) + k).max(1e-5);
    let gl: f32 = n_dot_l / (n_dot_l * (1.0 - k) + k).max(1e-5);
    gv * gl
}

/// Integrates the Split-Sum GGX BRDF lookup table `[scale, bias]` across `(N·V, roughness)`.
///
/// # Arguments
///
/// - `u32` - Square LUT dimension (`size x size`).
/// - `u32` - Hammersley Monte Carlo sample count per texel.
///
/// # Returns
///
/// - `Vec<[f32; 2]>` - Row-major `[scale, bias]` pairs (`len == size * size`).
#[must_use]
pub fn compute_brdf_lut(size: u32, samples: u32) -> Vec<[f32; 2]> {
    let dim: usize = size.max(4) as usize;
    let sample_count: u32 = samples.max(16);
    let mut lut: Vec<[f32; 2]> = Vec::with_capacity(dim * dim);
    let normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
    for row in 0..dim {
        let roughness: f32 = (((row as f32) + 0.5) / (dim as f32)).clamp(0.02, 1.0);
        for col in 0..dim {
            let n_dot_v: f32 = (((col as f32) + 0.5) / (dim as f32)).clamp(0.01, 1.0);
            let view: Vec3 = Vec3::new((1.0 - n_dot_v * n_dot_v).max(0.0).sqrt(), 0.0, n_dot_v);
            let mut sum_a: f32 = 0.0;
            let mut sum_b: f32 = 0.0;
            for idx in 0..sample_count {
                let xi: [f32; 2] = hammersley_2d(idx, sample_count);
                let half_v: Vec3 = importance_sample_ggx(xi, normal, roughness);
                let v_dot_h: f32 = view.dot(half_v).max(0.0);
                let light: Vec3 = half_v.scale(2.0 * v_dot_h).sub(view).normalize();
                let n_dot_l: f32 = light.get_z().max(0.0);
                let n_dot_h: f32 = half_v.get_z().max(0.0);
                if n_dot_l > 0.0 {
                    let g_val: f32 = geometry_smith_ibl(n_dot_v, n_dot_l, roughness);
                    let g_vis: f32 = (g_val * v_dot_h) / (n_dot_h * n_dot_v).max(1e-5);
                    let fc: f32 = (1.0 - v_dot_h).powi(5);
                    sum_a += (1.0 - fc) * g_vis;
                    sum_b += fc * g_vis;
                }
            }
            let inv_s: f32 = 1.0 / (sample_count as f32);
            lut.push([
                (sum_a * inv_s).clamp(0.0, 1.0),
                (sum_b * inv_s).clamp(0.0, 1.0),
            ]);
        }
    }
    lut
}

/// Evaluates Kulla-Conty multi-scattering energy compensation factor `1 + F0 * (1 / E_ss - 1)`.
///
/// # Arguments
///
/// - `Vec3` - Surface base Fresnel reflectance `F0`.
/// - `f32` - Single-scattering directional albedo `brdf_scale + brdf_bias`.
///
/// # Returns
///
/// - `Vec3` - Multi-scattering RGB boost factor (`>= 1.0`).
#[must_use]
pub fn kulla_conty_multiscatter_factor(f0: Vec3, single_scatter_albedo: f32) -> Vec3 {
    let inv_e: f32 = (1.0 / single_scatter_albedo.clamp(0.05, 1.0)) - 1.0;
    Vec3::new(
        1.0 + f0.get_x() * inv_e,
        1.0 + f0.get_y() * inv_e,
        1.0 + f0.get_z() * inv_e,
    )
}

/// Evaluates the 9 real L2 Spherical Harmonics basis functions for unit direction `dir`.
///
/// # Arguments
///
/// - `Vec3` - Unit direction vector.
///
/// # Returns
///
/// - `[f32; 9]` - L2 SH basis values `[Y00, Y1-1, Y10, Y11, Y2-2, Y2-1, Y20, Y21, Y22]`.
#[must_use]
pub fn eval_sh_l2_basis(dir: Vec3) -> [f32; 9] {
    let x: f32 = dir.get_x();
    let y: f32 = dir.get_y();
    let z: f32 = dir.get_z();
    [
        SH_C0,
        SH_C1 * y,
        SH_C1 * z,
        SH_C1 * x,
        SH_C2_0 * x * y,
        SH_C2_0 * y * z,
        SH_C2_1 * (3.0 * z * z - 1.0),
        SH_C2_0 * x * z,
        SH_C2_2 * (x * x - y * y),
    ]
}

/// Evaluates the 6th-order Blender AgX sigmoid contrast curve on normalized log2 channels `[0..1]`.
///
/// # Arguments
///
/// - `f32` - Normalized log2 input channel in `[0.0, 1.0]`.
///
/// # Returns
///
/// - `f32` - Sigmoid-mapped AgX channel in `[0.0, 1.0]`.
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn agx_default_contrast_approx(x: f32) -> f32 {
    let x2: f32 = x * x;
    let x4: f32 = x2 * x2;
    let poly: f32 =
        15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.429_8 * x2 + 0.119_1 * x
            - 0.002_32;
    poly.clamp(0.0, 1.0)
}

/// Applies Blender 4.0+/5.x **AgX** filmic view-transform tone mapping from linear HDR RGB to linear display RGB `[0..1]`.
///
/// # Arguments
///
/// - `Vec3` - Linear scene-referred HDR RGB radiance.
///
/// # Returns
///
/// - `Vec3` - Display-referred linear RGB color in `[0.0, 1.0]`.
#[must_use]
pub fn agx_tonemap(hdr: Vec3) -> Vec3 {
    let r: f32 = hdr.get_x().max(1e-6);
    let g: f32 = hdr.get_y().max(1e-6);
    let b: f32 = hdr.get_z().max(1e-6);
    let inset_r: f32 =
        AGX_INSET_MATRIX[0][0] * r + AGX_INSET_MATRIX[0][1] * g + AGX_INSET_MATRIX[0][2] * b;
    let inset_g: f32 =
        AGX_INSET_MATRIX[1][0] * r + AGX_INSET_MATRIX[1][1] * g + AGX_INSET_MATRIX[1][2] * b;
    let inset_b: f32 =
        AGX_INSET_MATRIX[2][0] * r + AGX_INSET_MATRIX[2][1] * g + AGX_INSET_MATRIX[2][2] * b;
    let ev_span: f32 = AGX_MAX_EV - AGX_MIN_EV;
    let cr: f32 = agx_default_contrast_approx(
        (inset_r.max(1e-6).log2().clamp(AGX_MIN_EV, AGX_MAX_EV) - AGX_MIN_EV) / ev_span,
    );
    let cg: f32 = agx_default_contrast_approx(
        (inset_g.max(1e-6).log2().clamp(AGX_MIN_EV, AGX_MAX_EV) - AGX_MIN_EV) / ev_span,
    );
    let cb: f32 = agx_default_contrast_approx(
        (inset_b.max(1e-6).log2().clamp(AGX_MIN_EV, AGX_MAX_EV) - AGX_MIN_EV) / ev_span,
    );
    let out_r: f32 =
        AGX_OUTSET_MATRIX[0][0] * cr + AGX_OUTSET_MATRIX[0][1] * cg + AGX_OUTSET_MATRIX[0][2] * cb;
    let out_g: f32 =
        AGX_OUTSET_MATRIX[1][0] * cr + AGX_OUTSET_MATRIX[1][1] * cg + AGX_OUTSET_MATRIX[1][2] * cb;
    let out_b: f32 =
        AGX_OUTSET_MATRIX[2][0] * cr + AGX_OUTSET_MATRIX[2][1] * cg + AGX_OUTSET_MATRIX[2][2] * cb;
    Vec3::new(
        out_r.clamp(0.0, 1.0).powf(2.2),
        out_g.clamp(0.0, 1.0).powf(2.2),
        out_b.clamp(0.0, 1.0).powf(2.2),
    )
}

/// Applies Narkowicz ACES Filmic tone mapping from linear HDR RGB to display linear RGB `[0..1]`.
///
/// # Arguments
///
/// - `Vec3` - Linear scene-referred HDR RGB radiance.
///
/// # Returns
///
/// - `Vec3` - Display-referred linear RGB color in `[0.0, 1.0]`.
#[must_use]
pub fn aces_filmic_tonemap(hdr: Vec3) -> Vec3 {
    let map_ch: fn(f32) -> f32 = |val: f32| -> f32 {
        let v: f32 = val.max(0.0);
        let num: f32 = v * (2.51 * v + 0.03);
        let den: f32 = v * (2.43 * v + 0.59) + 0.14;
        (num / den.max(1e-4)).clamp(0.0, 1.0)
    };
    Vec3::new(
        map_ch(hdr.get_x()),
        map_ch(hdr.get_y()),
        map_ch(hdr.get_z()),
    )
}

/// Samples an equirectangular HDR image in direction `dir` using bilinear interpolation.
///
/// # Arguments
///
/// - `&DecodedHdrImage` - Equirectangular linear HDR image.
/// - `Vec3` - Unit world-space lookup direction.
///
/// # Returns
///
/// - `Vec3` - Bilinearly filtered linear HDR RGB radiance.
#[must_use]
pub fn sample_equirectangular_hdr(hdr: &DecodedHdrImage, direction: Vec3) -> Vec3 {
    let w: usize = hdr.get_width().max(1) as usize;
    let h: usize = hdr.get_height().max(1) as usize;
    let px: &[f32] = hdr.get_pixels().as_slice();
    if px.len() < w * h * 4 {
        return Vec3::zero();
    }
    let dir: Vec3 = direction.normalize();
    let phi: f32 = dir.get_z().atan2(dir.get_x());
    let u: f32 = (phi / TAU + 0.5).rem_euclid(1.0);
    let v: f32 = (dir.get_y().clamp(-1.0, 1.0).acos() / PI).clamp(0.0, 1.0);
    let fx: f32 = u * (w as f32) - 0.5;
    let fy: f32 = (v * (h as f32) - 0.5).clamp(0.0, (h - 1) as f32);
    let x0: usize = (fx.floor() as isize).rem_euclid(w as isize) as usize;
    let x1: usize = (x0 + 1) % w;
    let y0: usize = fy.floor() as usize;
    let y1: usize = (y0 + 1).min(h - 1);
    let tx: f32 = fx - fx.floor();
    let ty: f32 = fy - (y0 as f32);
    let o00: usize = (y0 * w + x0) * 4;
    let o10: usize = (y0 * w + x1) * 4;
    let o01: usize = (y1 * w + x0) * 4;
    let o11: usize = (y1 * w + x1) * 4;
    let c00: Vec3 = Vec3::new(px[o00], px[o00 + 1], px[o00 + 2]);
    let c10: Vec3 = Vec3::new(px[o10], px[o10 + 1], px[o10 + 2]);
    let c01: Vec3 = Vec3::new(px[o01], px[o01 + 1], px[o01 + 2]);
    let c11: Vec3 = Vec3::new(px[o11], px[o11 + 1], px[o11 + 2]);
    let top: Vec3 = c00.lerp(c10, tx);
    let bot: Vec3 = c01.lerp(c11, tx);
    top.lerp(bot, ty)
}