mirror of
https://github.com/bevyengine/bevy
synced 2024-11-24 21:53:07 +00:00
render resources refactor and normal forward rendering
This commit is contained in:
parent
c0f8ded062
commit
6a819a1884
12 changed files with 479 additions and 156 deletions
|
@ -15,3 +15,6 @@ zerocopy = "0.2"
|
|||
log = "0.4"
|
||||
env_logger = "0.7"
|
||||
rand = "0.7.2"
|
||||
|
||||
[profile.release]
|
||||
debug = true
|
|
@ -109,9 +109,9 @@ fn build_spawner_system(world: &mut World) -> Box<dyn Schedulable> {
|
|||
mesh_storage.get_named("cube").unwrap()
|
||||
};
|
||||
|
||||
let duration = 10000.0;
|
||||
let duration = 0.5;
|
||||
let mut elapsed = duration;
|
||||
let batch_size = 5;
|
||||
let batch_size = 100;
|
||||
|
||||
SystemBuilder::new("Spawner")
|
||||
.read_resource::<Time>()
|
||||
|
|
|
@ -8,8 +8,6 @@ use winit::{
|
|||
use zerocopy::AsBytes;
|
||||
use legion::prelude::*;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::rc::Rc;
|
||||
use std::mem;
|
||||
|
||||
use wgpu::{Surface, Device, Queue, SwapChain, SwapChainDescriptor};
|
||||
|
@ -27,37 +25,14 @@ pub struct Application
|
|||
pub swap_chain: SwapChain,
|
||||
pub swap_chain_descriptor: SwapChainDescriptor,
|
||||
pub scheduler: SystemScheduler<ApplicationStage>,
|
||||
pub render_resources: RenderResources,
|
||||
pub render_passes: Vec<Box<dyn Pass>>,
|
||||
}
|
||||
|
||||
impl Application {
|
||||
pub const MAX_LIGHTS: usize = 10;
|
||||
|
||||
fn add_default_passes(&mut self) {
|
||||
let light_uniform_size =
|
||||
(Self::MAX_LIGHTS * mem::size_of::<LightRaw>()) as wgpu::BufferAddress;
|
||||
|
||||
let local_bind_group_layout =
|
||||
Rc::new(self.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
bindings: &[wgpu::BindGroupLayoutBinding {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::UniformBuffer { dynamic: false },
|
||||
}],
|
||||
}));
|
||||
|
||||
let light_uniform_buffer = Arc::new(UniformBuffer {
|
||||
buffer: self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
size: light_uniform_size,
|
||||
usage: wgpu::BufferUsage::UNIFORM
|
||||
| wgpu::BufferUsage::COPY_SRC
|
||||
| wgpu::BufferUsage::COPY_DST,
|
||||
}),
|
||||
size: light_uniform_size,
|
||||
});
|
||||
|
||||
let vertex_size = mem::size_of::<Vertex>();
|
||||
let vb_desc = wgpu::VertexBufferDescriptor {
|
||||
let vertex_buffer_descriptor = wgpu::VertexBufferDescriptor {
|
||||
stride: vertex_size as wgpu::BufferAddress,
|
||||
step_mode: wgpu::InputStepMode::Vertex,
|
||||
attributes: &[
|
||||
|
@ -74,9 +49,11 @@ impl Application {
|
|||
],
|
||||
};
|
||||
|
||||
let shadow_pass = ShadowPass::new(&mut self.device, &mut self.world, light_uniform_buffer.clone(), vb_desc.clone(), local_bind_group_layout.clone(), Self::MAX_LIGHTS as u32);
|
||||
let forward_pass = ForwardPass::new(&mut self.device, &self.world, light_uniform_buffer.clone(), &shadow_pass, vb_desc, &local_bind_group_layout, &self.swap_chain_descriptor);
|
||||
self.render_passes.push(Box::new(shadow_pass));
|
||||
// let shadow_pass = ShadowPass::new(&mut self.device, &mut self.world, &self.render_resources, vertex_buffer_descriptor.clone());
|
||||
// let forward_shadow_pass = ForwardShadowPass::new(&mut self.device, &self.world, &self.render_resources, &shadow_pass, vertex_buffer_descriptor.clone(), &self.swap_chain_descriptor);
|
||||
let forward_pass = ForwardPass::new(&mut self.device, &self.world, &self.render_resources, vertex_buffer_descriptor, &self.swap_chain_descriptor);
|
||||
// self.render_passes.push(Box::new(shadow_pass));
|
||||
// self.render_passes.push(Box::new(forward_shadow_pass));
|
||||
self.render_passes.push(Box::new(forward_pass));
|
||||
}
|
||||
|
||||
|
@ -154,18 +131,44 @@ impl Application {
|
|||
);
|
||||
}
|
||||
|
||||
self.render_resources.update_lights(&self.device, &mut encoder, &mut self.world);
|
||||
|
||||
for mut material in <Write<Material>>::query().iter(&mut self.world) {
|
||||
if let None = material.bind_group {
|
||||
let material_uniform_size = mem::size_of::<MaterialUniforms>() as wgpu::BufferAddress;
|
||||
let uniform_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
size: material_uniform_size,
|
||||
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
|
||||
});
|
||||
|
||||
let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &self.render_resources.local_bind_group_layout,
|
||||
bindings: &[wgpu::Binding {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer {
|
||||
buffer: &uniform_buf,
|
||||
range: 0 .. material_uniform_size,
|
||||
},
|
||||
}],
|
||||
});
|
||||
|
||||
material.bind_group = Some(bind_group);
|
||||
material.uniform_buf = Some(uniform_buf);
|
||||
}
|
||||
}
|
||||
|
||||
let temp_buf = temp_buf_data.finish();
|
||||
|
||||
for pass in self.render_passes.iter_mut() {
|
||||
pass.render(&mut self.device, &mut frame, &mut encoder, &mut self.world);
|
||||
pass.render(&mut self.device, &mut frame, &mut encoder, &mut self.world, &self.render_resources);
|
||||
}
|
||||
|
||||
// TODO: this should happen before rendering
|
||||
for (i, (entity, _)) in entities.iter(&mut self.world).enumerate() {
|
||||
for (i, (material, _)) in entities.iter(&mut self.world).enumerate() {
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&temp_buf,
|
||||
(i * size) as wgpu::BufferAddress,
|
||||
entity.uniform_buf.as_ref().unwrap(),
|
||||
material.uniform_buf.as_ref().unwrap(),
|
||||
0,
|
||||
size as wgpu::BufferAddress,
|
||||
);
|
||||
|
@ -189,7 +192,7 @@ impl Application {
|
|||
)
|
||||
.unwrap();
|
||||
|
||||
let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
let (mut device, queue) = adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
extensions: wgpu::Extensions {
|
||||
anisotropic_filtering: false,
|
||||
},
|
||||
|
@ -217,6 +220,8 @@ impl Application {
|
|||
|
||||
world.resources.insert(Time::new());
|
||||
|
||||
let render_resources = RenderResources::new(&mut device, 10);
|
||||
|
||||
log::info!("Initializing the example...");
|
||||
let mut app = Application {
|
||||
universe,
|
||||
|
@ -227,6 +232,7 @@ impl Application {
|
|||
queue,
|
||||
swap_chain,
|
||||
swap_chain_descriptor,
|
||||
render_resources,
|
||||
scheduler: system_scheduler,
|
||||
render_passes: Vec::new(),
|
||||
};
|
||||
|
|
|
@ -20,28 +20,12 @@ layout(set = 0, binding = 0) uniform Globals {
|
|||
layout(set = 0, binding = 1) uniform Lights {
|
||||
Light u_Lights[MAX_LIGHTS];
|
||||
};
|
||||
layout(set = 0, binding = 2) uniform texture2DArray t_Shadow;
|
||||
layout(set = 0, binding = 3) uniform samplerShadow s_Shadow;
|
||||
|
||||
layout(set = 1, binding = 0) uniform Entity {
|
||||
mat4 u_World;
|
||||
vec4 u_Color;
|
||||
};
|
||||
|
||||
float fetch_shadow(int light_id, vec4 homogeneous_coords) {
|
||||
if (homogeneous_coords.w <= 0.0) {
|
||||
return 1.0;
|
||||
}
|
||||
// compute texture coordinates for shadow lookup
|
||||
vec4 light_local = vec4(
|
||||
(homogeneous_coords.xy/homogeneous_coords.w + 1.0) / 2.0,
|
||||
light_id,
|
||||
homogeneous_coords.z / homogeneous_coords.w
|
||||
);
|
||||
// do the lookup, using HW PCF and comparison
|
||||
return texture(sampler2DArrayShadow(t_Shadow, s_Shadow), light_local);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 normal = normalize(v_Normal);
|
||||
vec3 ambient = vec3(0.05, 0.05, 0.05);
|
||||
|
@ -49,13 +33,11 @@ void main() {
|
|||
vec3 color = ambient;
|
||||
for (int i=0; i<int(u_NumLights.x) && i<MAX_LIGHTS; ++i) {
|
||||
Light light = u_Lights[i];
|
||||
// project into the light space
|
||||
float shadow = fetch_shadow(i, light.proj * v_Position);
|
||||
// compute Lambertian diffuse term
|
||||
vec3 light_dir = normalize(light.pos.xyz - v_Position.xyz);
|
||||
float diffuse = max(0.0, dot(normal, light_dir));
|
||||
// add light contribution
|
||||
color += shadow * diffuse * light.color.xyz;
|
||||
color += diffuse * light.color.xyz;
|
||||
}
|
||||
// multiply the light by material color
|
||||
o_Target = vec4(color, 1.0) * u_Color;
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
use crate::{render::*, asset::*, render::mesh::*, math};
|
||||
use legion::prelude::*;
|
||||
use std::{mem, sync::Arc};
|
||||
use std::mem;
|
||||
use zerocopy::{AsBytes, FromBytes};
|
||||
use wgpu::{Buffer, CommandEncoder, Device, BindGroupLayout, VertexBufferDescriptor, SwapChainDescriptor, SwapChainOutput};
|
||||
use wgpu::{Buffer, CommandEncoder, Device, VertexBufferDescriptor, SwapChainDescriptor, SwapChainOutput};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, AsBytes, FromBytes)]
|
||||
|
@ -15,12 +15,11 @@ pub struct ForwardPass {
|
|||
pub pipeline: wgpu::RenderPipeline,
|
||||
pub bind_group: wgpu::BindGroup,
|
||||
pub forward_uniform_buffer: wgpu::Buffer,
|
||||
pub light_uniform_buffer: Arc::<UniformBuffer>,
|
||||
pub depth_texture: wgpu::TextureView,
|
||||
}
|
||||
|
||||
impl Pass for ForwardPass {
|
||||
fn render(&mut self, device: &Device, frame: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World) {
|
||||
fn render(&mut self, device: &Device, frame: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World, _: &RenderResources) {
|
||||
let mut mesh_query = <(Read<Material>, Read<Handle<Mesh>>)>::query();
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
|
||||
|
@ -49,15 +48,29 @@ impl Pass for ForwardPass {
|
|||
pass.set_bind_group(0, &self.bind_group, &[]);
|
||||
|
||||
let mut mesh_storage = world.resources.get_mut::<AssetStorage<Mesh, MeshType>>().unwrap();
|
||||
let mut last_mesh_id = None;
|
||||
for (entity, mesh) in mesh_query.iter_immutable(world) {
|
||||
if let Some(mesh_asset) = mesh_storage.get(*mesh.id.read().unwrap()) {
|
||||
mesh_asset.setup_buffers(device);
|
||||
pass.set_bind_group(1, entity.bind_group.as_ref().unwrap(), &[]);
|
||||
pass.set_index_buffer(mesh_asset.index_buffer.as_ref().unwrap(), 0);
|
||||
pass.set_vertex_buffers(0, &[(&mesh_asset.vertex_buffer.as_ref().unwrap(), 0)]);
|
||||
pass.draw_indexed(0 .. mesh_asset.indices.len() as u32, 0, 0 .. 1);
|
||||
let current_mesh_id = *mesh.id.read().unwrap();
|
||||
|
||||
let mut should_load_mesh = last_mesh_id == None;
|
||||
if let Some(last) = last_mesh_id {
|
||||
should_load_mesh = last != current_mesh_id;
|
||||
}
|
||||
|
||||
if should_load_mesh {
|
||||
if let Some(mesh_asset) = mesh_storage.get(*mesh.id.read().unwrap()) {
|
||||
mesh_asset.setup_buffers(device);
|
||||
pass.set_index_buffer(mesh_asset.index_buffer.as_ref().unwrap(), 0);
|
||||
pass.set_vertex_buffers(0, &[(&mesh_asset.vertex_buffer.as_ref().unwrap(), 0)]);
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(ref mesh_asset) = mesh_storage.get(*mesh.id.read().unwrap()) {
|
||||
pass.set_bind_group(1, entity.bind_group.as_ref().unwrap(), &[]);
|
||||
pass.draw_indexed(0 .. mesh_asset.indices.len() as u32, 0, 0 .. 1);
|
||||
};
|
||||
|
||||
last_mesh_id = Some(current_mesh_id);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -73,7 +86,7 @@ impl Pass for ForwardPass {
|
|||
impl ForwardPass {
|
||||
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
|
||||
|
||||
pub fn new(device: &Device, world: &World, light_uniform_buffer: Arc::<UniformBuffer>, shadow_pass: &shadow::ShadowPass, vertex_buffer_descriptor: VertexBufferDescriptor, local_bind_group_layout: &BindGroupLayout, swap_chain_descriptor: &SwapChainDescriptor) -> ForwardPass {
|
||||
pub fn new(device: &Device, world: &World, render_resources: &RenderResources, vertex_buffer_descriptor: VertexBufferDescriptor, swap_chain_descriptor: &SwapChainDescriptor) -> Self {
|
||||
let vs_bytes = shader::load_glsl(
|
||||
include_str!("forward.vert"),
|
||||
shader::ShaderStage::Vertex,
|
||||
|
@ -95,20 +108,7 @@ impl ForwardPass {
|
|||
binding: 1, // lights
|
||||
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::UniformBuffer { dynamic: false },
|
||||
},
|
||||
wgpu::BindGroupLayoutBinding {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::SampledTexture {
|
||||
multisampled: false,
|
||||
dimension: wgpu::TextureViewDimension::D2Array,
|
||||
},
|
||||
},
|
||||
wgpu::BindGroupLayoutBinding {
|
||||
binding: 3,
|
||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler,
|
||||
},
|
||||
}
|
||||
],
|
||||
});
|
||||
|
||||
|
@ -138,24 +138,15 @@ impl ForwardPass {
|
|||
wgpu::Binding {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Buffer {
|
||||
buffer: &light_uniform_buffer.buffer,
|
||||
range: 0 .. light_uniform_buffer.size,
|
||||
buffer: &render_resources.light_uniform_buffer.buffer,
|
||||
range: 0 .. render_resources.light_uniform_buffer.size,
|
||||
},
|
||||
},
|
||||
wgpu::Binding {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::TextureView(&shadow_pass.shadow_view),
|
||||
},
|
||||
wgpu::Binding {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::Sampler(&shadow_pass.shadow_sampler),
|
||||
},
|
||||
}
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
bind_group_layouts: &[&bind_group_layout, local_bind_group_layout],
|
||||
bind_group_layouts: &[&bind_group_layout, &render_resources.local_bind_group_layout],
|
||||
});
|
||||
|
||||
let vs_module = device.create_shader_module(&vs_bytes);
|
||||
|
@ -207,7 +198,6 @@ impl ForwardPass {
|
|||
pipeline,
|
||||
bind_group,
|
||||
forward_uniform_buffer,
|
||||
light_uniform_buffer,
|
||||
depth_texture: Self::get_depth_texture(device, swap_chain_descriptor)
|
||||
}
|
||||
}
|
||||
|
|
62
src/render/forward_shadow/forward_shadow.frag
Normal file
62
src/render/forward_shadow/forward_shadow.frag
Normal file
|
@ -0,0 +1,62 @@
|
|||
#version 450
|
||||
|
||||
const int MAX_LIGHTS = 10;
|
||||
|
||||
layout(location = 0) in vec3 v_Normal;
|
||||
layout(location = 1) in vec4 v_Position;
|
||||
|
||||
layout(location = 0) out vec4 o_Target;
|
||||
|
||||
struct Light {
|
||||
mat4 proj;
|
||||
vec4 pos;
|
||||
vec4 color;
|
||||
};
|
||||
|
||||
layout(set = 0, binding = 0) uniform Globals {
|
||||
mat4 u_ViewProj;
|
||||
uvec4 u_NumLights;
|
||||
};
|
||||
layout(set = 0, binding = 1) uniform Lights {
|
||||
Light u_Lights[MAX_LIGHTS];
|
||||
};
|
||||
layout(set = 0, binding = 2) uniform texture2DArray t_Shadow;
|
||||
layout(set = 0, binding = 3) uniform samplerShadow s_Shadow;
|
||||
|
||||
layout(set = 1, binding = 0) uniform Entity {
|
||||
mat4 u_World;
|
||||
vec4 u_Color;
|
||||
};
|
||||
|
||||
float fetch_shadow(int light_id, vec4 homogeneous_coords) {
|
||||
if (homogeneous_coords.w <= 0.0) {
|
||||
return 1.0;
|
||||
}
|
||||
// compute texture coordinates for shadow lookup
|
||||
vec4 light_local = vec4(
|
||||
(homogeneous_coords.xy/homogeneous_coords.w + 1.0) / 2.0,
|
||||
light_id,
|
||||
homogeneous_coords.z / homogeneous_coords.w
|
||||
);
|
||||
// do the lookup, using HW PCF and comparison
|
||||
return texture(sampler2DArrayShadow(t_Shadow, s_Shadow), light_local);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 normal = normalize(v_Normal);
|
||||
vec3 ambient = vec3(0.05, 0.05, 0.05);
|
||||
// accumulate color
|
||||
vec3 color = ambient;
|
||||
for (int i=0; i<int(u_NumLights.x) && i<MAX_LIGHTS; ++i) {
|
||||
Light light = u_Lights[i];
|
||||
// project into the light space
|
||||
float shadow = fetch_shadow(i, light.proj * v_Position);
|
||||
// compute Lambertian diffuse term
|
||||
vec3 light_dir = normalize(light.pos.xyz - v_Position.xyz);
|
||||
float diffuse = max(0.0, dot(normal, light_dir));
|
||||
// add light contribution
|
||||
color += shadow * diffuse * light.color.xyz;
|
||||
}
|
||||
// multiply the light by material color
|
||||
o_Target = vec4(color, 1.0) * u_Color;
|
||||
}
|
22
src/render/forward_shadow/forward_shadow.vert
Normal file
22
src/render/forward_shadow/forward_shadow.vert
Normal file
|
@ -0,0 +1,22 @@
|
|||
#version 450
|
||||
|
||||
layout(location = 0) in vec4 a_Pos;
|
||||
layout(location = 1) in vec4 a_Normal;
|
||||
|
||||
layout(location = 0) out vec3 v_Normal;
|
||||
layout(location = 1) out vec4 v_Position;
|
||||
|
||||
layout(set = 0, binding = 0) uniform Globals {
|
||||
mat4 u_ViewProj;
|
||||
uvec4 u_NumLights;
|
||||
};
|
||||
layout(set = 1, binding = 0) uniform Entity {
|
||||
mat4 u_World;
|
||||
vec4 u_Color;
|
||||
};
|
||||
|
||||
void main() {
|
||||
v_Normal = mat3(u_World) * vec3(a_Normal.xyz);
|
||||
v_Position = u_World * vec4(a_Pos);
|
||||
gl_Position = u_ViewProj * v_Position;
|
||||
}
|
230
src/render/forward_shadow/mod.rs
Normal file
230
src/render/forward_shadow/mod.rs
Normal file
|
@ -0,0 +1,230 @@
|
|||
use crate::{render::*, asset::*, render::mesh::*, math};
|
||||
use legion::prelude::*;
|
||||
use std::mem;
|
||||
use zerocopy::{AsBytes, FromBytes};
|
||||
use wgpu::{Buffer, CommandEncoder, Device, VertexBufferDescriptor, SwapChainDescriptor, SwapChainOutput};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, AsBytes, FromBytes)]
|
||||
pub struct ForwardUniforms {
|
||||
pub proj: [[f32; 4]; 4],
|
||||
pub num_lights: [u32; 4],
|
||||
}
|
||||
|
||||
pub struct ForwardShadowPass {
|
||||
pub pipeline: wgpu::RenderPipeline,
|
||||
pub bind_group: wgpu::BindGroup,
|
||||
pub forward_uniform_buffer: wgpu::Buffer,
|
||||
pub depth_texture: wgpu::TextureView,
|
||||
}
|
||||
|
||||
impl Pass for ForwardShadowPass {
|
||||
fn render(&mut self, device: &Device, frame: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World, _: &RenderResources) {
|
||||
let mut mesh_query = <(Read<Material>, Read<Handle<Mesh>>)>::query();
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
|
||||
attachment: &frame.view,
|
||||
resolve_target: None,
|
||||
load_op: wgpu::LoadOp::Clear,
|
||||
store_op: wgpu::StoreOp::Store,
|
||||
clear_color: wgpu::Color {
|
||||
r: 0.3,
|
||||
g: 0.4,
|
||||
b: 0.5,
|
||||
a: 1.0,
|
||||
},
|
||||
}],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
|
||||
attachment: &self.depth_texture,
|
||||
depth_load_op: wgpu::LoadOp::Clear,
|
||||
depth_store_op: wgpu::StoreOp::Store,
|
||||
stencil_load_op: wgpu::LoadOp::Clear,
|
||||
stencil_store_op: wgpu::StoreOp::Store,
|
||||
clear_depth: 1.0,
|
||||
clear_stencil: 0,
|
||||
}),
|
||||
});
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, &self.bind_group, &[]);
|
||||
|
||||
let mut mesh_storage = world.resources.get_mut::<AssetStorage<Mesh, MeshType>>().unwrap();
|
||||
for (entity, mesh) in mesh_query.iter_immutable(world) {
|
||||
if let Some(mesh_asset) = mesh_storage.get(*mesh.id.read().unwrap()) {
|
||||
mesh_asset.setup_buffers(device);
|
||||
pass.set_bind_group(1, entity.bind_group.as_ref().unwrap(), &[]);
|
||||
pass.set_index_buffer(mesh_asset.index_buffer.as_ref().unwrap(), 0);
|
||||
pass.set_vertex_buffers(0, &[(&mesh_asset.vertex_buffer.as_ref().unwrap(), 0)]);
|
||||
pass.draw_indexed(0 .. mesh_asset.indices.len() as u32, 0, 0 .. 1);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn resize(&mut self, device: &Device, frame: &SwapChainDescriptor) {
|
||||
self.depth_texture = Self::get_depth_texture(device, frame);
|
||||
}
|
||||
|
||||
fn get_camera_uniform_buffer(&self) -> Option<&Buffer> {
|
||||
Some(&self.forward_uniform_buffer)
|
||||
}
|
||||
}
|
||||
|
||||
impl ForwardShadowPass {
|
||||
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
|
||||
|
||||
pub fn new(device: &Device, world: &World, render_resources: &RenderResources, shadow_pass: &shadow::ShadowPass, vertex_buffer_descriptor: VertexBufferDescriptor, swap_chain_descriptor: &SwapChainDescriptor) -> Self {
|
||||
let vs_bytes = shader::load_glsl(
|
||||
include_str!("forward_shadow.vert"),
|
||||
shader::ShaderStage::Vertex,
|
||||
);
|
||||
let fs_bytes = shader::load_glsl(
|
||||
include_str!("forward_shadow.frag"),
|
||||
shader::ShaderStage::Fragment,
|
||||
);
|
||||
|
||||
let bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
bindings: &[
|
||||
wgpu::BindGroupLayoutBinding {
|
||||
binding: 0, // global
|
||||
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::UniformBuffer { dynamic: false },
|
||||
},
|
||||
wgpu::BindGroupLayoutBinding {
|
||||
binding: 1, // lights
|
||||
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::UniformBuffer { dynamic: false },
|
||||
},
|
||||
wgpu::BindGroupLayoutBinding {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::SampledTexture {
|
||||
multisampled: false,
|
||||
dimension: wgpu::TextureViewDimension::D2Array,
|
||||
},
|
||||
},
|
||||
wgpu::BindGroupLayoutBinding {
|
||||
binding: 3,
|
||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let light_count = <Read<Light>>::query().iter_immutable(world).count();
|
||||
let forward_uniforms = ForwardUniforms {
|
||||
proj: math::Mat4::identity().to_cols_array_2d(),
|
||||
num_lights: [light_count as u32, 0, 0, 0],
|
||||
};
|
||||
|
||||
let uniform_size = mem::size_of::<ForwardUniforms>() as wgpu::BufferAddress;
|
||||
let forward_uniform_buffer = device.create_buffer_with_data(
|
||||
forward_uniforms.as_bytes(),
|
||||
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
|
||||
);
|
||||
|
||||
// Create bind group
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &bind_group_layout,
|
||||
bindings: &[
|
||||
wgpu::Binding {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer {
|
||||
buffer: &forward_uniform_buffer,
|
||||
range: 0 .. uniform_size,
|
||||
},
|
||||
},
|
||||
wgpu::Binding {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Buffer {
|
||||
buffer: &render_resources.light_uniform_buffer.buffer,
|
||||
range: 0 .. render_resources.light_uniform_buffer.size,
|
||||
},
|
||||
},
|
||||
wgpu::Binding {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::TextureView(&shadow_pass.shadow_view),
|
||||
},
|
||||
wgpu::Binding {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::Sampler(&shadow_pass.shadow_sampler),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
bind_group_layouts: &[&bind_group_layout, &render_resources.local_bind_group_layout],
|
||||
});
|
||||
|
||||
let vs_module = device.create_shader_module(&vs_bytes);
|
||||
let fs_module = device.create_shader_module(&fs_bytes);
|
||||
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
layout: &pipeline_layout,
|
||||
vertex_stage: wgpu::ProgrammableStageDescriptor {
|
||||
module: &vs_module,
|
||||
entry_point: "main",
|
||||
},
|
||||
fragment_stage: Some(wgpu::ProgrammableStageDescriptor {
|
||||
module: &fs_module,
|
||||
entry_point: "main",
|
||||
}),
|
||||
rasterization_state: Some(wgpu::RasterizationStateDescriptor {
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: wgpu::CullMode::Back,
|
||||
depth_bias: 0,
|
||||
depth_bias_slope_scale: 0.0,
|
||||
depth_bias_clamp: 0.0,
|
||||
}),
|
||||
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
color_states: &[
|
||||
wgpu::ColorStateDescriptor {
|
||||
format: swap_chain_descriptor.format,
|
||||
color_blend: wgpu::BlendDescriptor::REPLACE,
|
||||
alpha_blend: wgpu::BlendDescriptor::REPLACE,
|
||||
write_mask: wgpu::ColorWrite::ALL,
|
||||
},
|
||||
],
|
||||
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
|
||||
format: Self::DEPTH_FORMAT,
|
||||
depth_write_enabled: true,
|
||||
depth_compare: wgpu::CompareFunction::Less,
|
||||
stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE,
|
||||
stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE,
|
||||
stencil_read_mask: 0,
|
||||
stencil_write_mask: 0,
|
||||
}),
|
||||
index_format: wgpu::IndexFormat::Uint16,
|
||||
vertex_buffers: &[vertex_buffer_descriptor],
|
||||
sample_count: 1,
|
||||
sample_mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
});
|
||||
|
||||
ForwardShadowPass {
|
||||
pipeline,
|
||||
bind_group,
|
||||
forward_uniform_buffer,
|
||||
depth_texture: Self::get_depth_texture(device, swap_chain_descriptor)
|
||||
}
|
||||
}
|
||||
|
||||
fn get_depth_texture(device: &Device, swap_chain_descriptor: &SwapChainDescriptor) -> wgpu::TextureView {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
size: wgpu::Extent3d {
|
||||
width: swap_chain_descriptor.width,
|
||||
height: swap_chain_descriptor.height,
|
||||
depth: 1,
|
||||
},
|
||||
array_layer_count: 1,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: Self::DEPTH_FORMAT,
|
||||
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
|
||||
});
|
||||
|
||||
texture.create_default_view()
|
||||
}
|
||||
}
|
||||
|
|
@ -2,11 +2,14 @@ pub mod camera;
|
|||
pub mod shader;
|
||||
pub mod mesh;
|
||||
mod forward;
|
||||
mod forward_shadow;
|
||||
mod shadow;
|
||||
mod light;
|
||||
mod pass;
|
||||
mod material;
|
||||
mod render_resources;
|
||||
|
||||
pub use forward_shadow::{ForwardShadowPass};
|
||||
pub use forward::{ForwardPass, ForwardUniforms};
|
||||
pub use shadow::ShadowPass;
|
||||
pub use light::*;
|
||||
|
@ -15,6 +18,7 @@ pub use pass::*;
|
|||
pub use material::*;
|
||||
pub use mesh::*;
|
||||
pub use camera::*;
|
||||
pub use render_resources::RenderResources;
|
||||
|
||||
pub struct UniformBuffer {
|
||||
pub buffer: wgpu::Buffer,
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
use legion::world::World;
|
||||
use wgpu::{Buffer, CommandEncoder, Device, SwapChainDescriptor, SwapChainOutput};
|
||||
use crate::render::RenderResources;
|
||||
|
||||
pub trait Pass {
|
||||
fn render(&mut self, device: &Device, frame: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World);
|
||||
fn render(&mut self, device: &Device, frame: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World, render_resources: &RenderResources);
|
||||
fn resize(&mut self, device: &Device, frame: &SwapChainDescriptor);
|
||||
fn get_camera_uniform_buffer(&self) -> Option<&Buffer>;
|
||||
}
|
74
src/render/render_resources.rs
Normal file
74
src/render/render_resources.rs
Normal file
|
@ -0,0 +1,74 @@
|
|||
use crate::{render::*, LocalToWorld, Translation};
|
||||
|
||||
use legion::prelude::*;
|
||||
use std::sync::Arc;
|
||||
use std::rc::Rc;
|
||||
use std::mem;
|
||||
use zerocopy::AsBytes;
|
||||
|
||||
use wgpu::{BindGroupLayout, CommandEncoder, Device};
|
||||
|
||||
pub struct RenderResources {
|
||||
pub local_bind_group_layout: Rc<BindGroupLayout>,
|
||||
pub light_uniform_buffer: Arc<UniformBuffer>,
|
||||
pub lights_are_dirty: bool,
|
||||
pub max_lights: usize,
|
||||
}
|
||||
|
||||
impl RenderResources {
|
||||
pub fn new(device: &mut Device, max_lights: usize) -> RenderResources {
|
||||
let light_uniform_size =
|
||||
(max_lights * mem::size_of::<LightRaw>()) as wgpu::BufferAddress;
|
||||
|
||||
let local_bind_group_layout =
|
||||
Rc::new(device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
bindings: &[wgpu::BindGroupLayoutBinding {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::UniformBuffer { dynamic: false },
|
||||
}],
|
||||
}));
|
||||
|
||||
let light_uniform_buffer = Arc::new(UniformBuffer {
|
||||
buffer: device.create_buffer(&wgpu::BufferDescriptor {
|
||||
size: light_uniform_size,
|
||||
usage: wgpu::BufferUsage::UNIFORM
|
||||
| wgpu::BufferUsage::COPY_SRC
|
||||
| wgpu::BufferUsage::COPY_DST,
|
||||
}),
|
||||
size: light_uniform_size,
|
||||
});
|
||||
|
||||
RenderResources {
|
||||
local_bind_group_layout,
|
||||
light_uniform_buffer,
|
||||
lights_are_dirty: true,
|
||||
max_lights
|
||||
}
|
||||
}
|
||||
pub fn update_lights(&mut self, device: &Device, encoder: &mut CommandEncoder, world: &mut World) {
|
||||
if self.lights_are_dirty {
|
||||
let mut light_query = <(Read<Light>, Read<LocalToWorld>, Read<Translation>)>::query();
|
||||
let light_count = light_query.iter(world).count();
|
||||
|
||||
self.lights_are_dirty = false;
|
||||
let size = mem::size_of::<LightRaw>();
|
||||
let total_size = size * light_count;
|
||||
let temp_buf_data =
|
||||
device.create_buffer_mapped(total_size, wgpu::BufferUsage::COPY_SRC);
|
||||
for ((light, local_to_world, translation), slot) in light_query
|
||||
.iter(world)
|
||||
.zip(temp_buf_data.data.chunks_exact_mut(size))
|
||||
{
|
||||
slot.copy_from_slice(LightRaw::from(&light, &local_to_world.0, &translation).as_bytes());
|
||||
}
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&temp_buf_data.finish(),
|
||||
0,
|
||||
&self.light_uniform_buffer.buffer,
|
||||
0,
|
||||
total_size as wgpu::BufferAddress,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,8 +1,7 @@
|
|||
use crate::{render::*, asset::*, LocalToWorld, Translation};
|
||||
use wgpu::{BindGroupLayout, Buffer, CommandEncoder, Device, VertexBufferDescriptor, SwapChainOutput, SwapChainDescriptor};
|
||||
use wgpu::{Buffer, CommandEncoder, Device, VertexBufferDescriptor, SwapChainOutput, SwapChainDescriptor};
|
||||
use legion::prelude::*;
|
||||
use zerocopy::AsBytes;
|
||||
use std::{mem, sync::Arc, rc::Rc};
|
||||
use std::mem;
|
||||
|
||||
pub struct ShadowPass {
|
||||
pub pipeline: wgpu::RenderPipeline,
|
||||
|
@ -11,8 +10,6 @@ pub struct ShadowPass {
|
|||
pub shadow_texture: wgpu::Texture,
|
||||
pub shadow_view: wgpu::TextureView,
|
||||
pub shadow_sampler: wgpu::Sampler,
|
||||
pub local_bind_group_layout: Rc<BindGroupLayout>,
|
||||
pub light_uniform_buffer: Arc::<UniformBuffer>,
|
||||
pub lights_are_dirty: bool,
|
||||
}
|
||||
|
||||
|
@ -22,55 +19,9 @@ pub struct ShadowUniforms {
|
|||
}
|
||||
|
||||
impl Pass for ShadowPass {
|
||||
fn render(&mut self, device: &Device, _: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World) {
|
||||
fn render(&mut self, device: &Device, _: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World, render_resources: &RenderResources) {
|
||||
let mut light_query = <(Read<Light>, Read<LocalToWorld>, Read<Translation>)>::query();
|
||||
let mut mesh_query = <(Read<Material>, Read<Handle<Mesh>>)>::query();
|
||||
let light_count = light_query.iter(world).count();
|
||||
|
||||
if self.lights_are_dirty {
|
||||
self.lights_are_dirty = false;
|
||||
let size = mem::size_of::<LightRaw>();
|
||||
let total_size = size * light_count;
|
||||
let temp_buf_data =
|
||||
device.create_buffer_mapped(total_size, wgpu::BufferUsage::COPY_SRC);
|
||||
for ((light, local_to_world, translation), slot) in light_query
|
||||
.iter(world)
|
||||
.zip(temp_buf_data.data.chunks_exact_mut(size))
|
||||
{
|
||||
slot.copy_from_slice(LightRaw::from(&light, &local_to_world.0, &translation).as_bytes());
|
||||
}
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&temp_buf_data.finish(),
|
||||
0,
|
||||
&self.light_uniform_buffer.buffer,
|
||||
0,
|
||||
total_size as wgpu::BufferAddress,
|
||||
);
|
||||
}
|
||||
|
||||
for mut material in <Write<Material>>::query().iter(world) {
|
||||
if let None = material.bind_group {
|
||||
let entity_uniform_size = mem::size_of::<MaterialUniforms>() as wgpu::BufferAddress;
|
||||
let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
size: entity_uniform_size,
|
||||
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
|
||||
});
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &self.local_bind_group_layout,
|
||||
bindings: &[wgpu::Binding {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer {
|
||||
buffer: &uniform_buf,
|
||||
range: 0 .. entity_uniform_size,
|
||||
},
|
||||
}],
|
||||
});
|
||||
|
||||
material.bind_group = Some(bind_group);
|
||||
material.uniform_buf = Some(uniform_buf);
|
||||
}
|
||||
}
|
||||
|
||||
for (i, (mut light, _)) in <(Write<Light>, Read<LocalToWorld>)>::query().iter(world).enumerate() {
|
||||
if let None = light.target_view {
|
||||
|
@ -90,7 +41,7 @@ impl Pass for ShadowPass {
|
|||
// The light uniform buffer already has the projection,
|
||||
// let's just copy it over to the shadow uniform buffer.
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.light_uniform_buffer.buffer,
|
||||
&render_resources.light_uniform_buffer.buffer,
|
||||
(i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress,
|
||||
&self.uniform_buf,
|
||||
0,
|
||||
|
@ -139,7 +90,7 @@ impl ShadowPass {
|
|||
depth: 1,
|
||||
};
|
||||
|
||||
pub fn new(device: &Device, _: &World, light_uniform_buffer: Arc::<UniformBuffer>, vertex_buffer_descriptor: VertexBufferDescriptor, local_bind_group_layout: Rc<BindGroupLayout>, max_lights: u32) -> ShadowPass {
|
||||
pub fn new(device: &Device, _: &World, render_resources: &RenderResources, vertex_buffer_descriptor: VertexBufferDescriptor) -> ShadowPass {
|
||||
// Create pipeline layout
|
||||
let bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
|
@ -150,7 +101,7 @@ impl ShadowPass {
|
|||
}],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout],
|
||||
bind_group_layouts: &[&bind_group_layout, &render_resources.local_bind_group_layout],
|
||||
});
|
||||
|
||||
let uniform_size = mem::size_of::<ShadowUniforms>() as wgpu::BufferAddress;
|
||||
|
@ -173,7 +124,7 @@ impl ShadowPass {
|
|||
|
||||
let shadow_texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
size: Self::SHADOW_SIZE,
|
||||
array_layer_count: max_lights,
|
||||
array_layer_count: render_resources.max_lights as u32,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
|
@ -246,8 +197,6 @@ impl ShadowPass {
|
|||
shadow_texture,
|
||||
shadow_view,
|
||||
shadow_sampler,
|
||||
light_uniform_buffer,
|
||||
local_bind_group_layout,
|
||||
lights_are_dirty: true,
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue