WIP shadowmapping

This commit is contained in:
Lauri Räsänen 2023-01-29 18:57:29 +02:00
parent 2fdae1a23a
commit ac67a3d4de
9 changed files with 270 additions and 122 deletions

17
res/shaders/depth.wgsl Normal file
View file

@ -0,0 +1,17 @@
#include globals.wgsl
@vertex
fn vs_main(
model: VertexInput,
instance: InstanceInput,
) -> @builtin(position) vec4<f32> {
let model_matrix = mat4x4<f32>(
instance.model_matrix_0,
instance.model_matrix_1,
instance.model_matrix_2,
instance.model_matrix_3,
);
let world_position = model_matrix * vec4<f32>(model.position, 1.0);
return camera.proj * camera.view * world_position;
}

51
res/shaders/globals.wgsl Normal file
View file

@ -0,0 +1,51 @@
// Vertex shader
struct CameraUniform {
view: mat4x4<f32>,
proj: mat4x4<f32>,
position: vec4<f32>,
}
@group(0) @binding(0)
var<uniform> camera: CameraUniform;
struct Light {
position: vec3<f32>,
color: vec4<f32>,
}
@group(1) @binding(0)
var<uniform> light: Light;
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) tex_coords: vec2<f32>,
@location(2) normal: vec3<f32>,
@location(3) tangent: vec3<f32>,
@location(4) bitangent: vec3<f32>,
}
struct InstanceInput {
@location(5) model_matrix_0: vec4<f32>,
@location(6) model_matrix_1: vec4<f32>,
@location(7) model_matrix_2: vec4<f32>,
@location(8) model_matrix_3: vec4<f32>,
@location(9) normal_matrix_0: vec3<f32>,
@location(10) normal_matrix_1: vec3<f32>,
@location(11) normal_matrix_2: vec3<f32>,
}
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) tex_coords: vec2<f32>,
@location(1) tangent_position: vec3<f32>,
@location(2) tangent_light_position: vec3<f32>,
@location(3) tangent_view_position: vec3<f32>,
@location(4) world_position: vec3<f32>,
@location(5) light_local_position: vec4<f32>,
}
// Fragment shader
@group(1)@binding(1)
var t_light_depth: texture_depth_2d;
@group(1) @binding(2)
var s_light_depth: sampler_comparison;

View file

@ -1,43 +1,26 @@
// Vertex shader #include globals.wgsl
struct Camera { struct LightVertexInput {
view: mat4x4<f32>,
proj: mat4x4<f32>,
position: vec4<f32>,
}
@group(0) @binding(0)
var<uniform> camera: Camera;
struct Light {
position: vec3<f32>,
color: vec3<f32>,
}
@group(1) @binding(0)
var<uniform> light: Light;
struct VertexInput {
@location(0) position: vec3<f32>, @location(0) position: vec3<f32>,
}; };
struct VertexOutput { struct LightVertexOutput {
@builtin(position) clip_position: vec4<f32>, @builtin(position) clip_position: vec4<f32>,
@location(0) color: vec3<f32>, @location(0) color: vec3<f32>,
}; };
@vertex @vertex
fn vs_main( fn vs_main(
model: VertexInput, model: LightVertexInput,
) -> VertexOutput { ) -> LightVertexOutput {
let scale = 10.0; let scale = 10.0;
var out: VertexOutput; var out: LightVertexOutput;
out.clip_position = camera.proj * camera.view * vec4<f32>(model.position * scale + light.position, 1.0); out.clip_position = camera.proj * camera.view * vec4<f32>(model.position * scale + light.position, 1.0);
out.color = light.color; out.color = light.color.xyz;
return out; return out;
} }
// Fragment shader
@fragment @fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { fn fs_main(in: LightVertexOutput) -> @location(0) vec4<f32> {
return vec4<f32>(in.color, 1.0); return vec4<f32>(in.color, 1.0);
} }

View file

