use thiserror::Error;
fn xorshift64(state: &mut u64) -> u64 {
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
if *state == 0 {
*state = 1;
}
*state
}
fn xorshift_f32(state: &mut u64) -> f32 {
xorshift64(state) as f32 / u64::MAX as f32
}
#[derive(Debug, Error)]
pub enum AoError {
#[error("dimension mismatch: width*height={expected}, buffer len={got}")]
DimensionMismatch {
expected: usize,
got: usize,
},
#[error("invalid radius: must be > 0, got {0}")]
InvalidRadius(f32),
#[error("invalid config: {0}")]
InvalidConfig(String),
#[error("empty input")]
EmptyInput,
#[error("invalid kernel size: must be > 0, got {0}")]
InvalidKernelSize(usize),
}
#[derive(Debug, Clone)]
pub struct AoConfig {
pub n_samples: usize,
pub radius: f32,
pub bias: f32,
pub power: f32,
pub blur_radius: usize,
pub blur_sigma_space: f32,
pub blur_sigma_depth: f32,
pub strength: f32,
}
impl Default for AoConfig {
fn default() -> Self {
Self {
n_samples: 16,
radius: 0.5,
bias: 0.025,
power: 1.0,
blur_radius: 2,
blur_sigma_space: 2.0,
blur_sigma_depth: 0.1,
strength: 1.0,
}
}
}
#[derive(Debug, Clone)]
pub struct AoStats {
pub mean_ao: f32,
pub min_ao: f32,
pub max_ao: f32,
pub occlusion_fraction: f32,
pub background_fraction: f32,
}
#[derive(Debug, Clone)]
pub struct SsaoResult {
pub image: Vec<f32>,
pub ao_map: Vec<f32>,
pub ao_map_blurred: Vec<f32>,
pub stats: AoStats,
}
#[derive(Debug, Clone, Copy)]
pub struct AoProjParams {
pub focal_px_x: f32,
pub focal_px_y: f32,
}
impl AoProjParams {
pub fn new(focal_px_x: f32, focal_px_y: f32) -> Self {
Self {
focal_px_x,
focal_px_y,
}
}
pub fn from_fov(fov_x: f32, fov_y: f32, width: f32, height: f32) -> Self {
let focal_px_x = width / (2.0 * (fov_x * 0.5).tan());
let focal_px_y = height / (2.0 * (fov_y * 0.5).tan());
Self {
focal_px_x,
focal_px_y,
}
}
}
pub struct AoSamplingBuffers<'a> {
pub kernel: &'a [f32],
pub noise: &'a [f32],
}
#[inline]
pub fn ao_dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
#[inline]
pub fn ao_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
#[inline]
pub fn ao_normalize(v: [f32; 3]) -> [f32; 3] {
let len2 = ao_dot(v, v);
if len2 < 1e-12 {
return [0.0, 0.0, 1.0];
}
let inv = 1.0 / len2.sqrt();
[v[0] * inv, v[1] * inv, v[2] * inv]
}
#[inline]
pub fn ao_smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
if edge1 <= edge0 {
return if x >= edge1 { 1.0 } else { 0.0 };
}
let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
pub fn ao_sample_depth(depth_buf: &[f32], width: usize, height: usize, x: f32, y: f32) -> f32 {
if width == 0 || height == 0 || depth_buf.is_empty() {
return 0.0;
}
let x_clamped = x.clamp(0.0, (width as f32) - 1.0);
let y_clamped = y.clamp(0.0, (height as f32) - 1.0);
let x0 = x_clamped.floor() as usize;
let y0 = y_clamped.floor() as usize;
let x1 = (x0 + 1).min(width - 1);
let y1 = (y0 + 1).min(height - 1);
let fx = x_clamped - x0 as f32;
let fy = y_clamped - y0 as f32;
let d00 = depth_buf[y0 * width + x0];
let d10 = depth_buf[y0 * width + x1];
let d01 = depth_buf[y1 * width + x0];
let d11 = depth_buf[y1 * width + x1];
let d0 = d00 + fx * (d10 - d00);
let d1 = d01 + fx * (d11 - d01);
d0 + fy * (d1 - d0)
}
pub fn ao_sample_kernel(n_samples: usize) -> Result<Vec<f32>, AoError> {
if n_samples == 0 {
return Err(AoError::InvalidConfig("n_samples must be > 0".to_string()));
}
let mut state = n_samples as u64;
if state == 0 {
state = 1;
}
let mut kernel = Vec::with_capacity(n_samples * 3);
let two_pi = 2.0 * core::f32::consts::PI;
for i in 0..n_samples {
let theta = xorshift_f32(&mut state) * two_pi;
let u = xorshift_f32(&mut state);
let sin_phi = u.max(0.0).sqrt();
let cos_phi = (1.0 - u).max(0.0).sqrt();
let x = sin_phi * theta.cos();
let y = sin_phi * theta.sin();
let z = cos_phi;
let t = i as f32 / n_samples.max(1) as f32;
let scale = 0.1 + (t * t) * 0.9;
let random_factor = xorshift_f32(&mut state);
kernel.push(x * scale * random_factor);
kernel.push(y * scale * random_factor);
kernel.push(z * scale * random_factor);
}
Ok(kernel)
}
pub fn ao_noise_texture() -> Vec<f32> {
let mut state = 12345u64;
let mut noise = Vec::with_capacity(32);
for _ in 0..16 {
let nx = xorshift_f32(&mut state) * 2.0 - 1.0;
let ny = xorshift_f32(&mut state) * 2.0 - 1.0;
noise.push(nx);
noise.push(ny);
}
noise
}
pub fn ao_compute(
depth_buf: &[f32],
normal_buf: &[f32],
width: usize,
height: usize,
sampling: AoSamplingBuffers<'_>,
proj: AoProjParams,
config: &AoConfig,
) -> Result<Vec<f32>, AoError> {
let kernel = sampling.kernel;
let noise = sampling.noise;
if depth_buf.is_empty() {
return Err(AoError::EmptyInput);
}
if config.radius <= 0.0 {
return Err(AoError::InvalidRadius(config.radius));
}
if kernel.is_empty() || !kernel.len().is_multiple_of(3) {
return Err(AoError::InvalidConfig(format!(
"kernel must be a non-empty multiple of 3 (x, y, z triplets), got {}",
kernel.len()
)));
}
if noise.len() < 32 || !noise.len().is_multiple_of(2) {
return Err(AoError::InvalidConfig(format!(
"noise texture must have an even length >= 32, got {}",
noise.len()
)));
}
let num_pixels = width * height;
if depth_buf.len() != num_pixels {
return Err(AoError::DimensionMismatch {
expected: num_pixels,
got: depth_buf.len(),
});
}
let expected_normal_len = num_pixels * 3;
if normal_buf.len() != expected_normal_len {
return Err(AoError::DimensionMismatch {
expected: expected_normal_len,
got: normal_buf.len(),
});
}
let n_samples = kernel.len() / 3;
let radius = config.radius;
let bias = config.bias;
let power = config.power;
let mut ao_buf = Vec::with_capacity(num_pixels);
for py in 0..height {
for px in 0..width {
let pixel_idx = py * width + px;
let depth = depth_buf[pixel_idx];
if depth == 0.0 || !depth.is_finite() {
ao_buf.push(1.0_f32);
continue;
}
let nx = normal_buf[pixel_idx * 3];
let ny = normal_buf[pixel_idx * 3 + 1];
let nz = normal_buf[pixel_idx * 3 + 2];
let normal = ao_normalize([nx, ny, nz]);
let noise_idx = (py % 4) * 4 + (px % 4);
let noise_x = noise[(noise_idx * 2) % noise.len()];
let noise_y = noise[(noise_idx * 2 + 1) % noise.len()];
let noise_vec = [noise_x, noise_y, 0.0];
let dot_n_noise = ao_dot(normal, noise_vec);
let tangent_raw = [
noise_vec[0] - dot_n_noise * normal[0],
noise_vec[1] - dot_n_noise * normal[1],
noise_vec[2] - dot_n_noise * normal[2],
];
let tangent = ao_normalize(tangent_raw);
let bitangent = ao_cross(normal, tangent);
let mut occlusion_sum = 0.0_f32;
for s in 0..n_samples {
let kx = kernel[s * 3];
let ky = kernel[s * 3 + 1];
let kz = kernel[s * 3 + 2];
let vx = tangent[0] * kx + bitangent[0] * ky + normal[0] * kz;
let vy = tangent[1] * kx + bitangent[1] * ky + normal[1] * kz;
let vz = tangent[2] * kx + bitangent[2] * ky + normal[2] * kz;
let ox = vx * radius;
let oy = vy * radius;
let oz = vz * radius;
let denom = (depth + oz).max(1e-6);
let sx = px as f32 + ox * proj.focal_px_x / denom;
let sy = py as f32 + oy * proj.focal_px_y / denom;
let sx_clamped = sx.clamp(0.0, (width as f32) - 1.0);
let sy_clamped = sy.clamp(0.0, (height as f32) - 1.0);
let sampled_depth =
ao_sample_depth(depth_buf, width, height, sx_clamped, sy_clamped);
if sampled_depth == 0.0 || !sampled_depth.is_finite() {
continue;
}
let depth_diff = (depth - sampled_depth).abs();
let range_check = ao_smoothstep(0.0, 1.0, radius / (depth_diff + 1e-6));
let occluded = if sampled_depth <= (depth + oz - bias) {
1.0_f32
} else {
0.0_f32
};
occlusion_sum += occluded * range_check;
}
let n_samples_f = n_samples.max(1) as f32;
let ao = (1.0 - occlusion_sum / n_samples_f).powf(power);
ao_buf.push(ao.clamp(0.0, 1.0));
}
}
Ok(ao_buf)
}
pub fn ao_bilateral_blur(
ao_buf: &[f32],
depth_buf: &[f32],
width: usize,
height: usize,
config: &AoConfig,
) -> Result<Vec<f32>, AoError> {
if ao_buf.is_empty() {
return Err(AoError::EmptyInput);
}
let num_pixels = width * height;
if ao_buf.len() != num_pixels {
return Err(AoError::DimensionMismatch {
expected: num_pixels,
got: ao_buf.len(),
});
}
if depth_buf.len() != num_pixels {
return Err(AoError::DimensionMismatch {
expected: num_pixels,
got: depth_buf.len(),
});
}
let r = config.blur_radius as isize;
let sigma_space = config.blur_sigma_space.max(1e-6);
let sigma_depth = config.blur_sigma_depth.max(1e-6);
let inv_2sigma_space2 = 1.0 / (2.0 * sigma_space * sigma_space);
let inv_2sigma_depth2 = 1.0 / (2.0 * sigma_depth * sigma_depth);
let mut out = Vec::with_capacity(num_pixels);
for py in 0..height {
for px in 0..width {
let center_idx = py * width + px;
let center_depth = depth_buf[center_idx];
if center_depth == 0.0 || !center_depth.is_finite() {
out.push(ao_buf[center_idx]);
continue;
}
let mut weighted_sum = 0.0_f32;
let mut weight_total = 0.0_f32;
for dy in -r..=r {
for dx in -r..=r {
let nx = (px as isize + dx).clamp(0, width as isize - 1) as usize;
let ny = (py as isize + dy).clamp(0, height as isize - 1) as usize;
let nb_idx = ny * width + nx;
let nb_depth = depth_buf[nb_idx];
let nb_ao = ao_buf[nb_idx];
let dist2 = (dx * dx + dy * dy) as f32;
let w_space = (-dist2 * inv_2sigma_space2).exp();
let depth_diff = center_depth - nb_depth;
let w_depth = (-(depth_diff * depth_diff) * inv_2sigma_depth2).exp();
let w = w_space * w_depth;
weighted_sum += nb_ao * w;
weight_total += w;
}
}
let blurred = if weight_total > 1e-10 {
weighted_sum / weight_total
} else {
ao_buf[center_idx]
};
out.push(blurred.clamp(0.0, 1.0));
}
}
Ok(out)
}
pub fn ao_apply_to_image(
image: &[f32],
ao_buf: &[f32],
width: usize,
height: usize,
strength: f32,
) -> Result<Vec<f32>, AoError> {
if image.is_empty() {
return Err(AoError::EmptyInput);
}
let num_pixels = width * height;
let expected_image_len = num_pixels * 3;
if ao_buf.len() != num_pixels {
return Err(AoError::DimensionMismatch {
expected: num_pixels,
got: ao_buf.len(),
});
}
if image.len() != expected_image_len {
return Err(AoError::DimensionMismatch {
expected: expected_image_len,
got: image.len(),
});
}
let s = strength.clamp(0.0, 1.0);
let mut out = Vec::with_capacity(image.len());
for pixel_idx in 0..num_pixels {
let ao = ao_buf[pixel_idx];
let scale = 1.0 + s * (ao - 1.0);
let r = image[pixel_idx * 3];
let g = image[pixel_idx * 3 + 1];
let b = image[pixel_idx * 3 + 2];
out.push((r * scale).clamp(0.0, 1.0));
out.push((g * scale).clamp(0.0, 1.0));
out.push((b * scale).clamp(0.0, 1.0));
}
Ok(out)
}
pub fn ao_compute_stats(ao_buf: &[f32], depth_buf: &[f32]) -> AoStats {
if ao_buf.is_empty() {
return AoStats {
mean_ao: 1.0,
min_ao: 1.0,
max_ao: 1.0,
occlusion_fraction: 0.0,
background_fraction: 0.0,
};
}
let n = ao_buf.len();
let depth_len = depth_buf.len().min(n);
let mut sum = 0.0_f32;
let mut min_ao = f32::MAX;
let mut max_ao = f32::MIN;
let mut occluded_count = 0usize;
let mut background_count = 0usize;
let mut foreground_count = 0usize;
for i in 0..n {
let ao = ao_buf[i];
let depth = if i < depth_len { depth_buf[i] } else { 1.0 };
let is_bg = depth == 0.0 || !depth.is_finite();
if is_bg {
background_count += 1;
} else {
foreground_count += 1;
sum += ao;
if ao < min_ao {
min_ao = ao;
}
if ao > max_ao {
max_ao = ao;
}
if ao < 0.9 {
occluded_count += 1;
}
}
}
let (mean, min, max) = if foreground_count == 0 {
(1.0, 1.0, 1.0)
} else {
(sum / foreground_count as f32, min_ao, max_ao)
};
AoStats {
mean_ao: mean,
min_ao: min,
max_ao: max,
occlusion_fraction: if foreground_count == 0 {
0.0
} else {
occluded_count as f32 / foreground_count as f32
},
background_fraction: background_count as f32 / n as f32,
}
}
pub fn format_ao_config(config: &AoConfig) -> String {
format!(
"AoConfig {{ n_samples={}, radius={:.3}, bias={:.4}, power={:.2}, \
blur_radius={}, blur_sigma_space={:.2}, blur_sigma_depth={:.3}, strength={:.2} }}",
config.n_samples,
config.radius,
config.bias,
config.power,
config.blur_radius,
config.blur_sigma_space,
config.blur_sigma_depth,
config.strength,
)
}
pub fn format_ao_stats(stats: &AoStats) -> String {
format!(
"AoStats {{ mean={:.3}, min={:.3}, max={:.3}, \
occlusion={:.1}%, background={:.1}% }}",
stats.mean_ao,
stats.min_ao,
stats.max_ao,
stats.occlusion_fraction * 100.0,
stats.background_fraction * 100.0,
)
}
pub fn apply_ssao(
image: &[f32],
depth_buf: &[f32],
normal_buf: &[f32],
width: usize,
height: usize,
proj: AoProjParams,
config: &AoConfig,
) -> Result<SsaoResult, AoError> {
let kernel = ao_sample_kernel(config.n_samples)?;
let noise = ao_noise_texture();
let ao_map = ao_compute(
depth_buf,
normal_buf,
width,
height,
AoSamplingBuffers {
kernel: &kernel,
noise: &noise,
},
proj,
config,
)?;
let ao_map_blurred = ao_bilateral_blur(&ao_map, depth_buf, width, height, config)?;
let output_image = ao_apply_to_image(image, &ao_map_blurred, width, height, config.strength)?;
let stats = ao_compute_stats(&ao_map_blurred, depth_buf);
Ok(SsaoResult {
image: output_image,
ao_map,
ao_map_blurred,
stats,
})
}
#[cfg(test)]
mod tests;