render refactors. ecs integration

This commit is contained in:
Carter Anderson 2019-12-01 20:03:04 -08:00
parent 07c0fa0704
commit 188d355d10
13 changed files with 296 additions and 263 deletions

View file

@ -5,36 +5,41 @@ use winit::{
}; };
use zerocopy::AsBytes; use zerocopy::AsBytes;
use legion::prelude::*;
use std::rc::Rc; use std::sync::Arc;
use std::mem; use std::mem;
use crate::{temp::*, vertex::*, render::*, math}; use crate::{temp::*, vertex::*, render::*, math, Transform};
pub struct Application pub struct Application
{ {
entities: Vec<Entity>, pub universe: Universe,
lights: Vec<Light>, pub world: World,
lights_are_dirty: bool, pub shadow_pass: ShadowPass,
shadow_pass: ShadowPass, pub forward_pass: ForwardPass,
forward_pass: ForwardPass,
camera_position: math::Vec3, camera_position: math::Vec3,
camera_fov: f32, camera_fov: f32,
} }
impl Application { impl Application {
pub const MAX_LIGHTS: usize = 10;
fn init( fn init(
sc_desc: &wgpu::SwapChainDescriptor, sc_desc: &wgpu::SwapChainDescriptor,
device: &wgpu::Device, device: &wgpu::Device,
) -> (Self, Option<wgpu::CommandBuffer>) ) -> (Self, Option<wgpu::CommandBuffer>)
{ {
let universe = Universe::new();
let mut world = universe.create_world();
let vertex_size = mem::size_of::<Vertex>(); let vertex_size = mem::size_of::<Vertex>();
let (cube_vertex_data, cube_index_data) = create_cube(); let (cube_vertex_data, cube_index_data) = create_cube();
let cube_vertex_buf = Rc::new( let cube_vertex_buf = Arc::new(
device.create_buffer_with_data(cube_vertex_data.as_bytes(), wgpu::BufferUsage::VERTEX), device.create_buffer_with_data(cube_vertex_data.as_bytes(), wgpu::BufferUsage::VERTEX),
); );
let cube_index_buf = Rc::new( let cube_index_buf = Arc::new(
device.create_buffer_with_data(cube_index_data.as_bytes(), wgpu::BufferUsage::INDEX), device.create_buffer_with_data(cube_index_data.as_bytes(), wgpu::BufferUsage::INDEX),
); );
@ -71,16 +76,15 @@ impl Application {
}, },
}], }],
}); });
Entity { (CubeEnt {
mx_world: math::identity(),
rotation_speed: 0.0, rotation_speed: 0.0,
color: wgpu::Color::WHITE, color: wgpu::Color::WHITE,
vertex_buf: Rc::new(plane_vertex_buf), vertex_buf: Arc::new(plane_vertex_buf),
index_buf: Rc::new(plane_index_buf), index_buf: Arc::new(plane_index_buf),
index_count: plane_index_data.len(), index_count: plane_index_data.len(),
bind_group, bind_group,
uniform_buf: plane_uniform_buf, uniform_buf: plane_uniform_buf,
} }, Transform::new())
}]; }];
let camera_position = math::vec3(3.0f32, -10.0, 6.0); let camera_position = math::vec3(3.0f32, -10.0, 6.0);
@ -114,12 +118,11 @@ impl Application {
size: entity_uniform_size, size: entity_uniform_size,
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
}); });
entities.push(Entity { entities.push((CubeEnt {
mx_world: math::translation(&cube.offset),
rotation_speed: cube.rotation, rotation_speed: cube.rotation,
color: wgpu::Color::GREEN, color: wgpu::Color::GREEN,
vertex_buf: Rc::clone(&cube_vertex_buf), vertex_buf: Arc::clone(&cube_vertex_buf),
index_buf: Rc::clone(&cube_index_buf), index_buf: Arc::clone(&cube_index_buf),
index_count: cube_index_data.len(), index_count: cube_index_data.len(),
bind_group: device.create_bind_group(&wgpu::BindGroupDescriptor { bind_group: device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &local_bind_group_layout, layout: &local_bind_group_layout,
@ -132,9 +135,11 @@ impl Application {
}], }],
}), }),
uniform_buf, uniform_buf,
}); }, Transform { value: math::translation(&cube.offset)}));
} }
world.insert((), entities);
let vb_desc = wgpu::VertexBufferDescriptor { let vb_desc = wgpu::VertexBufferDescriptor {
stride: vertex_size as wgpu::BufferAddress, stride: vertex_size as wgpu::BufferAddress,
step_mode: wgpu::InputStepMode::Vertex, step_mode: wgpu::InputStepMode::Vertex,
@ -152,7 +157,20 @@ impl Application {
], ],
}; };
let shadow_pass = ShadowPass::new(device, vb_desc.clone(), &local_bind_group_layout); let light_uniform_size =
(Self::MAX_LIGHTS * mem::size_of::<LightRaw>()) as wgpu::BufferAddress;
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,
});
let shadow_pass = ShadowPass::new(device, light_uniform_buffer.clone(), vb_desc.clone(), &local_bind_group_layout, Self::MAX_LIGHTS as u32);
let mut shadow_target_views = (0 .. 2) let mut shadow_target_views = (0 .. 2)
.map(|i| { .map(|i| {
@ -167,8 +185,9 @@ impl Application {
})) }))
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let lights = vec![ let lights = vec![
Light { (Light {
pos: math::vec3(7.0, -5.0, 10.0), pos: math::vec3(7.0, -5.0, 10.0),
color: wgpu::Color { color: wgpu::Color {
r: 0.5, r: 0.5,
@ -179,8 +198,8 @@ impl Application {
fov: f32::to_radians(60.0), fov: f32::to_radians(60.0),
depth: 1.0 .. 20.0, depth: 1.0 .. 20.0,
target_view: shadow_target_views[0].take().unwrap(), target_view: shadow_target_views[0].take().unwrap(),
}, },),
Light { (Light {
pos: math::vec3(-5.0, 7.0, 10.0), pos: math::vec3(-5.0, 7.0, 10.0),
color: wgpu::Color { color: wgpu::Color {
r: 1.0, r: 1.0,
@ -191,21 +210,23 @@ impl Application {
fov: f32::to_radians(45.0), fov: f32::to_radians(45.0),
depth: 1.0 .. 20.0, depth: 1.0 .. 20.0,
target_view: shadow_target_views[1].take().unwrap(), target_view: shadow_target_views[1].take().unwrap(),
}, },),
]; ];
let light_count = lights.len();
world.insert((), lights);
let matrix = generate_matrix(&camera_position, camera_fov, sc_desc.width as f32 / sc_desc.height as f32, 1.0, 20.0); let matrix = camera::get_projection_view_matrix(&camera_position, camera_fov, sc_desc.width as f32 / sc_desc.height as f32, 1.0, 20.0);
let forward_uniforms = ForwardUniforms { let forward_uniforms = ForwardUniforms {
proj: *matrix.as_ref(), proj: *matrix.as_ref(),
num_lights: [lights.len() as u32, 0, 0, 0], num_lights: [light_count as u32, 0, 0, 0],
}; };
let forward_pass = ForwardPass::new(device, forward_uniforms, &shadow_pass, vb_desc, &local_bind_group_layout, sc_desc); let forward_pass = ForwardPass::new(device, forward_uniforms, light_uniform_buffer.clone(), &shadow_pass, vb_desc, &local_bind_group_layout, sc_desc);
let this = Application { let this = Application {
entities, universe,
lights, world,
lights_are_dirty: true,
shadow_pass, shadow_pass,
forward_pass, forward_pass,
camera_position, camera_position,
@ -221,7 +242,7 @@ impl Application {
) -> Option<wgpu::CommandBuffer> ) -> Option<wgpu::CommandBuffer>
{ {
let command_buf = { let command_buf = {
let mx_total = generate_matrix(&self.camera_position, self.camera_fov, sc_desc.width as f32 / sc_desc.height as f32, 1.0, 20.0); let mx_total = camera::get_projection_view_matrix(&self.camera_position, self.camera_fov, sc_desc.width as f32 / sc_desc.height as f32, 1.0, 20.0);
let mx_ref: [[f32; 4]; 4] = mx_total.into(); let mx_ref: [[f32; 4]; 4] = mx_total.into();
let temp_buf = let temp_buf =
device.create_buffer_with_data(mx_ref.as_bytes(), wgpu::BufferUsage::COPY_SRC); device.create_buffer_with_data(mx_ref.as_bytes(), wgpu::BufferUsage::COPY_SRC);
@ -251,23 +272,18 @@ impl Application {
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
{ {
let mut entities = <(Read<CubeEnt>, Read<Transform>)>::query();
let entities_count = entities.iter(&mut self.world).count();
let size = mem::size_of::<EntityUniforms>(); let size = mem::size_of::<EntityUniforms>();
let temp_buf_data = device let temp_buf_data = device
.create_buffer_mapped(self.entities.len() * size, wgpu::BufferUsage::COPY_SRC); .create_buffer_mapped(entities_count * size, wgpu::BufferUsage::COPY_SRC);
for (entity, slot) in self for ((entity, transform), slot) in entities.iter(&mut self.world)
.entities
.iter_mut()
.zip(temp_buf_data.data.chunks_exact_mut(size)) .zip(temp_buf_data.data.chunks_exact_mut(size))
{ {
if entity.rotation_speed != 0.0 {
let rotation =
math::rotation(entity.rotation_speed, &math::vec3(0.0, 1.0, 0.0));
entity.mx_world = entity.mx_world * rotation;
}
slot.copy_from_slice( slot.copy_from_slice(
EntityUniforms { EntityUniforms {
model: entity.mx_world.into(), model: transform.value.into(),
color: [ color: [
entity.color.r as f32, entity.color.r as f32,
entity.color.g as f32, entity.color.g as f32,
@ -281,7 +297,7 @@ impl Application {
let temp_buf = temp_buf_data.finish(); let temp_buf = temp_buf_data.finish();
for (i, entity) in self.entities.iter().enumerate() { for (i, (entity, _)) in entities.iter(&mut self.world).enumerate() {
encoder.copy_buffer_to_buffer( encoder.copy_buffer_to_buffer(
&temp_buf, &temp_buf,
(i * size) as wgpu::BufferAddress, (i * size) as wgpu::BufferAddress,
@ -292,97 +308,8 @@ impl Application {
} }
} }
if self.lights_are_dirty { self.shadow_pass.render(device, frame, &mut encoder, &mut self.world);
self.lights_are_dirty = false; self.forward_pass.render(device, frame, &mut encoder, &mut self.world);
let size = mem::size_of::<LightRaw>();
let total_size = size * self.lights.len();
let temp_buf_data =
device.create_buffer_mapped(total_size, wgpu::BufferUsage::COPY_SRC);
for (light, slot) in self
.lights
.iter()
.zip(temp_buf_data.data.chunks_exact_mut(size))
{
slot.copy_from_slice(light.to_raw().as_bytes());
}
encoder.copy_buffer_to_buffer(
&temp_buf_data.finish(),
0,
&self.forward_pass.light_uniform_buffer,
0,
total_size as wgpu::BufferAddress,
);
}
for (i, light) in self.lights.iter().enumerate() {
// 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.forward_pass.light_uniform_buffer,
(i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress,
&self.shadow_pass.uniform_buf,
0,
64,
);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
attachment: &light.target_view,
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.shadow_pass.pipeline);
pass.set_bind_group(0, &self.shadow_pass.bind_group, &[]);
for entity in &self.entities {
pass.set_bind_group(1, &entity.bind_group, &[]);
pass.set_index_buffer(&entity.index_buf, 0);
pass.set_vertex_buffers(0, &[(&entity.vertex_buf, 0)]);
pass.draw_indexed(0 .. entity.index_count as u32, 0, 0 .. 1);
}
}
// forward pass
{
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.1,
g: 0.2,
b: 0.3,
a: 1.0,
},
}],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
attachment: &self.forward_pass.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.forward_pass.pipeline);
pass.set_bind_group(0, &self.forward_pass.bind_group, &[]);
for entity in &self.entities {
pass.set_bind_group(1, &entity.bind_group, &[]);
pass.set_index_buffer(&entity.index_buf, 0);
pass.set_vertex_buffers(0, &[(&entity.vertex_buf, 0)]);
pass.draw_indexed(0 .. entity.index_count as u32, 0, 0 .. 1);
}
}
encoder.finish() encoder.finish()
} }

3
src/core/mod.rs Normal file
View file

@ -0,0 +1,3 @@
mod transform;
pub use transform::*;

View file

@ -2,15 +2,13 @@ use crate::math;
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub struct Transform { pub struct Transform {
pub local: math::Mat4, pub value: math::Mat4,
pub global: math::Mat4,
} }
impl Transform { impl Transform {
pub fn new() -> Transform { pub fn new() -> Transform {
Transform { Transform {
local: math::identity(), value: math::identity(),
global: math::identity(),
} }
} }
} }

View file

@ -1,11 +1,11 @@
mod transform; mod core;
mod application; mod application;
mod vertex; mod vertex;
mod temp; mod temp;
mod render; mod render;
pub use transform::Transform;
pub use application::Application; pub use application::Application;
pub use crate::core::*;
pub use legion; pub use legion;
pub use nalgebra_glm as math; pub use nalgebra_glm as math;

22
src/render/camera.rs Normal file
View file

@ -0,0 +1,22 @@
use crate::math;
pub fn get_projection_view_matrix(eye: &math::Vec3, fov: f32, aspect_ratio: f32, near: f32, far: f32) -> math::Mat4 {
let projection = math::perspective(aspect_ratio, fov, near, far);
let view = math::look_at_rh::<f32>(
&eye,
&math::vec3(0.0, 0.0, 0.0),
&math::vec3(0.0, 0.0, 1.0),
);
opengl_to_wgpu_matrix() * projection * view
}
pub fn opengl_to_wgpu_matrix() -> math::Mat4 {
math::mat4(
1.0, 0.0, 0.0, 0.0,
0.0, -1.0, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.0, 0.0, 0.5, 1.0,
)
}

View file

@ -1,8 +1,8 @@
use crate::{temp::*, render::shadow::ShadowPass}; use crate::{render::*, temp::*};
use legion::prelude::*;
use std::mem; use std::{mem, sync::Arc};
use zerocopy::{AsBytes, FromBytes}; use zerocopy::{AsBytes, FromBytes};
use wgpu::{Device, BindGroupLayout, VertexBufferDescriptor, SwapChainDescriptor}; use wgpu::{CommandEncoder, Device, BindGroupLayout, VertexBufferDescriptor, SwapChainDescriptor, SwapChainOutput};
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, AsBytes, FromBytes)] #[derive(Clone, Copy, AsBytes, FromBytes)]
@ -15,22 +15,59 @@ pub struct ForwardPass {
pub pipeline: wgpu::RenderPipeline, pub pipeline: wgpu::RenderPipeline,
pub bind_group: wgpu::BindGroup, pub bind_group: wgpu::BindGroup,
pub forward_uniform_buffer: wgpu::Buffer, pub forward_uniform_buffer: wgpu::Buffer,
pub light_uniform_buffer: wgpu::Buffer, pub light_uniform_buffer: Arc::<UniformBuffer>,
pub depth_texture: wgpu::TextureView, pub depth_texture: wgpu::TextureView,
} }
impl Pass for ForwardPass {
fn render(&mut self, device: &Device, frame: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World) {
let mut entities = <Read<CubeEnt>>::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.1,
g: 0.2,
b: 0.3,
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, &[]);
for entity in entities.iter_immutable(world) {
pass.set_bind_group(1, &entity.bind_group, &[]);
pass.set_index_buffer(&entity.index_buf, 0);
pass.set_vertex_buffers(0, &[(&entity.vertex_buf, 0)]);
pass.draw_indexed(0 .. entity.index_count as u32, 0, 0 .. 1);
}
}
}
impl ForwardPass { impl ForwardPass {
pub const MAX_LIGHTS: usize = 10;
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
pub fn new(device: &Device, forward_uniforms: ForwardUniforms, shadow_pass: &ShadowPass, vertex_buffer_descriptor: VertexBufferDescriptor, local_bind_group_layout: &BindGroupLayout, swap_chain_descriptor: &SwapChainDescriptor) -> ForwardPass { pub fn new(device: &Device, forward_uniforms: ForwardUniforms, light_uniform_buffer: Arc::<UniformBuffer>, shadow_pass: &shadow::ShadowPass, vertex_buffer_descriptor: VertexBufferDescriptor, local_bind_group_layout: &BindGroupLayout, swap_chain_descriptor: &SwapChainDescriptor) -> ForwardPass {
let vs_bytes = load_glsl( let vs_bytes = shader::load_glsl(
include_str!("forward.vert"), include_str!("forward.vert"),
ShaderStage::Vertex, shader::ShaderStage::Vertex,
); );
let fs_bytes = load_glsl( let fs_bytes = shader::load_glsl(
include_str!("forward.frag"), include_str!("forward.frag"),
ShaderStage::Fragment, shader::ShaderStage::Fragment,
); );
let bind_group_layout = let bind_group_layout =
@ -68,16 +105,6 @@ impl ForwardPass {
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
); );
let light_uniform_size =
(Self::MAX_LIGHTS * mem::size_of::<LightRaw>()) as wgpu::BufferAddress;
let light_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
size: light_uniform_size,
usage: wgpu::BufferUsage::UNIFORM
| wgpu::BufferUsage::COPY_SRC
| wgpu::BufferUsage::COPY_DST,
});
// Create bind group // Create bind group
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout, layout: &bind_group_layout,
@ -92,8 +119,8 @@ impl ForwardPass {
wgpu::Binding { wgpu::Binding {
binding: 1, binding: 1,
resource: wgpu::BindingResource::Buffer { resource: wgpu::BindingResource::Buffer {
buffer: &light_uniform_buffer, buffer: &light_uniform_buffer.buffer,
range: 0 .. light_uniform_size, range: 0 .. light_uniform_buffer.size,
}, },
}, },
wgpu::Binding { wgpu::Binding {
@ -157,7 +184,6 @@ impl ForwardPass {
alpha_to_coverage_enabled: false, alpha_to_coverage_enabled: false,
}); });
ForwardPass { ForwardPass {
pipeline, pipeline,
bind_group, bind_group,

35
src/render/light.rs Normal file
View file

@ -0,0 +1,35 @@
use crate::{math, render::camera};
use std::ops::Range;
use zerocopy::{AsBytes, FromBytes};
pub struct Light {
pub pos: math::Vec3,
pub color: wgpu::Color,
pub fov: f32,
pub depth: Range<f32>,
pub target_view: wgpu::TextureView,
}
#[repr(C)]
#[derive(Clone, Copy, AsBytes, FromBytes)]
pub struct LightRaw {
pub proj: [[f32; 4]; 4],
pub pos: [f32; 4],
pub color: [f32; 4],
}
impl Light {
pub fn to_raw(&self) -> LightRaw {
LightRaw {
proj: camera::get_projection_view_matrix(&self.pos, self.fov, 1.0, self.depth.start, self.depth.end).into(),
pos: [self.pos.x, self.pos.y, self.pos.z, 1.0],
color: [
self.color.r as f32,
self.color.g as f32,
self.color.b as f32,
1.0,
],
}
}
}

View file

@ -1,5 +1,17 @@
pub mod camera;
pub mod shader;
mod forward; mod forward;
mod shadow; mod shadow;
mod light;
mod pass;
pub use forward::{ForwardPass, ForwardUniforms}; pub use forward::{ForwardPass, ForwardUniforms};
pub use shadow::ShadowPass; pub use shadow::ShadowPass;
pub use light::*;
pub use shader::*;
pub use pass::*;
pub struct UniformBuffer {
pub buffer: wgpu::Buffer,
pub size: u64,
}

6
src/render/pass.rs Normal file
View file

@ -0,0 +1,6 @@
use legion::world::World;
use wgpu::{CommandEncoder, Device, SwapChainOutput};
pub trait Pass {
fn render(&mut self, device: &Device, frame: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World);
}

16
src/render/shader.rs Normal file
View file

@ -0,0 +1,16 @@
#[allow(dead_code)]
pub enum ShaderStage {
Vertex,
Fragment,
Compute,
}
pub fn load_glsl(code: &str, stage: ShaderStage) -> Vec<u32> {
let ty = match stage {
ShaderStage::Vertex => glsl_to_spirv::ShaderType::Vertex,
ShaderStage::Fragment => glsl_to_spirv::ShaderType::Fragment,
ShaderStage::Compute => glsl_to_spirv::ShaderType::Compute,
};
wgpu::read_spirv(glsl_to_spirv::compile(&code, ty).unwrap()).unwrap()
}

View file

@ -1,6 +1,8 @@
use crate::{temp::*, render::forward}; use crate::{render::*, temp::*};
use wgpu::{Device, BindGroupLayout, VertexBufferDescriptor}; use wgpu::{BindGroupLayout, CommandEncoder, Device, VertexBufferDescriptor, SwapChainOutput};
use std::mem; use legion::prelude::*;
use zerocopy::AsBytes;
use std::{mem, sync::Arc};
pub struct ShadowPass { pub struct ShadowPass {
pub pipeline: wgpu::RenderPipeline, pub pipeline: wgpu::RenderPipeline,
@ -9,6 +11,76 @@ pub struct ShadowPass {
pub shadow_texture: wgpu::Texture, pub shadow_texture: wgpu::Texture,
pub shadow_view: wgpu::TextureView, pub shadow_view: wgpu::TextureView,
pub shadow_sampler: wgpu::Sampler, pub shadow_sampler: wgpu::Sampler,
pub light_uniform_buffer: Arc::<UniformBuffer>,
pub lights_are_dirty: bool,
}
#[repr(C)]
pub struct ShadowUniforms {
pub proj: [[f32; 4]; 4],
}
impl Pass for ShadowPass {
fn render(&mut self, device: &Device, _: &SwapChainOutput, encoder: &mut CommandEncoder, world: &mut World) {
let mut light_query = <Read<Light>>::query();
let mut entity_query = <Read<CubeEnt>>::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, slot) in light_query
.iter(world)
.zip(temp_buf_data.data.chunks_exact_mut(size))
{
slot.copy_from_slice(light.to_raw().as_bytes());
}
encoder.copy_buffer_to_buffer(
&temp_buf_data.finish(),
0,
&self.light_uniform_buffer.buffer,
0,
total_size as wgpu::BufferAddress,
);
}
for (i, light) in light_query.iter_immutable(world).enumerate() {
// 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,
(i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress,
&self.uniform_buf,
0,
64,
);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
attachment: &light.target_view,
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, &[]);
for entity in entity_query.iter_immutable(world) {
pass.set_bind_group(1, &entity.bind_group, &[]);
pass.set_index_buffer(&entity.index_buf, 0);
pass.set_vertex_buffers(0, &[(&entity.vertex_buf, 0)]);
pass.draw_indexed(0 .. entity.index_count as u32, 0, 0 .. 1);
}
}
}
} }
impl ShadowPass { impl ShadowPass {
@ -19,7 +91,7 @@ impl ShadowPass {
depth: 1, depth: 1,
}; };
pub fn new(device: &Device, vertex_buffer_descriptor: VertexBufferDescriptor, local_bind_group_layout: &BindGroupLayout) -> ShadowPass { pub fn new(device: &Device, light_uniform_buffer: Arc::<UniformBuffer>, vertex_buffer_descriptor: VertexBufferDescriptor, local_bind_group_layout: &BindGroupLayout, max_lights: u32) -> ShadowPass {
// Create pipeline layout // Create pipeline layout
let bind_group_layout = let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@ -53,7 +125,7 @@ impl ShadowPass {
let shadow_texture = device.create_texture(&wgpu::TextureDescriptor { let shadow_texture = device.create_texture(&wgpu::TextureDescriptor {
size: Self::SHADOW_SIZE, size: Self::SHADOW_SIZE,
array_layer_count: forward::ForwardPass::MAX_LIGHTS as u32, array_layer_count: max_lights,
mip_level_count: 1, mip_level_count: 1,
sample_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
@ -78,9 +150,9 @@ impl ShadowPass {
// Create the render pipeline // Create the render pipeline
let vs_bytes = let vs_bytes =
load_glsl(include_str!("shadow.vert"), ShaderStage::Vertex); shader::load_glsl(include_str!("shadow.vert"), shader::ShaderStage::Vertex);
let fs_bytes = let fs_bytes =
load_glsl(include_str!("shadow.frag"), ShaderStage::Fragment); shader::load_glsl(include_str!("shadow.frag"), shader::ShaderStage::Fragment);
let vs_module = device.create_shader_module(&vs_bytes); let vs_module = device.create_shader_module(&vs_bytes);
let fs_module = device.create_shader_module(&fs_bytes); let fs_module = device.create_shader_module(&fs_bytes);
@ -125,7 +197,9 @@ impl ShadowPass {
uniform_buf, uniform_buf,
shadow_texture, shadow_texture,
shadow_view, shadow_view,
shadow_sampler shadow_sampler,
light_uniform_buffer,
lights_are_dirty: true,
} }
} }
} }

View file

@ -1,101 +1,19 @@
use std::{rc::Rc, ops::Range}; use std::{sync::Arc};
use zerocopy::{AsBytes, FromBytes}; use zerocopy::{AsBytes, FromBytes};
use crate::math;
pub struct CubeEnt {
pub fn opengl_to_wgpu_matrix() -> math::Mat4 {
math::mat4(
1.0, 0.0, 0.0, 0.0,
0.0, -1.0, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.0, 0.0, 0.5, 1.0,
)
}
pub struct Entity {
pub mx_world: math::Mat4,
pub rotation_speed: f32, pub rotation_speed: f32,
pub color: wgpu::Color, pub color: wgpu::Color,
pub vertex_buf: Rc<wgpu::Buffer>, pub vertex_buf: Arc<wgpu::Buffer>,
pub index_buf: Rc<wgpu::Buffer>, pub index_buf: Arc<wgpu::Buffer>,
pub index_count: usize, pub index_count: usize,
pub bind_group: wgpu::BindGroup, pub bind_group: wgpu::BindGroup,
pub uniform_buf: wgpu::Buffer, pub uniform_buf: wgpu::Buffer,
} }
pub struct Light {
pub pos: math::Vec3,
pub color: wgpu::Color,
pub fov: f32,
pub depth: Range<f32>,
pub target_view: wgpu::TextureView,
}
#[repr(C)]
#[derive(Clone, Copy, AsBytes, FromBytes)]
pub struct LightRaw {
pub proj: [[f32; 4]; 4],
pub pos: [f32; 4],
pub color: [f32; 4],
}
impl Light {
pub fn to_raw(&self) -> LightRaw {
LightRaw {
proj: generate_matrix(&self.pos, self.fov, 1.0, self.depth.start, self.depth.end).into(),
pos: [self.pos.x, self.pos.y, self.pos.z, 1.0],
color: [
self.color.r as f32,
self.color.g as f32,
self.color.b as f32,
1.0,
],
}
}
}
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, AsBytes, FromBytes)] #[derive(Clone, Copy, AsBytes, FromBytes)]
pub struct EntityUniforms { pub struct EntityUniforms {
pub model: [[f32; 4]; 4], pub model: [[f32; 4]; 4],
pub color: [f32; 4], pub color: [f32; 4],
} }
#[repr(C)]
pub struct ShadowUniforms {
pub proj: [[f32; 4]; 4],
}
// pub struct Pass {
// pub pipeline: wgpu::RenderPipeline,
// pub bind_group: wgpu::BindGroup,
// pub uniform_buf: wgpu::Buffer,
// }
#[allow(dead_code)]
pub enum ShaderStage {
Vertex,
Fragment,
Compute,
}
pub fn load_glsl(code: &str, stage: ShaderStage) -> Vec<u32> {
let ty = match stage {
ShaderStage::Vertex => glsl_to_spirv::ShaderType::Vertex,
ShaderStage::Fragment => glsl_to_spirv::ShaderType::Fragment,
ShaderStage::Compute => glsl_to_spirv::ShaderType::Compute,
};
wgpu::read_spirv(glsl_to_spirv::compile(&code, ty).unwrap()).unwrap()
}
pub fn generate_matrix(eye: &math::Vec3, fov: f32, aspect_ratio: f32, near: f32, far: f32) -> math::Mat4 {
let projection = math::perspective(aspect_ratio, fov, near, far);
let view = math::look_at_rh::<f32>(
&eye,
&math::vec3(0.0, 0.0, 0.0),
&math::vec3(0.0, 0.0, 1.0),
);
opengl_to_wgpu_matrix() * projection * view
}

View file

@ -2,10 +2,6 @@ use bevy::*;
use bevy::legion::prelude::*; use bevy::legion::prelude::*;
fn main() { fn main() {
let universe = Universe::new();
let mut world = universe.create_world();
world.insert((), vec![(Transform::new(),)]);
// Create a query which finds all `Position` and `Velocity` components // Create a query which finds all `Position` and `Velocity` components
// let mut query = Read::<Transform>::query(); // let mut query = Read::<Transform>::query();
Application::run(); Application::run();