use crate::renderer::Renderer;
use crate::settings::{self, Settings};
use crate::static_lighting::{IrradianceAtlas, Lightmap};
use crate::{
Backdrop, Camera, DirectionalLight, FrameInput, HemisphereLight, IrradianceCell,
IrradianceVolume, Light, LightShape, Scene, asset, test_support,
};
use glam::{DVec3, Mat4, Vec3};
use std::f64::consts::{FRAC_PI_2, PI};
pub(super) const THETA_STEPS: usize = 512;
pub(super) const PHI_STEPS: usize = 1024;
pub(super) const THREADS: usize = 256;
pub(super) fn cell(theta: f64) -> f64 {
theta.sin() * (FRAC_PI_2 / THETA_STEPS as f64) * (2. * PI / PHI_STEPS as f64)
}
pub(super) fn grid(row: usize, column: usize) -> (f64, f64) {
(
(row as f64 + 0.5) / THETA_STEPS as f64 * FRAC_PI_2,
(column as f64 + 0.5) / PHI_STEPS as f64 * 2. * PI,
)
}
pub(super) fn polar(theta: f64, phi: f64) -> DVec3 {
DVec3::new(
theta.sin() * phi.cos(),
theta.sin() * phi.sin(),
theta.cos(),
)
}
pub(super) fn grid_wgsl() -> String {
format!(
r#"
const THETA_STEPS:u32={THETA_STEPS}u;
const PHI_STEPS:u32={PHI_STEPS}u;
const THREADS:u32={THREADS}u;
fn grid_direction(row:u32,column:u32)->vec3<f32> {{
let theta=(f32(row)+.5)/f32(THETA_STEPS)*1.5707963267948966;
let phi=(f32(column)+.5)/f32(PHI_STEPS)*6.283185307179586;
return vec3(sin(theta)*cos(phi),sin(theta)*sin(phi),cos(theta));
}}
fn case_surface(view:vec3<f32>,rough:f32,base:vec3<f32>,metallic:f32)->Surface {{
var s:Surface;
s.normal=vec3(0.,0.,1.);
s.geometry_normal=s.normal;
s.coat_normal=s.normal;
s.view=view;
s.roughness=rough;
s.base=vec4(base,1.);
s.metallic=metallic;
s.dielectric_f0=vec3(.04);
s.specular=1.;
s.environment_scale=1.;
s.occlusion=1.;
s.front=true;
return s;
}}
fn case_reflectance(s:Surface)->SurfaceReflectance {{
return surface_reflectance(s,surface_dfg(specular_nv(s.normal,s.view),s.roughness));
}}
"#
)
}
#[derive(Clone, Copy, Debug)]
struct Furnace {
view: DVec3,
rough: f64,
base: [f64; 3],
metallic: f64,
specular: f64,
film: [f64; 3],
}
const NO_FILM: [f64; 3] = [0., 1.3, 0.];
fn furnaces(cases: &[Furnace]) -> Option<Vec<(DVec3, DVec3)>> {
let (device, queue) = test_support::device()?;
let scene = Scene::new(&device, &queue);
let packed: Vec<[[f32; 4]; 3]> = cases
.iter()
.map(|c| {
[
c.view.as_vec3().extend(c.rough as f32).to_array(),
[c.base[0], c.base[1], c.base[2], c.metallic].map(|v| v as f32),
[c.specular, c.film[0], c.film[1], c.film[2]].map(|v| v as f32),
]
})
.collect();
let observation = format!(
r#"{}
struct Case {{ view:vec4<f32>,base:vec4<f32>,light:vec4<f32> }}
@group(0) @binding(3) var<storage,read> cases:array<Case>;
@group(0) @binding(4) var<storage,read_write> result:array<vec4<f32>>;
@compute @workgroup_size({THREADS}) fn observe(@builtin(workgroup_id) group:vec3<u32>,@builtin(local_invocation_index) thread:u32) {{
let c=cases[group.x];
var s=case_surface(c.view.xyz,c.view.w,c.base.rgb,c.base.w);
s.film=surface_film(s,c.light.y,c.light.z,c.light.w);
let reflectance=case_reflectance(s);
for (var row=thread;row<THETA_STEPS;row+=THREADS) {{
var ring=vec3(0.);
for (var column=0u;column<PHI_STEPS;column++) {{
let light=LightSample(grid_direction(row,column),vec3(1.),1.,1.,c.light.x,NO_RECT_LIGHT,0.);
ring+=surface_direct_light(s,reflectance,light);
}}
result[group.x*THETA_STEPS+row]=vec4(ring,0.);
}}
if thread==0u {{
let dfg=reflectance.view_dfg;
let lobes=specular_lobes(s.normal,s.normal,s.view,reflectance.f0,reflectance.f90,s.roughness,dfg,0.,0.,vec4(0.),lookup_tables,environment_sampler);
let ibl=surface_ibl_weights(s,reflectance);
result[arrayLength(&cases)*THETA_STEPS+group.x]=vec4(lobes[0].response+ibl.multi+ibl.diffuse,0.);
}}
}}
"#,
grid_wgsl()
);
let rows = test_support::observe_surface(
&device,
&queue,
&scene,
bytemuck::cast_slice(&packed),
&observation,
cases.len() as u32,
cases.len() * (THETA_STEPS + 1),
);
let vector = |a: [f32; 4]| DVec3::new(a[0] as f64, a[1] as f64, a[2] as f64);
Some(
(0..cases.len())
.map(|case| {
let direct = (0..THETA_STEPS)
.map(|row| vector(rows[case * THETA_STEPS + row]) * cell(grid(row, 0).0))
.sum();
(direct, vector(rows[cases.len() * THETA_STEPS + case]))
})
.collect(),
)
}
pub(super) fn view(nv: f64) -> DVec3 {
DVec3::new((1. - nv * nv).sqrt(), 0., nv)
}
pub(super) fn coupled_diffuse(view: DVec3) -> f64 {
let mut sum = 0.;
for row in 0..THETA_STEPS {
for column in 0..PHI_STEPS {
let (theta, phi) = grid(row, column);
let l = polar(theta, phi);
let vh = view.dot((view + l).normalize()).clamp(0., 1.);
let fresnel = 0.04 + 0.96 * (1. - vh).powi(5);
sum += (1. - fresnel) / PI * l.z * cell(theta);
}
}
sum
}
#[test]
fn a_white_furnace_conserves_energy_under_direct_light() {
let views = [0.1, 0.3, 0.5, 0.7, 0.9, 1.];
let mut cases = Vec::new();
for rough in [0.25, 0.5, 0.75, 1.] {
for &nv in &views {
cases.push(Furnace {
view: view(nv),
rough,
base: [1.; 3],
metallic: 1.,
specular: 1.,
film: NO_FILM,
});
}
}
let first_dielectric = cases.len();
for &nv in &views {
cases.push(Furnace {
view: view(nv),
rough: 0.5,
base: [1.; 3],
metallic: 0.,
specular: 0.,
film: NO_FILM,
});
}
let Some(observed) = furnaces(&cases) else {
return;
};
let mut worst = [0f64; 3];
for (case, (direct, _)) in cases[..first_dielectric].iter().zip(&observed) {
let bound = if case.rough < 1. { 0.01 } else { 0.035 };
let deviation = (*direct - DVec3::ONE).abs().max_element();
let at = usize::from(case.rough == 1.);
worst[at] = worst[at].max(deviation);
assert!(
(*direct - DVec3::ONE).abs().max_element() <= bound,
"white metal {case:?}: reflects {direct:?} of a white furnace"
);
}
for (case, (direct, _)) in cases[first_dielectric..]
.iter()
.zip(&observed[first_dielectric..])
{
let expected = coupled_diffuse(case.view);
worst[2] = worst[2].max((*direct - DVec3::splat(expected)).abs().max_element() / expected);
assert!(
(*direct - DVec3::splat(expected)).abs().max_element() <= 0.001 * expected,
"white dielectric under diffuse-only lights {case:?}: {direct:?}, glTF {expected}"
);
}
eprintln!(
"white furnace: metal within {:.5} below roughness 1 and {:.5} at 1; dielectric within {:.6} of glTF",
worst[0], worst[1], worst[2]
);
}
#[test]
fn a_white_furnace_conserves_energy_under_a_film() {
let film = [1., 1.8, 400.];
let cases: Vec<Furnace> = [1., 0.7]
.into_iter()
.map(|nv| Furnace {
view: view(nv),
rough: 0.5,
base: [1.; 3],
metallic: 0.,
specular: 0.,
film,
})
.collect();
let Some(observed) = furnaces(&cases) else {
return;
};
for (case, (direct, environment)) in cases.iter().zip(&observed) {
assert!(
(*environment - DVec3::ONE).abs().max_element() <= 1e-4,
"white dielectric under a film {case:?}: reflects {environment:?} of a white environment"
);
let thin = super::iridescence_tests::thin_film(film[1], 1.5, film[2], case.view.z);
let kept = 1. - thin.into_iter().fold(0., f64::max);
assert!(
(*direct - DVec3::splat(kept)).abs().max_element() <= 0.011,
"white dielectric under a film and diffuse-only lights {case:?}: {direct:?}, rgb_mix {kept}"
);
}
}
#[test]
fn diffuse_only_lights_light_the_base_whole_beneath_its_layers() {
let layers = [(0., [0.; 3]), (1., [0.; 3]), (0., [1.; 3]), (1., [1.; 3])];
let mut cases = Vec::new();
for nv in [0.3, 0.8] {
for transmission in [0., 0.5] {
for (coat, sheen) in layers {
cases.push(Layered {
view: view(nv),
coat,
sheen,
transmission,
light_specular: 0.,
..Layered::default()
});
}
}
}
let Some(observed) = observe_lit(&cases) else {
return;
};
for (cases, observed) in cases
.chunks(layers.len())
.zip(observed.chunks(layers.len()))
{
let [bare_above, bare_below, _] = observed[0];
for (case, [above, below, _]) in cases.iter().zip(observed).skip(1) {
for (side, layered, bare) in [("front", above, bare_above), ("back", below, bare_below)]
{
assert!(
(*layered - bare).abs().max_element() <= 1e-5 * bare.max_element().max(1e-3),
"{case:?}, {side}: {layered:?}, {bare:?} without its layers"
);
}
}
}
}
#[test]
fn a_probe_ray_s_hit_takes_no_coat() {
let Some((device, queue)) = test_support::device() else {
return;
};
let settings = quiet_settings();
let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
let mut scene = Scene::new(&device, &queue);
let mut input = dark_input();
input.hemisphere_light = HemisphereLight {
sky_color: [1.; 3],
ground_color: [0.5; 3],
intensity: 1.,
};
input.directional_lights[0] = Some(DirectionalLight {
direction: Vec3::new(0.3, 0., -1.),
color: [1.; 3],
illuminance: 1.,
..Default::default()
});
let observation = format!(
r#"{}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
@compute @workgroup_size(1) fn observe() {{
let context=ShadeContext(vec2(0.),SHADOW_RECEIVER_PROBE_HIT,false,true,cluster_range(vec3(0.),vec2(0.)),untraced_reflection());
for (var coat=0u;coat<2u;coat++) {{
var s=case_surface(normalize(vec3(-.6,0.,.8)),.5,vec3(.8),0.);
s.lightmap_uv=vec2(-1.);
s.coat=f32(coat);
s.coat_roughness=.3;
s.emission=vec3(.25);
output[coat*2u]=vec4(shade_lit(s,context).color,0.);
output[coat*2u+1u]=vec4(probe_hit_light(s,cluster_range(s.position,vec2(0.)),vec3(0.)),0.);
}}
}}
"#,
grid_wgsl()
);
let rows = test_support::observe_ray_hits(
&device,
&queue,
&mut renderer,
&mut scene,
&input,
&settings,
&observation,
4,
);
let vector = |a: [f32; 4]| DVec3::new(a[0] as f64, a[1] as f64, a[2] as f64);
for (label, bare, coated) in [
("indirect light and emission", rows[0], rows[2]),
("its light", rows[1], rows[3]),
] {
let (bare, coated) = (vector(bare), vector(coated));
assert!(bare.min_element() > 0.01, "{label}: {bare:?}");
assert!(
(coated - bare).abs().max_element() <= 1e-5 * bare.max_element(),
"{label}: coated {coated:?}, {bare:?} without its coat"
);
}
}
#[test]
fn specular_weights_above_1_leave_the_base_beneath_its_layers_as_at_1() {
let layers = [(1., [0.; 3]), (0., [1.; 3]), (1., [1.; 3])];
let weights = [1., 2., 4.];
let mut cases = Vec::new();
for nv in [0.3, 0.8] {
for (coat, sheen) in layers {
for light_specular in weights {
cases.push(Layered {
view: view(nv),
coat,
sheen,
transmission: 1.,
light_specular,
..Layered::default()
});
}
}
}
let Some(observed) = observe_lit(&cases) else {
return;
};
for (cases, observed) in cases
.chunks(weights.len())
.zip(observed.chunks(weights.len()))
{
let [_, at_1, _] = observed[0];
assert!(at_1.max_element() > 0., "{:?}: lit from behind", cases[0]);
for (case, [_, below, _]) in cases.iter().zip(observed).skip(1) {
assert!(
(*below - at_1).abs().max_element() <= 1e-5 * at_1.max_element(),
"{case:?}: {below:?} behind, {at_1:?} at weight 1"
);
}
}
}
#[test]
fn direct_light_and_the_environment_reflect_alike() {
let metals = [
("gold", [1., 0.766, 0.336]),
("copper", [0.955, 0.638, 0.538]),
("iron", [0.56, 0.57, 0.58]),
];
let mut cases = Vec::new();
for (_, base) in metals {
for rough in [0.25, 0.5, 0.75, 1.] {
for nv in [0.3, 0.7] {
cases.push(Furnace {
view: view(nv),
rough,
base,
metallic: 1.,
specular: 1.,
film: NO_FILM,
});
}
}
}
let Some(observed) = furnaces(&cases) else {
return;
};
let mut worst = [0f64; 2];
for (case, (direct, environment)) in cases.iter().zip(observed) {
let bound = if case.rough < 1. { 0.01 } else { 0.035 };
let ratio = direct / environment;
let at = usize::from(case.rough == 1.);
worst[at] = worst[at].max((ratio - DVec3::ONE).abs().max_element());
assert!(
(ratio - DVec3::ONE).abs().max_element() <= bound,
"{case:?}: direct {direct:?} against the environment's {environment:?}"
);
}
eprintln!(
"direct against environment: within {:.5} below roughness 1 and {:.5} at 1",
worst[0], worst[1]
);
}
pub(super) fn dark_input() -> FrameInput {
let mut input = FrameInput::new(Camera {
view: Mat4::IDENTITY,
projection: crate::perspective(1., 1., 0.1),
eye: Vec3::ZERO,
});
input.backdrop = Backdrop::Color([0.; 3]);
input.hemisphere_light = HemisphereLight {
sky_color: [0.; 3],
ground_color: [0.; 3],
intensity: 0.,
};
input.baked_lighting = true;
input
}
pub(super) fn quiet_settings() -> Settings {
Settings {
antialiasing: settings::Antialiasing::Off,
bloom: settings::Bloom::Off,
ambient_occlusion: settings::AmbientOcclusionQuality::Off,
screen_space_reflections: settings::ScreenSpaceReflections::Off,
world_space_reflections: settings::WorldSpaceReflections::Off,
dynamic_gi: settings::DynamicGiQuality::Off,
..Settings::default()
}
}
const IRRADIANCE: f32 = 0.5;
#[test]
fn one_rule_for_every_indirect_source() {
let Some((device, queue)) = test_support::device() else {
return;
};
let settings = quiet_settings();
let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
let mut scene = Scene::new(&device, &queue);
let mut model = test_support::cube();
model.meshes[0].vertices = [(-1., -1.), (1., -1.), (1., 1.), (-1., 1.)]
.map(|(x, z)| asset::Vertex {
tangent: [0.; 4],
position: [x, -50., z],
normal: [0., 1., 0.],
uv: [0.5; 2],
color: [1.; 4],
lightmap_uv: [0.5; 2],
lightmap_bounds: [0., 0., 1., 1.],
})
.to_vec();
model.meshes[0].indices = vec![0, 1, 2, 0, 2, 3];
let (world, _) = test_support::add_static(&device, &queue, &mut scene, model);
let irradiance = [IRRADIANCE; 3];
scene
.set_lightmap(
&device,
&queue,
&Lightmap {
size: [2, 2],
uv_scale_offset: [1., 1., 0., 0.],
irradiance: vec![irradiance; 4],
directionality: vec![],
},
&world.materials,
)
.unwrap();
scene
.set_static_irradiance_atlas(
&device,
&queue,
&IrradianceAtlas {
size: [4, 4],
irradiance: vec![irradiance; 16],
back_irradiance: vec![irradiance; 16],
directionality: vec![],
back_directionality: vec![],
},
)
.unwrap();
let volume = IrradianceVolume {
origin: Vec3::new(-2., -2., 8.),
cell_size: Vec3::splat(1.),
cells: [4, 4, 4],
};
scene
.set_irradiance_volume(&device, &queue, Some(volume))
.unwrap();
let cells = vec![
IrradianceCell {
irradiance: crate::static_lighting::AmbientCube {
irradiance: [irradiance; 6],
},
sky_visibility: [0.; 6],
};
64
];
let region = crate::PreparedIrradianceRegion::new(volume.origin, volume.cells, &cells).unwrap();
scene.write_irradiance_cells(&queue, ®ion).unwrap();
let texel: Vec<u8> = [IRRADIANCE, IRRADIANCE, IRRADIANCE, 1.]
.iter()
.flat_map(|&value| test_support::to_half(value).to_le_bytes())
.collect();
let environment = scene
.add_environment(
&device,
&queue,
&test_support::environment([255; 4], &texel),
)
.unwrap();
let sources = [
("environment", true, false, Vec3::ZERO, false, false, false),
(
"hemisphere fill",
false,
true,
Vec3::ZERO,
false,
false,
false,
),
(
"irradiance volume",
false,
false,
Vec3::new(0., 0., 10.),
false,
false,
false,
),
("lightmap", false, false, Vec3::ZERO, true, false, false),
(
"irradiance atlas",
false,
false,
Vec3::ZERO,
false,
true,
false,
),
("ambient cube", false, false, Vec3::ZERO, false, false, true),
];
let mut observed = Vec::new();
for (name, lit_by_environment, filled, position, lightmapped, charted, moving) in sources {
let mut input = dark_input();
if lit_by_environment {
input.environment = Some(environment);
}
if filled {
input.hemisphere_light = HemisphereLight {
sky_color: [1.; 3],
ground_color: [1.; 3],
intensity: IRRADIANCE * std::f32::consts::PI,
};
}
let observation = format!(
r#"{}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
@compute @workgroup_size(1) fn observe() {{
let view=normalize(vec3(.95394,.3,0.));
for (var metal=0u;metal<2u;metal++) {{
let gold=metal==1u;
var s=case_surface(view,select(.5,.6,gold),select(vec3(.5),vec3(1.,.766,.336),gold),select(0.,1.,gold));
s.normal=vec3(0.,1.,0.);
s.geometry_normal=s.normal;
s.coat_normal=s.normal;
s.position=vec3({:?},{:?},{:?});
s.baked={lightmapped};
s.moving={moving};
s.lightmap_uv=select(vec2(-1.),vec2(.5),{lightmapped}||{charted});
s.lightmap_bounds=vec4(0.,0.,1.,1.);
for (var face=0u;face<6u;face++) {{
s.baked_irradiance[face]=vec4({IRRADIANCE:?});
}}
let context=ShadeContext(vec2(0.),SHADOW_RECEIVER_CAMERA,false,false,cluster_range(s.position,vec2(0.)),untraced_reflection());
output[metal]=vec4(shade_lit(s,context).color,0.);
}}
}}
"#,
grid_wgsl(),
position.x,
position.y,
position.z,
);
let rows = test_support::observe_ray_hits(
&device,
&queue,
&mut renderer,
&mut scene,
&input,
&settings,
&observation,
2,
);
observed.push((name, rows));
}
let (_, reference) = &observed[0];
assert!(reference.iter().all(|c| c[0] > 0.01), "{reference:?}");
for (name, rows) in &observed[1..] {
for (material, (row, expected)) in ["grey dielectric", "rough gold"]
.iter()
.zip(rows.iter().zip(reference))
{
for channel in 0..3 {
assert!(
(row[channel] - expected[channel]).abs() <= 0.005 * expected[channel],
"{material} under the {name}: {row:?}, under the environment {expected:?}"
);
}
}
}
}
fn disc_reference(view: DVec3, rough: f64, centre: DVec3, radius: f64, radiance: f64) -> f64 {
let a2 = rough.powi(4);
let tangent = centre.cross(DVec3::Y).normalize();
let bitangent = centre.cross(tangent);
let steps = 1000;
let mut sum = 0.;
for i in 0..steps {
let theta = (i as f64 + 0.5) / steps as f64 * radius;
for j in 0..steps {
let phi = (j as f64 + 0.5) / steps as f64 * 2. * PI;
let l =
centre * theta.cos() + (tangent * phi.cos() + bitangent * phi.sin()) * theta.sin();
let (nl, nv) = (l.z, view.z);
if nl <= 0. {
continue;
}
let nh = (view + l).normalize().z;
let d = a2 / (PI * (nh * nh * (a2 - 1.) + 1.).powi(2));
let visibility = 0.5
/ (nl * (nv * nv * (1. - a2) + a2).sqrt() + nv * (nl * nl * (1. - a2) + a2).sqrt());
let solid_angle = theta.sin() * (radius / steps as f64) * (2. * PI / steps as f64);
sum += d * visibility * nl * solid_angle;
}
}
sum * radiance
}
fn highlight(
(device, queue): (&wgpu::Device, &wgpu::Queue),
renderer: &mut Renderer,
scene: &mut Scene,
input: &FrameInput,
rough: f64,
peak_view: DVec3,
light: &str,
) -> (f64, f64) {
let observation = format!(
r#"{}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
fn reflected(view:vec3<f32>)->f32 {{
let s=case_surface(view,{rough:?},vec3(1.),1.);
let reflectance=case_reflectance(s);
return surface_direct_light(s,reflectance,{light}).g;
}}
@compute @workgroup_size({THREADS}) fn observe(@builtin(local_invocation_index) thread:u32) {{
for (var row=thread;row<THETA_STEPS;row+=THREADS) {{
var ring=0.;
for (var column=0u;column<PHI_STEPS;column++) {{
let view=grid_direction(row,column);
ring+=reflected(view)*view.z;
}}
output[row]=vec4(ring,0.,0.,0.);
}}
if thread==0u {{
output[THETA_STEPS]=vec4(reflected(vec3({:?},{:?},{:?})),0.,0.,0.);
}}
}}
"#,
grid_wgsl(),
peak_view.x as f32,
peak_view.y as f32,
peak_view.z as f32,
);
let rows = test_support::observe_ray_hits(
device,
queue,
renderer,
scene,
input,
&quiet_settings(),
&observation,
THETA_STEPS + 1,
);
let energy = (0..THETA_STEPS)
.map(|row| rows[row][0] as f64 * cell(grid(row, 0).0))
.sum();
(rows[THETA_STEPS][0] as f64, energy)
}
#[test]
fn a_sized_light_spreads_its_highlight_over_its_sphere_or_disc() {
let Some((device, queue)) = test_support::device() else {
return;
};
let settings = quiet_settings();
let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
let within = |ratio: f64, low: f64, high: f64| (low..=high).contains(&ratio);
for elevation in [0.6f64, 1.0, 1.3] {
let centre = DVec3::new(elevation.sin(), 0., elevation.cos());
let mirror = DVec3::new(-centre.x, 0., centre.z);
for (rough, size) in [(0.045, 0.05), (0.1, 0.05), (0.1, 0.2), (0.25, 0.2)] {
let distance = 2.;
let radius = size * distance;
let mut scene = Scene::new(&device, &queue);
scene
.add_light(
&device,
&queue,
Light {
position: (centre * distance).as_vec3(),
shape: LightShape::Point {
radius: radius as f32,
},
color: [1.; 3],
intensity: 1.,
range: 1000.,
baked: false,
specular: 1.,
casts_shadow: false,
..Default::default()
},
)
.unwrap();
let (peak, energy) = highlight(
(&device, &queue),
&mut renderer,
&mut scene,
&dark_input(),
rough,
mirror,
"scene_light_sample(0u,s.position,s.normal,s.coat_normal,s.geometry_normal,vec2(0.),SHADOW_RECEIVER_CAPTURE,false,s.position,0.)",
);
let angular = (radius / distance).asin();
let expected =
disc_reference(mirror, rough, centre, angular, 1. / (PI * radius * radius));
let irradiance = centre.z / (distance * distance);
eprintln!(
"sphere at elevation {elevation}, roughness {rough}, radius/distance {size}: mirror {:.3} of the sphere's, energy {:.3}",
peak / expected,
energy / irradiance
);
assert!(
rough > 0.1 || within(peak / expected, 0.55, 1.1),
"sphere at elevation {elevation}, roughness {rough}, radius/distance {size}: {peak} along the mirror, the sphere gives {expected}"
);
assert!(
within(energy / irradiance, 0.8, 1.1),
"sphere at elevation {elevation}, roughness {rough}, radius/distance {size}: reflects {energy} of irradiance {irradiance}"
);
}
let mut scene = Scene::new(&device, &queue);
for rough in [0.045, 0.1] {
let mut input = dark_input();
input.directional_lights[0] = Some(DirectionalLight {
direction: -centre.as_vec3(),
illuminance: 1.,
angular_diameter: 0.1,
..Default::default()
});
let (peak, energy) = highlight(
(&device, &queue),
&mut renderer,
&mut scene,
&input,
rough,
mirror,
"directional_light_sample(0u,s.position,s.normal,s.coat_normal,s.geometry_normal,ShadeContext(vec2(0.),SHADOW_RECEIVER_CAPTURE,false,false,cluster_range(s.position,vec2(0.)),untraced_reflection()),false,s.position)",
);
let angular = 0.05f64;
let expected = disc_reference(
mirror,
rough,
centre,
angular,
1. / (PI * angular.sin().powi(2)),
);
eprintln!(
"disc at elevation {elevation}, roughness {rough}: mirror {:.3} of the disc's, energy {:.3}",
peak / expected,
energy / centre.z
);
assert!(
within(peak / expected, 0.55, 1.1),
"disc at elevation {elevation}, roughness {rough}: {peak} along the mirror, the disc gives {expected}"
);
assert!(
within(energy / centre.z, 0.8, 1.1),
"disc at elevation {elevation}, roughness {rough}: reflects {energy} of irradiance {}",
centre.z
);
}
}
}
#[test]
fn the_directional_light_s_front_skips_no_light_it_gives() {
let Some((device, queue)) = test_support::device() else {
return;
};
const ROWS: usize = 128;
const COLUMNS: usize = 256;
let settings = quiet_settings();
let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
let mut scene = Scene::new(&device, &queue);
let mut input = dark_input();
input.directional_lights[0] = Some(DirectionalLight {
direction: -Vec3::new(0.3, 0.2, 0.93).normalize(),
illuminance: 1.,
angular_diameter: 0.2,
..Default::default()
});
let observation = format!(
r#"{}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
@compute @workgroup_size({ROWS}) fn observe(@builtin(local_invocation_index) row:u32) {{
let light=frame.directional_lights[0];
let l=normalize(light.direction_to_light);
var mismatched=0.;
var behind=0.;
var most=0.;
for (var column=0u;column<{COLUMNS}u;column++) {{
let theta=(f32(row)+.5)/f32({ROWS})*3.141592653589793;
let phi=(f32(column)+.5)/f32({COLUMNS})*6.283185307179586;
let n=vec3(sin(theta)*cos(phi),sin(theta)*sin(phi),cos(theta));
let across=l-n*dot(n,l);
let toward=select(n,normalize(across),dot(across,across)>1e-8);
for (var tilt=0u;tilt<3u;tilt++) {{
let angle=array<f32,3>(0.,.4,.9)[tilt];
let coat_normal=normalize(n*cos(angle)+toward*sin(angle));
var s=case_surface(normalize(n+coat_normal),.3,vec3(1.),0.);
s.normal=n;
s.geometry_normal=n;
s.coat_normal=coat_normal;
s.coat=1.;
s.coat_roughness=.3;
let reflectance=case_reflectance(s);
let context=ShadeContext(vec2(0.),SHADOW_RECEIVER_CAPTURE,false,false,cluster_range(s.position,vec2(0.)),untraced_reflection());
let sampled=surface_direct_light(s,reflectance,directional_light_sample(0u,s.position,s.normal,s.coat_normal,s.geometry_normal,context,false,s.position));
let full=surface_direct_light(s,reflectance,LightSample(l,light.color*light.illuminance,1.,0.,1.,NO_RECT_LIGHT,light.disc_radius));
if any(abs(sampled-full)>full*1e-4+1e-12) {{
mismatched+=1.;
}}
if dot(n,l)<=0. && any(full>vec3(0.)) {{
behind+=1.;
}}
most=max(most,max(full.r,max(full.g,full.b)));
}}
}}
output[row]=vec4(mismatched,behind,most,0.);
}}
"#,
grid_wgsl(),
);
let rows = test_support::observe_ray_hits(
&device,
&queue,
&mut renderer,
&mut scene,
&input,
&settings,
&observation,
ROWS,
);
let total = |channel: usize| rows.iter().map(|row| row[channel] as f64).sum::<f64>();
let most = rows.iter().map(|row| row[2]).fold(0f32, f32::max);
eprintln!(
"{} surfaces take the light with the base normal turned away; brightest {most}",
total(1)
);
assert!(most > 0.1, "the light reflects {most} at most");
assert_eq!(
total(0),
0.,
"surfaces whose front reflects other than the full-visibility light gives"
);
}
#[derive(Clone, Copy, Debug)]
pub(super) struct Layered {
pub view: DVec3,
pub rough: f64,
pub base: [f64; 3],
pub metallic: f64,
pub dielectric_f0: f64,
pub coat: f64,
pub sheen: [f64; 3],
pub sheen_rough: f64,
pub transmission: f64,
pub transmission_color: [f64; 3],
pub volume_thickness: f64,
pub attenuation: [f64; 3],
pub occlusion: f64,
pub light_specular: f64,
}
impl Default for Layered {
fn default() -> Self {
Self {
view: DVec3::Z,
rough: 0.5,
base: [1.; 3],
metallic: 0.,
dielectric_f0: 0.04,
coat: 0.,
sheen: [0.; 3],
sheen_rough: 0.5,
transmission: 0.,
transmission_color: [1.; 3],
volume_thickness: 0.,
attenuation: [0.; 3],
occlusion: 1.,
light_specular: 1.,
}
}
}
pub(super) fn observe_lit(cases: &[Layered]) -> Option<Vec<[DVec3; 3]>> {
let (device, queue) = test_support::device()?;
let settings = quiet_settings();
let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
let mut scene = Scene::new(&device, &queue);
let texel: Vec<u8> = [1f32; 4]
.iter()
.flat_map(|&value| test_support::to_half(value).to_le_bytes())
.collect();
let environment = scene
.add_environment(
&device,
&queue,
&test_support::environment([255; 4], &texel),
)
.unwrap();
let mut input = dark_input();
input.environment = Some(environment);
let v3 = |v: [f64; 3]| {
format!(
"vec3({:?},{:?},{:?})",
v[0] as f32, v[1] as f32, v[2] as f32
)
};
let surfaces: Vec<String> = cases
.iter()
.map(|c| {
format!(
"Layered({},{:?},{},{:?},{:?},{:?},{},{:?},{:?},{},{:?},{},{:?},{:?})",
v3(c.view.to_array()),
c.rough as f32,
v3(c.base),
c.metallic as f32,
c.dielectric_f0 as f32,
c.coat as f32,
v3(c.sheen),
c.sheen_rough as f32,
c.transmission as f32,
v3(c.transmission_color),
c.volume_thickness as f32,
v3(c.attenuation),
c.occlusion as f32,
c.light_specular as f32,
)
})
.collect();
let count = cases.len();
let observation = format!(
r#"{}
struct Layered {{ view:vec3<f32>,rough:f32,base:vec3<f32>,metallic:f32,dielectric_f0:f32,coat:f32,sheen:vec3<f32>,sheen_rough:f32,transmission:f32,transmission_color:vec3<f32>,volume_thickness:f32,attenuation:vec3<f32>,occlusion:f32,light_specular:f32 }}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
fn layered(c:Layered)->Surface {{
var s=case_surface(c.view,c.rough,c.base,c.metallic);
s.dielectric_f0=vec3(c.dielectric_f0);
s.specular=select(0.,1.,c.dielectric_f0>0.);
s.coat=c.coat;
s.coat_roughness=.3;
s.sheen=c.sheen;
s.sheen_roughness=c.sheen_rough;
s.diffuse_transmission=c.transmission;
s.diffuse_transmission_color=c.transmission_color;
s.volume_thickness=c.volume_thickness;
s.volume_attenuation=c.attenuation;
s.occlusion=c.occlusion;
s.lightmap_uv=vec2(-1.);
return s;
}}
@compute @workgroup_size({THREADS}) fn observe(@builtin(local_invocation_index) thread:u32) {{
var cases=array<Layered,{count}>({});
for (var index=0u;index<{count}u;index++) {{
let c=cases[index];
let s=layered(c);
let reflectance=case_reflectance(s);
for (var row=thread;row<THETA_STEPS;row+=THREADS) {{
var above=vec3(0.);
var below=vec3(0.);
for (var column=0u;column<PHI_STEPS;column++) {{
let l=grid_direction(row,column);
above+=surface_direct_light(s,reflectance,LightSample(l,vec3(1.),1.,1.,c.light_specular,NO_RECT_LIGHT,0.));
below+=surface_direct_light(s,reflectance,LightSample(vec3(l.xy,-l.z),vec3(1.),1.,1.,c.light_specular,NO_RECT_LIGHT,0.));
}}
output[(index*THETA_STEPS+row)*2u]=vec4(above,0.);
output[(index*THETA_STEPS+row)*2u+1u]=vec4(below,0.);
}}
if thread==0u {{
let context=ShadeContext(vec2(0.),SHADOW_RECEIVER_CAPTURE,true,true,cluster_range(s.position,vec2(0.)),untraced_reflection());
output[{count}u*THETA_STEPS*2u+index]=vec4(shade_lit(s,context).color,0.);
}}
}}
}}
"#,
grid_wgsl(),
surfaces.join(","),
);
let rows = test_support::observe_ray_hits(
&device,
&queue,
&mut renderer,
&mut scene,
&input,
&settings,
&observation,
count * (THETA_STEPS * 2 + 1),
);
let vector = |a: [f32; 4]| DVec3::new(a[0] as f64, a[1] as f64, a[2] as f64);
Some(
(0..count)
.map(|case| {
let side = |half: usize| {
(0..THETA_STEPS)
.map(|row| {
vector(rows[(case * THETA_STEPS + row) * 2 + half])
* cell(grid(row, 0).0)
})
.sum()
};
[
side(0),
side(1),
vector(rows[count * THETA_STEPS * 2 + case]),
]
})
.collect(),
)
}