use crate::RenderError;
const SH_C0: f32 = 0.282_094_8_f32;
const SH_C1: f32 = 0.488_602_52_f32;
const SH_C2: [f32; 5] = [
1.092_548_5_f32, -1.092_548_5_f32, 0.315_391_57_f32, -1.092_548_5_f32, 0.546_274_24_f32, ];
const SH_C3: [f32; 7] = [
-0.590_043_6_f32, 2.890_611_4_f32, -0.457_045_8_f32, 0.373_176_33_f32, -0.457_045_8_f32, 1.445_305_7_f32, -0.590_043_6_f32, ];
pub fn sh_basis_up_to_l2(direction: [f32; 3]) -> [f32; 9] {
let x = direction[0];
let y = direction[1];
let z = direction[2];
[
SH_C0,
-SH_C1 * y,
SH_C1 * z,
-SH_C1 * x,
SH_C2[0] * (x * y),
SH_C2[1] * (y * z),
SH_C2[2] * (3.0 * z * z - 1.0),
SH_C2[3] * (x * z),
SH_C2[4] * (x * x - y * y),
]
}
fn sh_basis_l3_extra(direction: [f32; 3]) -> [f32; 7] {
let x = direction[0];
let y = direction[1];
let z = direction[2];
let xx = x * x;
let yy = y * y;
let zz = z * z;
[
SH_C3[0] * y * (3.0 * xx - yy),
SH_C3[1] * x * y * z,
SH_C3[2] * y * (4.0 * zz - xx - yy),
SH_C3[3] * z * (2.0 * zz - 3.0 * xx - 3.0 * yy),
SH_C3[4] * x * (4.0 * zz - xx - yy),
SH_C3[5] * z * (xx - yy),
SH_C3[6] * x * (xx - 3.0 * yy),
]
}
pub fn sh_basis_up_to_l3(direction: [f32; 3]) -> [f32; 16] {
let l2 = sh_basis_up_to_l2(direction);
let l3 = sh_basis_l3_extra(direction);
[
l2[0], l2[1], l2[2], l2[3], l2[4], l2[5], l2[6], l2[7], l2[8], l3[0], l3[1], l3[2], l3[3],
l3[4], l3[5], l3[6],
]
}
#[derive(Debug, Clone, PartialEq)]
pub struct SphericalHarmonicsLight {
pub coeffs: [f32; 27],
pub max_degree: u32,
}
impl SphericalHarmonicsLight {
pub fn zeros() -> Self {
Self {
coeffs: [0.0_f32; 27],
max_degree: 2,
}
}
pub fn ambient(color: [f32; 3]) -> Self {
let mut s = Self::zeros();
s.max_degree = 0;
s.coeffs[0] = color[0];
s.coeffs[1] = color[1];
s.coeffs[2] = color[2];
s
}
pub fn evaluate(&self, direction: [f32; 3]) -> [f32; 3] {
let num_basis = match self.max_degree {
0 => 1_usize,
1 => 4_usize,
_ => 9_usize,
};
let basis = sh_basis_up_to_l2(direction);
let mut rgb = [0.0_f32; 3];
for (i, &basis_val) in basis.iter().enumerate().take(num_basis) {
for (c, rgb_val) in rgb.iter_mut().enumerate() {
*rgb_val += basis_val * self.coeffs[i * 3 + c];
}
}
[
rgb[0].clamp(0.0, 1.0),
rgb[1].clamp(0.0, 1.0),
rgb[2].clamp(0.0, 1.0),
]
}
pub fn add_ambient(&mut self, color: [f32; 3]) {
self.coeffs[0] += color[0];
self.coeffs[1] += color[1];
self.coeffs[2] += color[2];
}
pub fn scale(&mut self, factor: f32) {
for c in self.coeffs.iter_mut() {
*c *= factor;
}
}
}
#[derive(Debug, Clone)]
pub struct EnvironmentMap {
pub data: Vec<f32>,
pub width: usize,
pub height: usize,
}
impl EnvironmentMap {
pub fn new(width: usize, height: usize, data: Vec<f32>) -> Result<Self, RenderError> {
if width == 0 || height == 0 {
return Err(RenderError::ValidationError(format!(
"EnvironmentMap width and height must both be non-zero, got {width}Ć{height}"
)));
}
let expected = width * height * 3;
if data.len() != expected {
return Err(RenderError::MismatchedBufferSizes {
expected,
actual: data.len(),
});
}
Ok(Self {
data,
width,
height,
})
}
pub fn solid(color: [f32; 3]) -> Self {
Self {
data: vec![color[0], color[1], color[2]],
width: 1,
height: 1,
}
}
pub fn gradient_sky(zenith: [f32; 3], horizon: [f32; 3], nadir: [f32; 3]) -> Self {
const W: usize = 256;
const H: usize = 128;
let mut data = Vec::with_capacity(W * H * 3);
for py in 0..H {
let color = if py <= 64 {
let t = py as f32 / 64.0_f32;
lerp_rgb(zenith, horizon, t)
} else {
let t = (py - 64) as f32 / (127 - 64) as f32;
lerp_rgb(horizon, nadir, t)
};
for _px in 0..W {
data.push(color[0]);
data.push(color[1]);
data.push(color[2]);
}
}
Self {
data,
width: W,
height: H,
}
}
#[inline]
pub fn pixel(&self, px: usize, py: usize) -> [f32; 3] {
if px >= self.width || py >= self.height {
return [0.0, 0.0, 0.0];
}
let idx = (py * self.width + px) * 3;
match self.data.get(idx..idx + 3) {
Some(slice) => [slice[0], slice[1], slice[2]],
None => [0.0, 0.0, 0.0],
}
}
pub fn sample(&self, direction: [f32; 3]) -> [f32; 3] {
use std::f32::consts::PI;
let x = direction[0];
let y = direction[1];
let z = direction[2];
let theta = y.clamp(-1.0, 1.0).acos(); let phi = x.atan2(z);
let u = (phi + PI) / (2.0 * PI); let v = theta / PI;
let w = self.width as f32;
let h = self.height as f32;
let fx = u * w - 0.5;
let fy = v * h - 0.5;
let x0 = fx.floor() as i64;
let y0 = fy.floor() as i64;
let tx = fx - fx.floor();
let ty = fy - fy.floor();
let px0 = wrap_coord(x0, self.width as i64) as usize;
let px1 = wrap_coord(x0 + 1, self.width as i64) as usize;
let py0 = clamp_coord(y0, self.height as i64) as usize;
let py1 = clamp_coord(y0 + 1, self.height as i64) as usize;
let c00 = self.pixel(px0, py0);
let c10 = self.pixel(px1, py0);
let c01 = self.pixel(px0, py1);
let c11 = self.pixel(px1, py1);
let mut out = [0.0_f32; 3];
for c in 0..3 {
let top = c00[c] * (1.0 - tx) + c10[c] * tx;
let bot = c01[c] * (1.0 - tx) + c11[c] * tx;
out[c] = top * (1.0 - ty) + bot * ty;
}
out
}
}
#[inline]
fn lerp_rgb(a: [f32; 3], b: [f32; 3], t: f32) -> [f32; 3] {
[
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t,
a[2] + (b[2] - a[2]) * t,
]
}
#[inline]
fn wrap_coord(coord: i64, size: i64) -> i64 {
if size <= 0 {
return 0;
}
((coord % size) + size) % size
}
#[inline]
fn clamp_coord(coord: i64, size: i64) -> i64 {
if size <= 0 {
return 0;
}
coord.clamp(0, size - 1)
}
pub fn project_environment_to_sh(
env: &EnvironmentMap,
num_samples: usize,
) -> SphericalHarmonicsLight {
use std::f32::consts::PI;
let golden_ratio = (1.0_f32 + 5.0_f32.sqrt()) / 2.0_f32;
let n = num_samples as f32;
let weight = 4.0_f32 * PI / n;
let mut light = SphericalHarmonicsLight::zeros();
for i in 0..num_samples {
let fi = i as f32;
let theta = (1.0_f32 - 2.0_f32 * (fi + 0.5_f32) / n)
.clamp(-1.0, 1.0)
.acos();
let phi = 2.0_f32 * PI * fi / golden_ratio;
let sin_theta = theta.sin();
let direction = [sin_theta * phi.cos(), theta.cos(), sin_theta * phi.sin()];
let color = env.sample(direction);
let basis = sh_basis_up_to_l2(direction);
for (b, &basis_val) in basis.iter().enumerate() {
for (c, &color_val) in color.iter().enumerate() {
light.coeffs[b * 3 + c] += color_val * basis_val * weight;
}
}
}
light.max_degree = 2;
light
}
pub fn evaluate_gaussian_sh(sh_coeffs: &[f32], direction: [f32; 3]) -> [f32; 3] {
let num_basis = (sh_coeffs.len() / 3).min(16);
let basis = sh_basis_up_to_l3(direction);
let mut rgb = [0.5_f32; 3]; for i in 0..num_basis {
for c in 0..3 {
rgb[c] += basis[i] * sh_coeffs[i * 3 + c];
}
}
[
rgb[0].clamp(0.0, 1.0),
rgb[1].clamp(0.0, 1.0),
rgb[2].clamp(0.0, 1.0),
]
}
#[cfg(test)]
mod tests {
use super::*;
use std::f32::consts::PI;
const EPS: f32 = 1e-4;
fn approx_eq(a: f32, b: f32, tol: f32) -> bool {
(a - b).abs() <= tol
}
#[test]
fn test_sh_basis_l0_constant() {
let dirs = [
[1.0_f32, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[0.577_350_3, 0.577_350_3, 0.577_350_3],
];
for d in &dirs {
let b = sh_basis_up_to_l2(*d);
assert!(
approx_eq(b[0], SH_C0, EPS),
"Y_0_0 = {} != {} for dir {:?}",
b[0],
SH_C0,
d
);
}
}
#[test]
fn test_sh_basis_l1_x_direction() {
let b = sh_basis_up_to_l2([1.0, 0.0, 0.0]);
assert!(
approx_eq(b[3], -SH_C1, EPS),
"Y_1_1 should be -SH_C1 for [1,0,0], got {}",
b[3]
);
assert!(approx_eq(b[1], 0.0, EPS), "Y_1_-1 != 0 for [1,0,0]");
assert!(approx_eq(b[2], 0.0, EPS), "Y_1_0 != 0 for [1,0,0]");
}
#[test]
fn test_sh_basis_l1_y_direction_matches_3dgs_sign_convention() {
let b = sh_basis_up_to_l2([0.0, 1.0, 0.0]);
assert!(
approx_eq(b[1], -SH_C1, EPS),
"Y_1_-1 should be -SH_C1 for [0,1,0], got {}",
b[1]
);
}
#[test]
fn test_sh_basis_l2_m_minus1_and_plus1_signs_match_3dgs() {
let d = [1.0_f32 / 3.0_f32.sqrt(); 3]; let b = sh_basis_up_to_l2(d);
assert!(b[5] < 0.0, "Y_2_-1 should be negative, got {}", b[5]);
assert!(b[7] < 0.0, "Y_2_1 should be negative, got {}", b[7]);
}
#[test]
fn test_sh_basis_l2_shape() {
let b = sh_basis_up_to_l2([1.0, 0.0, 0.0]);
assert!(approx_eq(b[4], 0.0, EPS));
assert!(approx_eq(b[5], 0.0, EPS));
let expected_y20 = SH_C2[2] * (3.0 * 0.0 - 1.0);
assert!(approx_eq(b[6], expected_y20, EPS));
assert!(approx_eq(b[7], 0.0, EPS));
assert!(approx_eq(b[8], SH_C2[4], EPS));
}
#[test]
fn test_sh_basis_normalization_property() {
let num_samples = 100_000_usize;
let golden_ratio = (1.0_f32 + 5.0_f32.sqrt()) / 2.0_f32;
let n = num_samples as f32;
let mut sum = 0.0_f32;
for i in 0..num_samples {
let fi = i as f32;
let theta = (1.0_f32 - 2.0_f32 * (fi + 0.5_f32) / n)
.clamp(-1.0, 1.0)
.acos();
let phi = 2.0_f32 * PI * fi / golden_ratio;
let direction = [
theta.sin() * phi.cos(),
theta.cos(),
theta.sin() * phi.sin(),
];
let b = sh_basis_up_to_l2(direction);
sum += b[0] * b[0]; }
let integral = sum * (4.0_f32 * PI / n);
assert!(
approx_eq(integral, 1.0, 0.01),
"ā« Y_0_0² dĪ© ā {} (expected 1.0)",
integral
);
}
#[test]
fn test_sh_light_zeros() {
let s = SphericalHarmonicsLight::zeros();
for c in &s.coeffs {
assert_eq!(*c, 0.0_f32);
}
assert_eq!(s.max_degree, 2);
}
#[test]
fn test_sh_light_ambient() {
let color = [0.3_f32, 0.5_f32, 0.7_f32];
let s = SphericalHarmonicsLight::ambient(color);
assert_eq!(s.max_degree, 0);
assert!(approx_eq(s.coeffs[0], color[0], EPS));
assert!(approx_eq(s.coeffs[1], color[1], EPS));
assert!(approx_eq(s.coeffs[2], color[2], EPS));
for i in 3..27 {
assert_eq!(s.coeffs[i], 0.0_f32);
}
}
#[test]
fn test_sh_light_evaluate_ambient() {
let raw_intensity = 1.5_f32; let s = SphericalHarmonicsLight::ambient([raw_intensity, 0.4, 0.2]);
let result = s.evaluate([1.0, 0.0, 0.0]);
let expected_r = (raw_intensity * SH_C0).clamp(0.0, 1.0);
let expected_g = (0.4_f32 * SH_C0).clamp(0.0, 1.0);
let expected_b = (0.2_f32 * SH_C0).clamp(0.0, 1.0);
assert!(approx_eq(result[0], expected_r, EPS));
assert!(approx_eq(result[1], expected_g, EPS));
assert!(approx_eq(result[2], expected_b, EPS));
}
#[test]
fn test_sh_light_add_ambient() {
let mut s = SphericalHarmonicsLight::zeros();
s.add_ambient([0.1, 0.2, 0.3]);
s.add_ambient([0.4, 0.5, 0.6]);
assert!(approx_eq(s.coeffs[0], 0.5, EPS));
assert!(approx_eq(s.coeffs[1], 0.7, EPS));
assert!(approx_eq(s.coeffs[2], 0.9, EPS));
}
#[test]
fn test_sh_light_scale() {
let mut s = SphericalHarmonicsLight::zeros();
s.coeffs[0] = 2.0;
s.coeffs[5] = 3.0;
s.scale(0.5);
assert!(approx_eq(s.coeffs[0], 1.0, EPS));
assert!(approx_eq(s.coeffs[5], 1.5, EPS));
}
#[test]
fn test_environment_map_new_valid() {
let data = vec![0.0_f32; 4 * 2 * 3];
let env = EnvironmentMap::new(4, 2, data).expect("should succeed");
assert_eq!(env.width, 4);
assert_eq!(env.height, 2);
}
#[test]
fn test_environment_map_invalid_size() {
let data = vec![0.0_f32; 5]; let result = EnvironmentMap::new(4, 2, data);
assert!(result.is_err());
}
#[test]
fn test_environment_map_new_rejects_zero_dimensions() {
assert!(EnvironmentMap::new(0, 0, vec![]).is_err());
assert!(EnvironmentMap::new(0, 5, vec![]).is_err());
assert!(EnvironmentMap::new(5, 0, vec![]).is_err());
}
#[test]
fn test_environment_map_pixel_out_of_bounds_does_not_panic() {
let env = EnvironmentMap::solid([0.5, 0.5, 0.5]);
assert_eq!(env.pixel(5, 5), [0.0, 0.0, 0.0]);
assert_eq!(env.pixel(1, 0), [0.0, 0.0, 0.0]);
assert_eq!(env.pixel(0, 1), [0.0, 0.0, 0.0]);
}
#[test]
fn test_environment_map_sample_on_degenerate_map_does_not_panic() {
let env = EnvironmentMap {
data: vec![],
width: 0,
height: 0,
};
let result = env.sample([0.0, 1.0, 0.0]);
assert_eq!(result, [0.0, 0.0, 0.0]);
}
#[test]
fn test_environment_map_solid_sample() {
let color = [0.6_f32, 0.3_f32, 0.9_f32];
let env = EnvironmentMap::solid(color);
let dirs = [[1.0_f32, 0.0, 0.0], [0.0, 1.0, 0.0], [-0.707, 0.0, 0.707]];
for d in &dirs {
let s = env.sample(*d);
for c in 0..3 {
assert!(
approx_eq(s[c], color[c], EPS),
"channel {c}: got {}, expected {}",
s[c],
color[c]
);
}
}
}
#[test]
fn test_environment_map_gradient_sky() {
let zenith = [0.0_f32, 0.0_f32, 1.0_f32];
let horizon = [0.5_f32, 0.5_f32, 0.5_f32];
let nadir = [1.0_f32, 0.0_f32, 0.0_f32];
let env = EnvironmentMap::gradient_sky(zenith, horizon, nadir);
assert_eq!(env.width, 256);
assert_eq!(env.height, 128);
assert_eq!(env.data.len(), 256 * 128 * 3);
let top = env.pixel(0, 0);
for c in 0..3 {
assert!(approx_eq(top[c], zenith[c], EPS), "zenith mismatch");
}
let mid = env.pixel(0, 64);
for c in 0..3 {
assert!(approx_eq(mid[c], horizon[c], EPS), "horizon mismatch");
}
let bot = env.pixel(0, 127);
for c in 0..3 {
assert!(approx_eq(bot[c], nadir[c], EPS), "nadir mismatch");
}
}
#[test]
fn test_environment_map_sample_top_direction() {
let zenith = [0.1_f32, 0.5_f32, 0.9_f32];
let horizon = [0.5_f32, 0.5_f32, 0.5_f32];
let nadir = [0.9_f32, 0.5_f32, 0.1_f32];
let env = EnvironmentMap::gradient_sky(zenith, horizon, nadir);
let s = env.sample([0.0, 1.0, 0.0]);
for c in 0..3 {
assert!(
approx_eq(s[c], zenith[c], 0.05),
"channel {c}: got {}, expected zenith {}",
s[c],
zenith[c]
);
}
}
#[test]
fn test_project_to_sh_ambient_env() {
let color = [0.8_f32, 0.6_f32, 0.4_f32];
let env = EnvironmentMap::solid(color);
let sh = project_environment_to_sh(&env, 1000);
let evaluated = sh.evaluate([0.0, 1.0, 0.0]);
for c in 0..3 {
assert!(
approx_eq(evaluated[c], color[c].clamp(0.0, 1.0), 0.05),
"channel {c}: got {}, expected {}",
evaluated[c],
color[c]
);
}
}
#[test]
fn test_project_to_sh_preserves_color() {
let env = EnvironmentMap::solid([1.0, 1.0, 1.0]);
let sh = project_environment_to_sh(&env, 2000);
let dirs = [
[1.0_f32, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[-1.0, 0.0, 0.0],
[0.0, -1.0, 0.0],
];
for d in &dirs {
let result = sh.evaluate(*d);
for (c, &val) in result.iter().enumerate() {
assert!(
val > 0.7,
"direction {:?} channel {c}: value {} too low",
d,
val
);
}
}
}
#[test]
fn test_evaluate_gaussian_sh_degree_0() {
let r = 0.2_f32;
let g = -0.3_f32; let b = 0.4_f32;
let coeffs = [r, g, b];
let result = evaluate_gaussian_sh(&coeffs, [1.0, 0.0, 0.0]);
let expected_r = (0.5 + r * SH_C0).clamp(0.0, 1.0);
let expected_g = (0.5 + g * SH_C0).clamp(0.0, 1.0);
let expected_b = (0.5 + b * SH_C0).clamp(0.0, 1.0);
assert!(approx_eq(result[0], expected_r, EPS));
assert!(approx_eq(result[1], expected_g, EPS));
assert!(approx_eq(result[2], expected_b, EPS));
}
#[test]
fn test_evaluate_gaussian_sh_degree_1() {
let mut coeffs = [0.0_f32; 12];
coeffs[0] = 0.5;
coeffs[1] = 0.5;
coeffs[2] = 0.5;
coeffs[9] = 1.0; coeffs[10] = 0.0;
coeffs[11] = 0.0;
let direction = [1.0_f32, 0.0, 0.0]; let result = evaluate_gaussian_sh(&coeffs, direction);
let basis = sh_basis_up_to_l2(direction);
let expected_r = (0.5 + 0.5 * basis[0] + 1.0 * basis[3]).clamp(0.0, 1.0);
assert!(
approx_eq(result[0], expected_r, EPS),
"R: got {}, expected {}",
result[0],
expected_r
);
}
#[test]
fn test_evaluate_gaussian_sh_degree_3_does_not_panic() {
let mut coeffs = [0.0_f32; 48];
for (i, c) in coeffs.iter_mut().enumerate() {
*c = (i as f32) * 0.001;
}
let direction = [0.577_350_3_f32, 0.577_350_3_f32, 0.577_350_3_f32]; let result = evaluate_gaussian_sh(&coeffs, direction);
for &v in &result {
assert!((0.0..=1.0).contains(&v), "result channel out of [0,1]: {v}");
}
}
#[test]
fn test_evaluate_gaussian_sh_degree_3_uses_l3_basis() {
let mut coeffs = [0.0_f32; 48];
coeffs[27] = 1.0; let direction = [0.577_350_3_f32, 0.577_350_3_f32, 0.577_350_3_f32];
let result = evaluate_gaussian_sh(&coeffs, direction);
let basis = sh_basis_up_to_l3(direction);
let expected_r = (0.5 + basis[9]).clamp(0.0, 1.0);
assert!(
approx_eq(result[0], expected_r, EPS),
"expected the degree-3 coefficient to contribute: got {}, expected {}",
result[0],
expected_r
);
}
#[test]
fn test_sh_basis_l3_matches_shader_reference() {
let d = [1.0_f32, 0.0, 0.0];
let b = sh_basis_up_to_l3(d);
assert!(approx_eq(b[9], 0.0, EPS));
assert!(approx_eq(b[15], SH_C3[6], EPS));
}
#[test]
fn test_fibonacci_sphere_coverage() {
let num_samples = 500_usize;
let golden_ratio = (1.0_f32 + 5.0_f32.sqrt()) / 2.0_f32;
let n = num_samples as f32;
for i in 0..num_samples {
let fi = i as f32;
let theta = (1.0_f32 - 2.0_f32 * (fi + 0.5_f32) / n)
.clamp(-1.0, 1.0)
.acos();
let phi = 2.0_f32 * PI * fi / golden_ratio;
let direction = [
theta.sin() * phi.cos(),
theta.cos(),
theta.sin() * phi.sin(),
];
let norm_sq = direction[0] * direction[0]
+ direction[1] * direction[1]
+ direction[2] * direction[2];
assert!(
approx_eq(norm_sq, 1.0, 1e-5),
"sample {i}: norm² = {norm_sq}, direction = {direction:?}"
);
}
let ys: Vec<f32> = (0..num_samples)
.map(|i| {
let fi = i as f32;
let theta = (1.0_f32 - 2.0_f32 * (fi + 0.5_f32) / n)
.clamp(-1.0, 1.0)
.acos();
theta.cos()
})
.collect();
let y_min = ys.iter().cloned().fold(f32::INFINITY, f32::min);
let y_max = ys.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
assert!(y_min < -0.9, "y_min {} not near -1", y_min);
assert!(y_max > 0.9, "y_max {} not near +1", y_max);
}
}