use super::probe_culling::ProbeCulling;
use crate::shading;
use crate::view::bindings::FogVolume;
use crate::view::cached_group::CachedGroup;
use crate::view::reflection_camera;
pub(crate) static COMPLETION: shading::Module = shading::Module {
name: "reflection_source",
source: include_str!("source.wgsl"),
deps: &[
&shading::GBUFFER,
&shading::PROBE_SAMPLING,
&shading::SPECULAR_LOBES,
&shading::PROBE_COLLECTION,
&shading::FULLSCREEN_VS,
&shading::FOG,
],
};
pub(crate) const MAIN_ENTRY: &str = "main";
pub(crate) const COMPOSE_SCREEN_SPACE_ENTRY: &str = "compose_screen_space";
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct ReflectionEnvironment {
pub yaw: f32,
pub intensity: f32,
pub fade: f32,
pub traced: f32,
}
pub(crate) fn environment_uniform(
device: &wgpu::Device,
rotation: f32,
strength: f32,
) -> wgpu::Buffer {
crate::counters::buffer_init(
device,
&wgpu::util::BufferInitDescriptor {
label: Some("application reflection environment intensity"),
contents: bytemuck::bytes_of(&ReflectionEnvironment {
yaw: rotation,
intensity: strength,
fade: 0.,
traced: 0.,
}),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
},
)
}
pub(crate) struct Environment<'a> {
pub sky: &'a wgpu::TextureView,
pub sampler: &'a wgpu::Sampler,
pub parameters: &'a wgpu::Buffer,
pub material: &'a wgpu::TextureView,
pub baked: &'a wgpu::TextureView,
pub collection: &'a wgpu::Buffer,
}
pub(crate) struct Inputs<'a> {
pub fog: FogVolume<'a>,
pub frame_fog: Option<SourceFog>,
pub camera: reflection_camera::Camera,
pub scene: &'a wgpu::TextureView,
pub ambient: &'a wgpu::TextureView,
pub output: &'a wgpu::TextureView,
pub normal: &'a wgpu::TextureView,
pub anisotropy: &'a wgpu::TextureView,
pub f0: &'a wgpu::TextureView,
pub depth: &'a wgpu::TextureView,
pub lookup_tables: &'a wgpu::TextureView,
pub ambient_occlusion: &'a wgpu::TextureView,
pub environment: Environment<'a>,
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct SourceCamera {
inverse: [[f32; 4]; 4],
eye: [f32; 4],
fog: [f32; 4],
forward: [f32; 3],
flags: u32,
}
const SOURCE_FOG: u32 = 1;
#[derive(Clone, Copy, Debug)]
pub(crate) struct SourceFog {
pub inverse_length: f32,
pub inverse_detail_spread: f32,
pub sky_affect: f32,
}
impl SourceCamera {
fn new(camera: reflection_camera::Camera, fog: Option<SourceFog>) -> Self {
let forward = -glam::Mat4::from_cols_array_2d(&camera.view)
.row(2)
.truncate();
Self {
inverse: camera.inverse_view_proj,
eye: camera.camera_position,
fog: fog.map_or([0.; 4], |fog| {
[
fog.inverse_length,
fog.inverse_detail_spread,
fog.sky_affect,
0.,
]
}),
forward: forward.to_array(),
flags: if fog.is_some() { SOURCE_FOG } else { 0 },
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct Variant {
pub environment: bool,
pub incident: bool,
pub diffuse_occlusion: bool,
}
struct Completion {
pipeline: wgpu::ComputePipeline,
group: CachedGroup,
compose: wgpu::RenderPipeline,
compose_group: CachedGroup,
}
fn completion(device: &wgpu::Device, variant: Variant) -> Completion {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("reflection source completion"),
source: wgpu::ShaderSource::Wgsl(shading::compose(&[&COMPLETION]).into()),
});
let constants = [
(
"application_environment_enabled",
f64::from(u8::from(variant.environment)),
),
(
"incident_radiance_enabled",
f64::from(u8::from(variant.incident)),
),
(
"diffuse_occlusion_enabled",
f64::from(u8::from(variant.diffuse_occlusion)),
),
];
let compilation_options = || wgpu::PipelineCompilationOptions {
constants: &constants,
..Default::default()
};
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("reflection source completion"),
layout: None,
module: &shader,
entry_point: Some(MAIN_ENTRY),
compilation_options: compilation_options(),
cache: None,
});
let compose = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("screen-space reflection composition"),
layout: None,
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(shading::FULLSCREEN_VS_ENTRY),
compilation_options: compilation_options(),
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(COMPOSE_SCREEN_SPACE_ENTRY),
compilation_options: compilation_options(),
targets: &[Some(wgpu::ColorTargetState {
format: crate::shading::gbuffer::COLOR,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::COLOR,
})],
}),
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
multiview_mask: None,
cache: None,
});
Completion {
group: CachedGroup::new(pipeline.get_bind_group_layout(0)),
pipeline,
compose_group: CachedGroup::new(compose.get_bind_group_layout(0)),
compose,
}
}
pub(crate) struct ReflectionSource {
culling: ProbeCulling,
completion: Completion,
variant: Variant,
camera: wgpu::Buffer,
size: [u32; 2],
pub(super) incident: wgpu::TextureView,
no_world: wgpu::TextureView,
}
impl ReflectionSource {
pub fn new(device: &wgpu::Device, size: [u32; 2], variant: Variant) -> Self {
let mut source = Self {
culling: ProbeCulling::new(device, size),
completion: completion(device, variant),
variant,
camera: crate::counters::buffer(
device,
&wgpu::BufferDescriptor {
label: Some("reflection source camera"),
size: std::mem::size_of::<SourceCamera>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
},
),
size,
incident: Self::target(device, [1, 1], "incident radiance"),
no_world: Self::target(device, [1, 1], "no world-space reflections"),
};
source.fit_incident(device);
source
}
fn target(device: &wgpu::Device, size: [u32; 2], label: &str) -> wgpu::TextureView {
device
.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: crate::shading::gbuffer::COLOR,
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::STORAGE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
})
.create_view(&Default::default())
}
pub fn use_variant(&mut self, device: &wgpu::Device, variant: Variant) {
if self.variant != variant {
self.completion = completion(device, variant);
self.variant = variant;
}
self.fit_incident(device);
}
pub fn resize(&mut self, device: &wgpu::Device, size: [u32; 2]) {
self.size = size;
self.culling.resize(device, size);
self.fit_incident(device);
}
pub fn incident(&self) -> Option<&wgpu::TextureView> {
self.variant.incident.then_some(&self.incident)
}
fn fit_incident(&mut self, device: &wgpu::Device) {
let size = if self.variant.incident {
self.size
} else {
[1, 1]
};
let texture = self.incident.texture();
if [texture.width(), texture.height()] != size {
self.incident = Self::target(device, size, "incident radiance");
}
}
pub fn encode(
&mut self,
encoder: &mut wgpu::CommandEncoder,
device: &wgpu::Device,
queue: &wgpu::Queue,
input: Inputs<'_>,
timing: Option<&crate::timing::GpuTiming>,
) {
crate::counters::write_buffer(
queue,
&self.camera,
0,
bytemuck::bytes_of(&SourceCamera::new(input.camera, input.frame_fog)),
);
self.culling.encode(
encoder,
device,
queue,
input.depth,
input.camera,
input.environment.collection,
timing,
);
let texture = wgpu::BindingResource::TextureView;
let fog = input.fog;
let resources = [
(0, texture(input.scene)),
(2, texture(input.output)),
(3, texture(input.normal)),
(4, texture(input.f0)),
(5, texture(input.depth)),
(6, self.camera.as_entire_binding()),
(7, texture(input.lookup_tables)),
(8, texture(input.environment.sky)),
(
10,
wgpu::BindingResource::Sampler(input.environment.sampler),
),
(12, input.environment.parameters.as_entire_binding()),
(13, texture(input.environment.material)),
(14, texture(&self.incident)),
(17, texture(input.anisotropy)),
(18, texture(input.environment.baked)),
(19, input.environment.collection.as_entire_binding()),
(21, self.culling.tiles.as_entire_binding()),
(22, texture(input.ambient_occlusion)),
(24, texture(input.ambient)),
(25, texture(fog.view)),
(26, wgpu::BindingResource::Sampler(fog.sampler)),
];
let group = self
.completion
.group
.get(device, "reflection source inputs", &resources);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("reflection source completion"),
timestamp_writes: timing.and_then(|t| t.compute_pass("reflection source completion")),
});
pass.set_pipeline(&self.completion.pipeline);
pass.set_bind_group(0, group, &[]);
let [width, height] = self.size;
pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
}
#[allow(clippy::too_many_arguments)]
pub fn compose(
&mut self,
encoder: &mut wgpu::CommandEncoder,
device: &wgpu::Device,
input: Inputs<'_>,
surface_depth: &wgpu::TextureView,
screen_space: &wgpu::TextureView,
world_space: Option<&wgpu::TextureView>,
timing: Option<&crate::timing::GpuTiming>,
) {
let world_space = world_space.unwrap_or(&self.no_world);
let texture = wgpu::BindingResource::TextureView;
let fog = input.fog;
let resources = [
(3, texture(input.normal)),
(4, texture(input.f0)),
(5, texture(input.depth)),
(6, self.camera.as_entire_binding()),
(7, texture(input.lookup_tables)),
(8, texture(input.environment.sky)),
(
10,
wgpu::BindingResource::Sampler(input.environment.sampler),
),
(12, input.environment.parameters.as_entire_binding()),
(13, texture(input.environment.material)),
(17, texture(input.anisotropy)),
(18, texture(input.environment.baked)),
(19, input.environment.collection.as_entire_binding()),
(20, texture(screen_space)),
(21, self.culling.tiles.as_entire_binding()),
(22, texture(input.ambient_occlusion)),
(23, texture(world_space)),
(24, texture(input.ambient)),
(25, texture(fog.view)),
(26, wgpu::BindingResource::Sampler(fog.sampler)),
(27, texture(surface_depth)),
];
let group = self.completion.compose_group.get(
device,
"screen-space reflection composition",
&resources,
);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("screen-space reflection composition"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: input.output,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
timestamp_writes: timing.and_then(|t| t.render_pass("reflection composition")),
..Default::default()
});
pass.set_pipeline(&self.completion.compose);
pass.set_bind_group(0, group, &[]);
pass.draw(0..3, 0..1);
}
}
#[cfg(test)]
pub(crate) fn mirrors() -> [crate::shading::layout_tests::Mirror; 2] {
use crate::shading::layout_tests::mirror;
[
mirror!(
"reflection_source",
"SourceCamera",
SourceCamera,
[inverse, eye, fog, forward, flags]
),
mirror!(
"reflection_source",
"ReflectionEnvironment",
ReflectionEnvironment,
[yaw, intensity, fade, traced]
),
]
}
#[cfg(test)]
pub(crate) fn constants() -> [crate::shading::layout_tests::Constant; 1] {
use crate::shading::layout_tests::Constant;
[Constant::new(
"reflection_source",
"SOURCE_FOG",
naga::Literal::U32(SOURCE_FOG),
)]
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod incident_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod receiver_tests;