use super::temporal_neighborhood_tests::{
SIZE, depth, depth_values, device, half, read_rgba16f, texels, texture,
};
use super::*;
use crate::{CameraAttribs, post_fx_context::FrameDesc};
const NEAR: f32 = 0.1;
fn projection_scales() -> (f32, f32) {
let aspect = SIZE[0] as f32 / SIZE[1] as f32;
(1.0 / 0.5f32.tan() / aspect, 1.0 / 0.5f32.tan())
}
fn infinite_reversed_camera() -> CameraAttribs {
let (a, b) = projection_scales();
let proj = [
a, 0., 0., 0., 0., b, 0., 0., 0., 0., 0., 1., 0., 0., NEAR, 0.,
];
let proj_inv = [
1. / a,
0.,
0.,
0.,
0.,
1. / b,
0.,
0.,
0.,
0.,
0.,
1. / NEAR,
0.,
0.,
1.,
0.,
];
let identity = [
1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.,
];
let mut camera = CameraAttribs {
f4_viewport_size: [
SIZE[0] as f32,
SIZE[1] as f32,
1.0 / SIZE[0] as f32,
1.0 / SIZE[1] as f32,
],
m_view: identity,
m_proj: proj,
m_view_proj: proj,
m_view_inv: identity,
m_proj_inv: proj_inv,
m_view_proj_inv: proj_inv,
..Default::default()
};
camera.set_clip_planes(f32::INFINITY, NEAR);
camera
}
fn pixel_ray(x: u32, y: u32) -> [f64; 3] {
let (a, b) = projection_scales();
let [width, height] = SIZE.map(f64::from);
[
((f64::from(x) + 0.5) / width * 2.0 - 1.0) / f64::from(a),
(1.0 - (f64::from(y) + 0.5) / height * 2.0) / f64::from(b),
1.0,
]
}
fn floor_depths(floor_normal: [f64; 3]) -> Vec<f32> {
(0..SIZE[1])
.flat_map(|y| (0..SIZE[0]).map(move |x| (x, y)))
.map(|(x, y)| {
let ray = pixel_ray(x, y);
let towards_floor: f64 = (0..3).map(|i| ray[i] * floor_normal[i]).sum();
if towards_floor < 0.0 {
(f64::from(NEAR) * -towards_floor) as f32
} else {
0.0
}
})
.collect()
}
fn trace_mirror_floor(
device: &wgpu::Device,
queue: &wgpu::Queue,
floor_normal: [f64; 3],
feature_flags: FeatureFlags,
roughness: u8,
zero_normal: fn(u32, u32) -> bool,
) -> ScreenSpaceReflection {
let camera = infinite_reversed_camera();
let mut encoder = device.create_command_encoder(&Default::default());
let scene_depth = depth_values(device, queue, &mut encoder, &floor_depths(floor_normal));
let previous_depth = depth(device, &mut encoder, 0.0);
let floor_normal = floor_normal.map(|v| v as f32);
let normals: Vec<u8> = (0..SIZE[1])
.flat_map(|y| (0..SIZE[0]).map(move |x| (x, y)))
.flat_map(|(x, y)| {
let [nx, ny, nz] = if zero_normal(x, y) {
[0.0; 3]
} else {
floor_normal
};
half(&[nx, ny, nz, 0.0])
})
.collect();
let normal = texels(device, queue, wgpu::TextureFormat::Rgba16Float, &normals);
let material = texture(device, queue, wgpu::TextureFormat::R8Unorm, &[roughness]);
let color = texture(
device,
queue,
wgpu::TextureFormat::Rgba16Float,
&half(&[1.0, 1.0, 1.0, 1.0]),
);
let motion = texels(
device,
queue,
wgpu::TextureFormat::Rg16Float,
&vec![0; 4 * (SIZE[0] * SIZE[1]) as usize],
);
let mut context = PostFXContext::new(
device,
queue,
post_fx_context::CreateInfo {
transition_duration: 0.0,
},
);
let mut ssr = ScreenSpaceReflection::new(device);
context.prepare_resources(
device,
&FrameDesc {
index: 0,
width: SIZE[0],
height: SIZE[1],
output_width: SIZE[0],
output_height: SIZE[1],
},
post_fx_context::FeatureFlags::REVERSED_DEPTH,
);
ssr.prepare_resources(device, &mut encoder, &mut context, feature_flags);
context.execute(&mut post_fx_context::RenderAttributes {
device,
queue,
device_context: &mut encoder,
curr_depth_buffer_srv: &scene_depth,
prev_depth_buffer_srv: &previous_depth,
curr_camera: Some(&camera),
prev_camera: Some(&camera),
camera_attribs_cb: None,
pass_timestamps: None,
});
ssr.execute(&mut RenderAttributes {
device,
queue,
device_context: &mut encoder,
post_fx_context: &mut context,
color_buffer_srv: &color,
depth_buffer_srv: &scene_depth,
normal_buffer_srv: &normal,
material_buffer_srv: &material,
motion_vectors_srv: &motion,
ssr_attribs: &ScreenSpaceReflectionAttribs::default(),
pass_timestamps: None,
reset_accumulation: true,
frame_time: 1.0 / 60.0,
});
queue.submit([encoder.finish()]);
ssr
}
fn nonfinite(texels: &[[f32; 4]]) -> usize {
texels
.iter()
.filter(|t| !t.iter().all(|v| v.is_finite()))
.count()
}
#[test]
fn half_resolution_rays_at_an_infinite_horizon_are_finite() {
let Some((device, queue)) = device() else {
return;
};
let (_, b) = projection_scales();
let (s, c) = (0.13 / f64::from(b)).atan().sin_cos();
let ssr = trace_mirror_floor(
&device,
&queue,
[0.0, c, -s],
FeatureFlags::HALF_RESOLUTION,
0,
|_, _| false,
);
for (name, view) in [
("radiance", &ssr.resources().radiance),
("direction and PDF", &ssr.resources().ray_direction_pdf),
] {
let rays = read_rgba16f(&device, &queue, view);
let nonfinite = nonfinite(&rays);
assert_eq!(nonfinite, 0, "{nonfinite} of {} rays' {name}", rays.len());
}
}
#[test]
fn rays_past_the_far_plane_keep_their_direction() {
let Some((device, queue)) = device() else {
return;
};
let (a, b) = projection_scales();
let horizon = -1.0 / 48.0 + 0.2 / 48.0;
let (s, c) = (horizon / f64::from(b)).atan().sin_cos();
let floor_normal = [0.0, c, -s];
let depths = floor_depths(floor_normal);
let ssr = trace_mirror_floor(
&device,
&queue,
floor_normal,
FeatureFlags::NONE,
0,
|_, _| false,
);
let rays = read_rgba16f(&device, &queue, &ssr.resources().ray_direction_pdf);
let mut wrong = Vec::new();
let mut row_24_past_far_plane = 0;
for y in 0..SIZE[1] {
for x in 0..SIZE[0] {
let at = (y * SIZE[0] + x) as usize;
if depths[at] == 0.0 {
continue;
}
assert!(y >= 24, "({x}, {y}) is floor above row 24");
let ray = rays[at];
let length = ray[..3].iter().map(|v| v * v).sum::<f32>().sqrt();
let view = pixel_ray(x, y);
let view_length = view.iter().map(|v| v * v).sum::<f64>().sqrt();
let view = view.map(|v| v / view_length);
let v_dot_n: f64 = (0..3).map(|i| view[i] * floor_normal[i]).sum();
let mirror: [f32; 3] =
std::array::from_fn(|i| (view[i] - 2.0 * v_dot_n * floor_normal[i]) as f32);
let vanishing = [
f64::from(mirror[0] / mirror[2] * a),
f64::from(mirror[1] / mirror[2] * b),
];
let past_far_plane = mirror[2] > 0.0
&& vanishing[0].abs() < 1.0 - 2.0 / f64::from(SIZE[0])
&& vanishing[1].abs() < 1.0 - 2.0 / f64::from(SIZE[1]);
if past_far_plane && y == 24 {
row_24_past_far_plane += 1;
}
if !((!past_far_plane || (65504.0 - 64.0..=65504.0 + 64.0).contains(&length))
&& (0..3).all(|i| (ray[i] / length - mirror[i]).abs() < 4e-3))
{
wrong.push(format!("({x}, {y}): {ray:?}, mirror {mirror:?}"));
}
}
}
assert!(
row_24_past_far_plane > 0,
"no ray of row 24 overshoots the far plane"
);
assert!(
wrong.is_empty(),
"{} of the floor's rays are not along their mirror direction, as long as RGBA16F holds past the far plane:\n{}",
wrong.len(),
wrong.join("\n")
);
let output = read_rgba16f(&device, &queue, ssr.get_ssr_radiance_srv());
let nonfinite = nonfinite(&output);
assert_eq!(nonfinite, 0, "{nonfinite} non-finite output pixels");
}
#[test]
fn zero_normals_report_a_miss() {
let Some((device, queue)) = device() else {
return;
};
let (_, b) = projection_scales();
let (s, c) = (0.13 / f64::from(b)).atan().sin_cos();
let floor_normal = [0.0, c, -s];
let zero_normal = |x: u32, y: u32| (x + y).is_multiple_of(5);
let depths = floor_depths(floor_normal);
for feature_flags in [FeatureFlags::NONE, FeatureFlags::HALF_RESOLUTION] {
let ssr = trace_mirror_floor(&device, &queue, floor_normal, feature_flags, 0, zero_normal);
let radiance = read_rgba16f(&device, &queue, &ssr.resources().radiance);
let rays = read_rgba16f(&device, &queue, &ssr.resources().ray_direction_pdf);
for (name, texels) in [("radiance", &radiance), ("direction and PDF", &rays)] {
let nonfinite = nonfinite(texels);
assert_eq!(
nonfinite,
0,
"{feature_flags:?}: {nonfinite} of {} rays' {name}",
texels.len()
);
}
if feature_flags != FeatureFlags::NONE {
continue;
}
let mut wrong = Vec::new();
for y in 0..SIZE[1] {
for x in 0..SIZE[0] {
let at = (y * SIZE[0] + x) as usize;
if depths[at] == 0.0 {
continue;
}
let traced = rays[at][..3].iter().any(|&v| v != 0.0);
let missed = rays[at] == [0.0; 4] && radiance[at] == [0.0; 4];
if zero_normal(x, y) && !missed || !zero_normal(x, y) && !traced {
wrong.push(format!(
"({x}, {y}): ray {:?}, radiance {:?}",
rays[at], radiance[at]
));
}
}
}
assert!(
wrong.is_empty(),
"{} floor pixels traced a zero normal or missed a unit one:\n{}",
wrong.len(),
wrong.join("\n")
);
}
}
#[test]
fn glossy_grazing_rays_keep_finite_pdf_and_reconstruction_weight() {
let Some((device, queue)) = device() else {
return;
};
let normal = [0.0, 1.0, 0.0];
let ssr = trace_mirror_floor(&device, &queue, normal, FeatureFlags::NONE, 17, |_, _| {
false
});
let rays = read_rgba16f(&device, &queue, &ssr.resources().ray_direction_pdf);
assert!(
rays.iter()
.all(|ray| ray[3].is_finite() && ray[3] <= 65504.0)
);
let mut source = crate::shaders::shader_source(
"SSR_ComputeSpatialReconstruction.fx",
&[
("SUPPORTED_SHADER_SRV", "1"),
("SSR_OPTION_INVERTED_DEPTH", "1"),
("SSR_OPTION_PREVIOUS_FRAME", "0"),
("SSR_OPTION_HALF_RESOLUTION", "0"),
("SSR_DENOISER_TILE_SIZE", "8"),
],
);
let (a, b) = projection_scales();
source.push_str(&format!(
r#"
@group(0) @binding(8) var<storage, read_write> measured_weights: array<f32>;
@compute @workgroup_size(8, 8)
fn measure_weight(@builtin(global_invocation_id) id: vec3<u32>) {{
if (id.x >= {width}u || id.y >= {height}u) {{ return; }}
let uv = (vec2<f32>(id.xy) + 0.5) / vec2<f32>({width}.0, {height}.0);
let V = -normalize(vec3<f32>((2.0 * uv.x - 1.0) / {a}, (1.0 - 2.0 * uv.y) / {b}, 1.0));
let N = vec3<f32>(0.0, 1.0, 0.0);
measured_weights[id.y * {width}u + id.x] = ComputeWeightRayLength(vec2<i32>(id.xy), V, N, 17.0 / 255.0, max(dot(N, V), 1e-6), 1.0).x;
}}
"#,
width = SIZE[0], height = SIZE[1],
));
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("glossy-floor reconstruction weights"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: None,
module: &shader,
entry_point: Some("measure_weight"),
compilation_options: Default::default(),
cache: None,
});
let size = u64::from(SIZE[0] * SIZE[1]) * 4;
let weights = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::TextureView(&ssr.resources().ray_direction_pdf),
},
wgpu::BindGroupEntry {
binding: 8,
resource: weights.as_entire_binding(),
},
],
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &bind, &[]);
pass.dispatch_workgroups(SIZE[0].div_ceil(8), SIZE[1].div_ceil(8), 1);
}
encoder.copy_buffer_to_buffer(&weights, 0, &readback, 0, size);
queue.submit([encoder.finish()]);
readback.map_async(wgpu::MapMode::Read, .., |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let bytes = readback.get_mapped_range(..).unwrap();
let weights: &[f32] = bytemuck::cast_slice(&bytes);
let mut saturated = 0;
for (ray, weight) in rays.iter().zip(weights) {
if ray[3] == 65504.0 {
saturated += 1;
assert!(
*weight > 1e-6,
"saturated grazing ray {ray:?} discarded at weight {weight}"
);
}
}
assert!(
saturated > 0,
"fixture did not reach the half-float PDF limit"
);
}