@ -1,50 +1,9 @@
#include constants.wgsl #include constants.wgsl
#include globals.wgsl
#include brdf.wgsl #include brdf.wgsl
// Vertex shader // Vertex shader
struct CameraUniform {
view: mat4x4<f32>,
proj: mat4x4<f32>,
position: vec4<f32>,
}
@group(1) @binding(0)
var<uniform> camera: CameraUniform;
struct Light {
position: vec3<f32>,
color: vec4<f32>,
}
@group(2) @binding(0)
var<uniform> light: Light;
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) tex_coords: vec2<f32>,
@location(2) normal: vec3<f32>,
@location(3) tangent: vec3<f32>,
@location(4) bitangent: vec3<f32>,
}
struct InstanceInput {
@location(5) model_matrix_0: vec4<f32>,
@location(6) model_matrix_1: vec4<f32>,
@location(7) model_matrix_2: vec4<f32>,
@location(8) model_matrix_3: vec4<f32>,
@location(9) normal_matrix_0: vec3<f32>,
@location(10) normal_matrix_1: vec3<f32>,
@location(11) normal_matrix_2: vec3<f32>,
}
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) tex_coords: vec2<f32>,
@location(1) tangent_position: vec3<f32>,
@location(2) tangent_light_position: vec3<f32>,
@location(3) tangent_view_position: vec3<f32>,
@location(4) world_position: vec3<f32>,
}
@vertex @vertex
fn vs_main( fn vs_main(
model: VertexInput, model: VertexInput,
@ -81,25 +40,26 @@ fn vs_main(
out.tangent_view_position = tangent_matrix * camera.position.xyz; out.tangent_view_position = tangent_matrix * camera.position.xyz;
out.world_position = world_position.xyz; out.world_position = world_position.xyz;
out.light_local_position = camera.proj * camera.view * world_position;
return out; return out;
} }
// Fragment shader // Fragment shader
@group(0) @binding(0) @group(2) @binding(0)
var t_diffuse: texture_2d<f32>; var t_diffuse: texture_2d<f32>;
@group(0)@binding(1) @group(2)@binding(1)
var s_diffuse: sampler; var s_diffuse: sampler;
@group(0)@binding(2) @group(2)@binding(2)
var t_normal: texture_2d<f32>; var t_normal: texture_2d<f32>;
@group(0) @binding(3) @group(2) @binding(3)
var s_normal: sampler; var s_normal: sampler;
@group(0)@binding(4) @group(2)@binding(4)
var t_roughness_metalness: texture_2d<f32>; var t_roughness_metalness: texture_2d<f32>;
@group(0) @binding(5) @group(2) @binding(5)
var s_roughness_metalness: sampler; var s_roughness_metalness: sampler;
@fragment @fragment
@ -109,7 +69,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
let object_normal: vec4<f32> = textureSample(t_normal, s_normal, in.tex_coords); let object_normal: vec4<f32> = textureSample(t_normal, s_normal, in.tex_coords);
let object_roughness_metalness: vec4<f32> = textureSample( let object_roughness_metalness: vec4<f32> = textureSample(
t_roughness_metalness, s_roughness_metalness, in.tex_coords); t_roughness_metalness, s_roughness_metalness, in.tex_coords);
// TODO: AO //let light_depth = textureSampleCompareLevel(t_light_depth, s_light_depth, in.light_local_position.xy, 1.0);
let albedo = object_color.xyz; let albedo = object_color.xyz;
// TODO: pass factors to shader // TODO: pass factors to shader

View file

@ -7,17 +7,17 @@ pub struct Camera {
pub position: cgmath::Point3<f32>, pub position: cgmath::Point3<f32>,
pub pitch: f32, pub pitch: f32,
pub yaw: f32, pub yaw: f32,
pub projection: Projection, pub projection: PerspectiveProjection,
} }
pub struct Projection { pub struct PerspectiveProjection {
pub aspect: f32, pub aspect: f32,
pub fovy: f32, pub fovy: f32,
pub znear: f32, pub znear: f32,
pub zfar: f32, pub zfar: f32,
} }
impl Projection { impl PerspectiveProjection {
pub fn resize(&mut self, width: u32, height: u32) { pub fn resize(&mut self, width: u32, height: u32) {
self.aspect = width as f32 / height as f32; self.aspect = width as f32 / height as f32;
} }
@ -27,6 +27,35 @@ impl Projection {
} }
} }
pub struct OrthoProjection {
pub left: f32,
pub right: f32,
pub bottom: f32,
pub top: f32,
pub znear: f32,
pub zfar: f32,
}
impl OrthoProjection {
pub fn resize(&mut self, width: u32, height: u32) {
self.left = width as f32 * -0.5;
self.right = width as f32 * 0.5;
self.bottom = height as f32 * -0.5;
self.top = height as f32 * 0.5;
}
pub fn get_matrix(&self) -> cgmath::Matrix4<f32> {
cgmath::ortho(
self.left,
self.right,
self.bottom,
self.top,
self.znear,
self.zfar,
)
}
}
impl Camera { impl Camera {
pub fn new( pub fn new(
position: cgmath::Point3<f32>, position: cgmath::Point3<f32>,
@ -39,7 +68,7 @@ impl Camera {
position, position,
pitch, pitch,
yaw, yaw,
projection: Projection { projection: PerspectiveProjection {
aspect, aspect,
fovy, fovy,
znear: 0.1, znear: 0.1,

View file

@ -7,7 +7,7 @@ pub struct Material {
pub diffuse_texture: Texture, pub diffuse_texture: Texture,
pub normal_texture: Texture, pub normal_texture: Texture,
pub metallic_roughness_texture: Texture, pub metallic_roughness_texture: Texture,
pub metallic_factor: f32, // TODO pass to shader pub metallic_factor: f32, // TODO pass to shader
pub roughness_factor: f32, // TODO pass to shader pub roughness_factor: f32, // TODO pass to shader
pub bind_group: wgpu::BindGroup, pub bind_group: wgpu::BindGroup,
} }
@ -194,9 +194,9 @@ where
) { ) {
self.set_vertex_buffer(0, mesh.vertex_buffer.slice(..)); self.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
self.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32); self.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
self.set_bind_group(0, &material.bind_group, &[]); self.set_bind_group(0, camera_bind_group, &[]);
self.set_bind_group(1, camera_bind_group, &[]); self.set_bind_group(1, light_bind_group, &[]);
self.set_bind_group(2, light_bind_group, &[]); self.set_bind_group(2, &material.bind_group, &[]);
self.draw_indexed(0..mesh.num_elements, 0, instances); self.draw_indexed(0..mesh.num_elements, 0, instances);
} }

View file

@ -14,17 +14,18 @@ impl RenderPass {
bind_group_layouts: &[&BindGroupLayout], bind_group_layouts: &[&BindGroupLayout],
push_constant_ranges: &[PushConstantRange], push_constant_ranges: &[PushConstantRange],
shader_name: &str, shader_name: &str,
color_format: TextureFormat, color_format: Option<TextureFormat>,
depth_format: Option<TextureFormat>, depth_format: Option<TextureFormat>,
vertex_layouts: &[VertexBufferLayout], vertex_layouts: &[VertexBufferLayout],
label: &str,
) -> Self { ) -> Self {
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Pipeline Layout"), label: Some((label.to_owned() + " pipeline Layout").as_str()),
bind_group_layouts: bind_group_layouts, bind_group_layouts: bind_group_layouts,
push_constant_ranges: push_constant_ranges, push_constant_ranges: push_constant_ranges,
}); });
let shader = wgpu::ShaderModuleDescriptor { let shader = wgpu::ShaderModuleDescriptor {
label: Some("Shader"), label: Some(shader_name),
source: preprocess_wgsl(shader_name), source: preprocess_wgsl(shader_name),
}; };
let pipeline = Self::create_render_pipeline( let pipeline = Self::create_render_pipeline(
@ -34,6 +35,7 @@ impl RenderPass {
depth_format, depth_format,
vertex_layouts, vertex_layouts,
shader, shader,
label,
); );
Self { pipeline } Self { pipeline }
@ -42,33 +44,40 @@ impl RenderPass {
fn create_render_pipeline( fn create_render_pipeline(
device: &wgpu::Device, device: &wgpu::Device,
layout: &wgpu::PipelineLayout, layout: &wgpu::PipelineLayout,
color_format: wgpu::TextureFormat, color_format: Option<wgpu::TextureFormat>,
depth_format: Option<wgpu::TextureFormat>, depth_format: Option<wgpu::TextureFormat>,
vertex_layouts: &[wgpu::VertexBufferLayout], vertex_layouts: &[wgpu::VertexBufferLayout],
shader: wgpu::ShaderModuleDescriptor, shader: wgpu::ShaderModuleDescriptor,
label: &str,
) -> wgpu::RenderPipeline { ) -> wgpu::RenderPipeline {
let shader = device.create_shader_module(shader); let shader = device.create_shader_module(shader);
let fragment_targets = &[Some(wgpu::ColorTargetState {
format: color_format.unwrap_or(wgpu::TextureFormat::Bgra8Unorm),
blend: Some(wgpu::BlendState {
alpha: wgpu::BlendComponent::REPLACE,
color: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})];
let fragment = match color_format {
Some(..) => Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: fragment_targets,
}),
None => None,
};
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"), label: Some((label.to_owned() + " pipeline Layout").as_str()),
layout: Some(layout), layout: Some(layout),
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
entry_point: "vs_main", entry_point: "vs_main",
buffers: vertex_layouts, buffers: vertex_layouts,
}, },
fragment: Some(wgpu::FragmentState { fragment: fragment,
module: &shader,
entry_point: "fs_main",
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState {
alpha: wgpu::BlendComponent::REPLACE,
color: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState { primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList, topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None, strip_index_format: None,

View file

@ -34,6 +34,8 @@ pub struct State {
light_buffer: wgpu::Buffer, light_buffer: wgpu::Buffer,
light_debug_pass: RenderPass, light_debug_pass: RenderPass,
light_bind_group: wgpu::BindGroup, light_bind_group: wgpu::BindGroup,
light_depth_pass: RenderPass,
light_depth_texture: Texture,
} }
impl State { impl State {
@ -121,6 +123,19 @@ impl State {
let camera_controller = CameraController::new(400.0, 2.0); let camera_controller = CameraController::new(400.0, 2.0);
let depth_texture = Texture::create_depth_texture(
&device,
&config,
"depth_texture",
Some(wgpu::CompareFunction::LessEqual),
);
let light_depth_texture = Texture::create_depth_texture(
&device,
&config,
"light_depth_texture",
Some(wgpu::CompareFunction::LessEqual),
);
let light_uniform = LightUniform::new([100.0, 60.0, 0.0], [1.0, 1.0, 1.0, 200000.0]); let light_uniform = LightUniform::new([100.0, 60.0, 0.0], [1.0, 1.0, 1.0, 200000.0]);
// We'll want to update our lights position, so we use COPY_DST // We'll want to update our lights position, so we use COPY_DST
@ -132,26 +147,55 @@ impl State {
let light_bind_group_layout = let light_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry { entries: &[
binding: 0, wgpu::BindGroupLayoutEntry {
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT, binding: 0,
ty: wgpu::BindingType::Buffer { visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BufferBindingType::Uniform, ty: wgpu::BindingType::Buffer {
has_dynamic_offset: false, ty: wgpu::BufferBindingType::Uniform,
min_binding_size: None, has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}, },
count: None, // depth
}], wgpu::BindGroupLayoutEntry {
label: None, binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Depth,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
count: None,
},
],
label: Some("Light Bind Group Layout"),
}); });
let light_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let light_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &light_bind_group_layout, layout: &light_bind_group_layout,
entries: &[wgpu::BindGroupEntry { entries: &[
binding: 0, wgpu::BindGroupEntry {
resource: light_buffer.as_entire_binding(), binding: 0,
}], resource: light_buffer.as_entire_binding(),
label: None, },
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&light_depth_texture.view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&light_depth_texture.sampler),
},
],
label: Some("Light Bind Group"),
}); });
surface.configure(&device, &config); surface.configure(&device, &config);
@ -244,20 +288,19 @@ impl State {
usage: wgpu::BufferUsages::VERTEX, usage: wgpu::BufferUsages::VERTEX,
}); });
let depth_texture = Texture::create_depth_texture(&device, &config, "depth_texture");
let geometry_pass = RenderPass::new( let geometry_pass = RenderPass::new(
&device, &device,
&[ &[
&texture_bind_group_layout,
&camera_bind_group_layout, &camera_bind_group_layout,
&light_bind_group_layout, &light_bind_group_layout,
&texture_bind_group_layout,
], ],
&[], &[],
"pbr.wgsl", "pbr.wgsl",
config.format, Some(config.format),
Some(Texture::DEPTH_FORMAT), Some(Texture::DEPTH_FORMAT),
&[ModelVertex::desc(), InstanceRaw::desc()], &[ModelVertex::desc(), InstanceRaw::desc()],
"geometry pass",
); );
let light_debug_pass = RenderPass::new( let light_debug_pass = RenderPass::new(
@ -265,9 +308,25 @@ impl State {
&[&camera_bind_group_layout, &light_bind_group_layout], &[&camera_bind_group_layout, &light_bind_group_layout],
&[], &[],
"light.wgsl", "light.wgsl",
config.format, Some(config.format),
Some(Texture::DEPTH_FORMAT), Some(Texture::DEPTH_FORMAT),
&[ModelVertex::desc()], &[ModelVertex::desc()],
"light debug pass",
);
let light_depth_pass = RenderPass::new(
&device,
&[
&camera_bind_group_layout,
&light_bind_group_layout,
&texture_bind_group_layout,
],
&[],
"depth.wgsl",
None,
Some(Texture::DEPTH_FORMAT),
&[ModelVertex::desc(), InstanceRaw::desc()],
"light depth pass",
); );
Self { Self {
@ -291,6 +350,8 @@ impl State {
light_buffer, light_buffer,
light_debug_pass, light_debug_pass,
light_bind_group, light_bind_group,
light_depth_pass,
light_depth_texture,
} }
} }
@ -303,8 +364,18 @@ impl State {
self.camera self.camera
.projection .projection
.resize(new_size.width, new_size.height); .resize(new_size.width, new_size.height);
self.depth_texture = self.depth_texture = Texture::create_depth_texture(
Texture::create_depth_texture(&self.device, &self.config, "depth_texture"); &self.device,
&self.config,
"depth_texture",
Some(wgpu::CompareFunction::LessEqual),
);
self.light_depth_texture = Texture::create_depth_texture(
&self.device,
&self.config,
"light_depth_texture",
Some(wgpu::CompareFunction::LessEqual),
);
} }
} }
@ -351,6 +422,33 @@ impl State {
label: Some("Render Encoder"), label: Some("Render Encoder"),
}); });
/*
{
let mut light_depth_render_pass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Light Depth Render Pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.light_depth_texture.view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: true,
}),
stencil_ops: None,
}),
});
light_depth_render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
light_depth_render_pass.set_pipeline(&self.light_depth_pass.pipeline);
light_depth_render_pass.draw_model_instanced(
&self.model,
0..self.instances.len() as u32,
&self.camera_bind_group, // TODO light projection
&self.light_bind_group, // TODO remove
);
}
*/
{ {
let mut geom_render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let mut geom_render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Geometry Render Pass"), label: Some("Geometry Render Pass"),

View file

@ -13,6 +13,7 @@ impl Texture {
device: &wgpu::Device, device: &wgpu::Device,
config: &wgpu::SurfaceConfiguration, config: &wgpu::SurfaceConfiguration,
label: &str, label: &str,
compare: Option<wgpu::CompareFunction>,
) -> Self { ) -> Self {
let size = wgpu::Extent3d { let size = wgpu::Extent3d {
width: config.width, width: config.width,
@ -38,7 +39,7 @@ impl Texture {
mag_filter: wgpu::FilterMode::Linear, mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Nearest, mipmap_filter: wgpu::FilterMode::Nearest,
compare: Some(wgpu::CompareFunction::LessEqual), compare,
lod_min_clamp: -100.0, lod_min_clamp: -100.0,
lod_max_clamp: 100.0, lod_max_clamp: 100.0,
..Default::default() ..Default::default()