rustfmt crate

This commit is contained in:
Carter Anderson 2020-01-11 02:11:27 -08:00
parent ee03942e40
commit 9f7e313dc4
36 changed files with 1043 additions and 694 deletions

View file

@ -1,4 +1,9 @@
use crate::{App, asset::AssetStorage, legion::prelude::{World, SystemScheduler}, render::{*, passes::*}, AppStage, Time}; use crate::{
asset::AssetStorage,
legion::prelude::{SystemScheduler, World},
render::{passes::*, *},
App, AppStage, Time,
};
pub struct AppBuilder { pub struct AppBuilder {
pub app: App, pub app: App,
@ -26,7 +31,7 @@ impl AppBuilder {
self self
} }
pub fn with_scheduler(mut self, scheduler: SystemScheduler::<AppStage>) -> Self { pub fn with_scheduler(mut self, scheduler: SystemScheduler<AppStage>) -> Self {
self.app.scheduler = scheduler; self.app.scheduler = scheduler;
self self
} }
@ -37,29 +42,36 @@ impl AppBuilder {
} }
pub fn add_default_passes(mut self) -> Self { pub fn add_default_passes(mut self) -> Self {
self.app.render_graph.add_render_resource_manager(Box::new(render_resources::MaterialResourceManager)); let render_graph = &mut self.app.render_graph;
self.app.render_graph.add_render_resource_manager(Box::new(render_resources::LightResourceManager::new(10))); render_graph
self.app.render_graph.add_render_resource_manager(Box::new(render_resources::GlobalResourceManager)); .add_render_resource_manager(Box::new(render_resources::MaterialResourceManager));
self.app.render_graph.add_render_resource_manager(Box::new(render_resources::Global2dResourceManager)); render_graph
.add_render_resource_manager(Box::new(render_resources::LightResourceManager::new(10)));
render_graph.add_render_resource_manager(Box::new(render_resources::GlobalResourceManager));
render_graph
.add_render_resource_manager(Box::new(render_resources::Global2dResourceManager));
let depth_format = wgpu::TextureFormat::Depth32Float; let depth_format = wgpu::TextureFormat::Depth32Float;
self.app.render_graph.set_pass("forward", Box::new(ForwardPass::new(depth_format))); render_graph.set_pass("forward", Box::new(ForwardPass::new(depth_format)));
self.app.render_graph.set_pipeline("forward", "forward", Box::new(ForwardPipeline::new())); render_graph.set_pipeline("forward", "forward", Box::new(ForwardPipeline::new()));
self.app.render_graph.set_pipeline("forward", "forward_instanced", Box::new(ForwardInstancedPipeline::new(depth_format))); render_graph.set_pipeline(
self.app.render_graph.set_pipeline("forward", "ui", Box::new(UiPipeline::new())); "forward",
"forward_instanced",
Box::new(ForwardInstancedPipeline::new(depth_format)),
);
render_graph.set_pipeline("forward", "ui", Box::new(UiPipeline::new()));
self self
} }
pub fn add_default_resources(mut self) -> Self { pub fn add_default_resources(mut self) -> Self {
self.app.world.resources.insert(Time::new()); let resources = &mut self.app.world.resources;
self.app.world.resources.insert(AssetStorage::<Mesh, MeshType>::new()); resources.insert(Time::new());
resources.insert(AssetStorage::<Mesh, MeshType>::new());
self self
} }
pub fn add_defaults(self) -> Self { pub fn add_defaults(self) -> Self {
self self.add_default_resources().add_default_passes()
.add_default_resources()
.add_default_passes()
} }
} }

View file

@ -15,4 +15,4 @@ impl std::fmt::Display for AppStage {
AppStage::Render => write!(f, "draw"), AppStage::Render => write!(f, "draw"),
} }
} }
} }

View file

@ -1,8 +1,8 @@
mod app_stage;
mod app_builder; mod app_builder;
mod app_stage;
pub use app_stage::AppStage;
pub use app_builder::AppBuilder; pub use app_builder::AppBuilder;
pub use app_stage::AppStage;
use winit::{ use winit::{
event, event,
@ -15,8 +15,7 @@ use legion::prelude::*;
use crate::{render::*, Time}; use crate::{render::*, Time};
pub struct App pub struct App {
{
pub world: World, pub world: World,
pub window: Option<Window>, pub window: Option<Window>,
pub render_graph: RenderGraph, pub render_graph: RenderGraph,
@ -33,7 +32,7 @@ impl App {
swap_chain: None, swap_chain: None,
window: None, window: None,
} }
} }
fn update(&mut self) { fn update(&mut self) {
{ {
@ -48,25 +47,22 @@ impl App {
} }
} }
fn resize(&mut self, width: u32, height: u32) fn resize(&mut self, width: u32, height: u32) {
{
self.swap_chain = Some(self.render_graph.resize(width, height, &mut self.world)); self.swap_chain = Some(self.render_graph.resize(width, height, &mut self.world));
} }
fn handle_event(&mut self, _: WindowEvent) fn handle_event(&mut self, _: WindowEvent) {}
{
}
fn render(&mut self) fn render(&mut self) {
{ self.render_graph
self.render_graph.render(&mut self.world, self.swap_chain.as_mut().unwrap()); .render(&mut self.world, self.swap_chain.as_mut().unwrap());
} }
pub fn run(mut self) { pub fn run(mut self) {
env_logger::init(); env_logger::init();
let event_loop = EventLoop::new(); let event_loop = EventLoop::new();
log::info!("Initializing the window..."); log::info!("Initializing the window...");
let adapter = wgpu::Adapter::request( let adapter = wgpu::Adapter::request(
&wgpu::RequestAdapterOptions { &wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::Default, power_preference: wgpu::PowerPreference::Default,
@ -74,7 +70,7 @@ impl App {
wgpu::BackendBit::PRIMARY, wgpu::BackendBit::PRIMARY,
) )
.unwrap(); .unwrap();
let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor { let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions { extensions: wgpu::Extensions {
anisotropic_filtering: false, anisotropic_filtering: false,
@ -91,7 +87,7 @@ impl App {
let surface = wgpu::Surface::create(&window); let surface = wgpu::Surface::create(&window);
(window, size, surface) (window, size, surface)
}; };
let swap_chain_descriptor = wgpu::SwapChainDescriptor { let swap_chain_descriptor = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8UnormSrgb, format: wgpu::TextureFormat::Bgra8UnormSrgb,
@ -102,11 +98,16 @@ impl App {
let swap_chain = device.create_swap_chain(&surface, &swap_chain_descriptor); let swap_chain = device.create_swap_chain(&surface, &swap_chain_descriptor);
log::info!("Initializing the example..."); log::info!("Initializing the example...");
self.render_graph.initialize(&mut self.world, device, swap_chain_descriptor, queue, surface); self.render_graph.initialize(
&mut self.world,
device,
swap_chain_descriptor,
queue,
surface,
);
self.window = Some(window); self.window = Some(window);
self.swap_chain = Some(swap_chain); self.swap_chain = Some(swap_chain);
log::info!("Entering render loop..."); log::info!("Entering render loop...");
event_loop.run(move |event, _, control_flow| { event_loop.run(move |event, _, control_flow| {
*control_flow = if cfg!(feature = "metal-auto-capture") { *control_flow = if cfg!(feature = "metal-auto-capture") {
@ -148,6 +149,6 @@ impl App {
} }
_ => (), _ => (),
} }
}); });
} }
} }

View file

@ -1,6 +1,6 @@
use std::{fs, io};
use std::boxed::Box; use std::boxed::Box;
use std::error::Error; use std::error::Error;
use std::{fs, io};
// use crate::render::Mesh; // use crate::render::Mesh;
@ -10,9 +10,8 @@ pub fn load_gltf(path: &str) -> Result<(), Box<dyn Error>> {
let reader = io::BufReader::new(file); let reader = io::BufReader::new(file);
let gltf = gltf::Gltf::from_reader(reader)?; let gltf = gltf::Gltf::from_reader(reader)?;
for scene in gltf.scenes() { for scene in gltf.scenes() {
for _mesh in scene.nodes() { for _mesh in scene.nodes() {}
}
} }
Ok(()) Ok(())
} }

View file

@ -2,21 +2,25 @@ mod gltf;
pub use self::gltf::load_gltf; pub use self::gltf::load_gltf;
use std::{sync::{Arc, RwLock}, marker::PhantomData, ops::Drop, collections::HashMap}; use std::{
collections::HashMap,
marker::PhantomData,
ops::Drop,
sync::{Arc, RwLock},
};
pub struct Handle<T> pub struct Handle<T> {
{
pub id: Arc<RwLock<usize>>, pub id: Arc<RwLock<usize>>,
marker: PhantomData<T>, marker: PhantomData<T>,
free_indices: Arc<RwLock<Vec<usize>>> free_indices: Arc<RwLock<Vec<usize>>>,
} }
impl<T> Clone for Handle<T> { impl<T> Clone for Handle<T> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Handle { Handle {
id: self.id.clone(), id: self.id.clone(),
free_indices: self.free_indices.clone(), free_indices: self.free_indices.clone(),
marker: PhantomData marker: PhantomData,
} }
} }
} }
@ -36,14 +40,20 @@ pub trait Asset<D> {
fn load(descriptor: D) -> Self; fn load(descriptor: D) -> Self;
} }
pub struct AssetStorage<T, D> where T: Asset<D> { pub struct AssetStorage<T, D>
where
T: Asset<D>,
{
assets: Vec<Option<T>>, assets: Vec<Option<T>>,
free_indices: Arc<RwLock<Vec<usize>>>, free_indices: Arc<RwLock<Vec<usize>>>,
names: HashMap<String, Arc<RwLock<usize>>>, names: HashMap<String, Arc<RwLock<usize>>>,
marker: PhantomData<D>, marker: PhantomData<D>,
} }
impl<T, D> AssetStorage<T, D> where T: Asset<D> { impl<T, D> AssetStorage<T, D>
where
T: Asset<D>,
{
pub fn new() -> AssetStorage<T, D> { pub fn new() -> AssetStorage<T, D> {
AssetStorage { AssetStorage {
assets: Vec::new(), assets: Vec::new(),
@ -55,13 +65,11 @@ impl<T, D> AssetStorage<T, D> where T: Asset<D> {
pub fn get_named(&self, name: &str) -> Option<Handle<T>> { pub fn get_named(&self, name: &str) -> Option<Handle<T>> {
match self.names.get(name) { match self.names.get(name) {
Some(id) => { Some(id) => Some(Handle {
Some(Handle { id: id.clone(),
id: id.clone(), marker: PhantomData,
marker: PhantomData, free_indices: self.free_indices.clone(),
free_indices: self.free_indices.clone() }),
})
},
None => None, None => None,
} }
} }
@ -75,9 +83,9 @@ impl<T, D> AssetStorage<T, D> where T: Asset<D> {
Handle { Handle {
id: handle, id: handle,
marker: PhantomData, marker: PhantomData,
free_indices: self.free_indices.clone() free_indices: self.free_indices.clone(),
} }
}, }
None => { None => {
self.assets.push(Some(asset)); self.assets.push(Some(asset));
let id = self.assets.len() - 1; let id = self.assets.len() - 1;
@ -86,7 +94,7 @@ impl<T, D> AssetStorage<T, D> where T: Asset<D> {
Handle { Handle {
id: handle, id: handle,
marker: PhantomData, marker: PhantomData,
free_indices: self.free_indices.clone() free_indices: self.free_indices.clone(),
} }
} }
} }
@ -95,14 +103,12 @@ impl<T, D> AssetStorage<T, D> where T: Asset<D> {
pub fn get(&mut self, id: usize) -> Option<&mut T> { pub fn get(&mut self, id: usize) -> Option<&mut T> {
if id >= self.assets.len() { if id >= self.assets.len() {
None None
} } else {
else {
if let Some(ref mut asset) = self.assets[id] { if let Some(ref mut asset) = self.assets[id] {
Some(asset) Some(asset)
} else { } else {
None None
} }
} }
} }
} }

View file

@ -1,2 +1,2 @@
pub mod time; pub mod time;
pub use time::Time; pub use time::Time;

View file

@ -3,7 +3,7 @@ use std::time::{Duration, Instant};
pub struct Time { pub struct Time {
pub delta: Duration, pub delta: Duration,
pub instant: Instant, pub instant: Instant,
pub delta_seconds: f32 pub delta_seconds: f32,
} }
impl Time { impl Time {
@ -21,6 +21,7 @@ impl Time {
pub fn stop(&mut self) { pub fn stop(&mut self) {
self.delta = Instant::now() - self.instant; self.delta = Instant::now() - self.instant;
self.delta_seconds = self.delta.as_secs() as f32 + (self.delta.subsec_nanos() as f32 / 1.0e9); self.delta_seconds =
self.delta.as_secs() as f32 + (self.delta.subsec_nanos() as f32 / 1.0e9);
} }
} }

View file

@ -1,17 +1,17 @@
pub mod render;
pub mod asset;
mod app; mod app;
mod vertex; pub mod asset;
mod core; mod core;
pub mod render;
mod vertex;
pub use app::{App, AppStage, AppBuilder};
pub use crate::core::*; pub use crate::core::*;
pub use app::{App, AppBuilder, AppStage};
pub use wgpu; pub use glam as math;
pub use legion; pub use legion;
pub use legion_transform;
pub use legion::prelude::*; pub use legion::prelude::*;
pub use legion::schedule::Schedulable; pub use legion::schedule::Schedulable;
pub use legion_transform;
pub use legion_transform::prelude::*; pub use legion_transform::prelude::*;
pub use legion_transform::transform_system_bundle; pub use legion_transform::transform_system_bundle;
pub use glam as math; pub use wgpu;

View file

@ -8,7 +8,7 @@ pub enum CameraType {
fov: f32, fov: f32,
aspect_ratio: f32, aspect_ratio: f32,
near: f32, near: f32,
far: f32 far: f32,
}, },
Orthographic { Orthographic {
left: f32, left: f32,
@ -35,14 +35,28 @@ impl Camera {
pub fn update(&mut self, width: u32, height: u32) { pub fn update(&mut self, width: u32, height: u32) {
match &mut self.camera_type { match &mut self.camera_type {
CameraType::Projection { aspect_ratio, fov, near, far } => { CameraType::Projection {
aspect_ratio,
fov,
near,
far,
} => {
*aspect_ratio = width as f32 / height as f32; *aspect_ratio = width as f32 / height as f32;
self.view_matrix = get_perspective_projection_matrix(*fov, *aspect_ratio, *near, *far) self.view_matrix =
}, get_perspective_projection_matrix(*fov, *aspect_ratio, *near, *far)
CameraType::Orthographic { left, right, bottom, top, near, far} => { }
CameraType::Orthographic {
left,
right,
bottom,
top,
near,
far,
} => {
*right = width as f32; *right = width as f32;
*top = height as f32; *top = height as f32;
self.view_matrix = get_orthographic_projection_matrix(*left, *right, *bottom, *top, *near, *far) self.view_matrix =
get_orthographic_projection_matrix(*left, *right, *bottom, *top, *near, *far)
} }
} }
} }
@ -54,7 +68,14 @@ pub fn get_perspective_projection_matrix(fov: f32, aspect_ratio: f32, near: f32,
opengl_to_wgpu_matrix() * projection opengl_to_wgpu_matrix() * projection
} }
pub fn get_orthographic_projection_matrix(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32) -> Mat4 { pub fn get_orthographic_projection_matrix(
left: f32,
right: f32,
bottom: f32,
top: f32,
near: f32,
far: f32,
) -> Mat4 {
let projection = Mat4::orthographic_rh_gl(left, right, bottom, top, near, far); let projection = Mat4::orthographic_rh_gl(left, right, bottom, top, near, far);
opengl_to_wgpu_matrix() * projection opengl_to_wgpu_matrix() * projection
@ -62,9 +83,6 @@ pub fn get_orthographic_projection_matrix(left: f32, right: f32, bottom: f32, to
pub fn opengl_to_wgpu_matrix() -> Mat4 { pub fn opengl_to_wgpu_matrix() -> Mat4 {
Mat4::from_cols_array(&[ Mat4::from_cols_array(&[
1.0, 0.0, 0.0, 0.0, 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,
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

@ -2,4 +2,4 @@ pub struct InstanceBufferInfo {
pub buffer: wgpu::Buffer, pub buffer: wgpu::Buffer,
pub instance_count: usize, pub instance_count: usize,
pub mesh_id: usize, pub mesh_id: usize,
} }

View file

@ -2,7 +2,6 @@ use crate::{math, render::camera, Translation};
use std::ops::Range; use std::ops::Range;
use zerocopy::{AsBytes, FromBytes}; use zerocopy::{AsBytes, FromBytes};
pub struct Light { pub struct Light {
pub color: wgpu::Color, pub color: wgpu::Color,
pub fov: f32, pub fov: f32,
@ -20,7 +19,12 @@ pub struct LightRaw {
impl LightRaw { impl LightRaw {
pub fn from(light: &Light, transform: &math::Mat4, translation: &Translation) -> LightRaw { pub fn from(light: &Light, transform: &math::Mat4, translation: &Translation) -> LightRaw {
let proj = camera::get_perspective_projection_matrix(light.fov, 1.0, light.depth.start, light.depth.end) * *transform; let proj = camera::get_perspective_projection_matrix(
light.fov,
1.0,
light.depth.start,
light.depth.end,
) * *transform;
let (x, y, z) = translation.0.into(); let (x, y, z) = translation.0.into();
LightRaw { LightRaw {
proj: proj.to_cols_array_2d(), proj: proj.to_cols_array_2d(),
@ -33,4 +37,4 @@ impl LightRaw {
], ],
} }
} }
} }

View file

@ -1,5 +1,5 @@
use zerocopy::{AsBytes, FromBytes};
use crate::math; use crate::math;
use zerocopy::{AsBytes, FromBytes};
pub struct Material { pub struct Material {
pub color: math::Vec4, pub color: math::Vec4,
@ -14,7 +14,7 @@ impl Material {
Material { Material {
color, color,
bind_group: None, bind_group: None,
uniform_buf: None, uniform_buf: None,
} }
} }
} }
@ -37,4 +37,4 @@ pub struct MaterialUniforms {
pub struct SimpleMaterialUniforms { pub struct SimpleMaterialUniforms {
pub position: [f32; 3], pub position: [f32; 3],
pub color: [f32; 4], pub color: [f32; 4],
} }

View file

@ -1,4 +1,4 @@
use crate::{vertex::Vertex, asset::Asset, math::*}; use crate::{asset::Asset, math::*, vertex::Vertex};
use wgpu::{Buffer, Device}; use wgpu::{Buffer, Device};
use zerocopy::AsBytes; use zerocopy::AsBytes;
@ -8,14 +8,14 @@ pub struct Mesh2d;
pub enum MeshType { pub enum MeshType {
Cube, Cube,
Plane { Plane {
size: f32 size: f32,
}, },
Quad { Quad {
north_west: Vec2, north_west: Vec2,
north_east: Vec2, north_east: Vec2,
south_west: Vec2, south_west: Vec2,
south_east: Vec2, south_east: Vec2,
} },
} }
pub struct Mesh { pub struct Mesh {
@ -28,11 +28,15 @@ pub struct Mesh {
impl Mesh { impl Mesh {
pub fn setup_buffers(&mut self, device: &Device) { pub fn setup_buffers(&mut self, device: &Device) {
if let None = self.vertex_buffer { if let None = self.vertex_buffer {
self.vertex_buffer = Some(device.create_buffer_with_data(self.vertices.as_bytes(), wgpu::BufferUsage::VERTEX)); self.vertex_buffer = Some(
device.create_buffer_with_data(self.vertices.as_bytes(), wgpu::BufferUsage::VERTEX),
);
} }
if let None = self.index_buffer { if let None = self.index_buffer {
self.index_buffer = Some(device.create_buffer_with_data(self.indices.as_bytes(), wgpu::BufferUsage::INDEX)); self.index_buffer = Some(
device.create_buffer_with_data(self.indices.as_bytes(), wgpu::BufferUsage::INDEX),
);
} }
} }
} }
@ -42,7 +46,12 @@ impl Asset<MeshType> for Mesh {
let (vertices, indices) = match descriptor { let (vertices, indices) = match descriptor {
MeshType::Cube => create_cube(), MeshType::Cube => create_cube(),
MeshType::Plane { size } => create_plane(size), MeshType::Plane { size } => create_plane(size),
MeshType::Quad { north_west, north_east, south_west, south_east } => create_quad(north_west, north_east, south_west, south_east), MeshType::Quad {
north_west,
north_east,
south_west,
south_east,
} => create_quad(north_west, north_east, south_west, south_east),
}; };
Mesh { Mesh {
@ -54,7 +63,12 @@ impl Asset<MeshType> for Mesh {
} }
} }
pub fn create_quad(north_west: Vec2, north_east: Vec2, south_west: Vec2, south_east: Vec2) -> (Vec<Vertex>, Vec<u16>) { pub fn create_quad(
north_west: Vec2,
north_east: Vec2,
south_west: Vec2,
south_east: Vec2,
) -> (Vec<Vertex>, Vec<u16>) {
let vertex_data = [ let vertex_data = [
Vertex::from(([south_west.x(), south_west.y(), 0.0], [0.0, 0.0, 1.0])), Vertex::from(([south_west.x(), south_west.y(), 0.0], [0.0, 0.0, 1.0])),
Vertex::from(([north_west.x(), north_west.y(), 0.0], [0.0, 0.0, 1.0])), Vertex::from(([north_west.x(), north_west.y(), 0.0], [0.0, 0.0, 1.0])),
@ -62,7 +76,7 @@ pub fn create_quad(north_west: Vec2, north_east: Vec2, south_west: Vec2, south_e
Vertex::from(([south_east.x(), south_east.y(), 0.0], [0.0, 0.0, 1.0])), Vertex::from(([south_east.x(), south_east.y(), 0.0], [0.0, 0.0, 1.0])),
]; ];
let index_data: &[u16] = &[ 0, 1, 2, 0, 2, 3 ]; let index_data: &[u16] = &[0, 1, 2, 0, 2, 3];
return (vertex_data.to_vec(), index_data.to_vec()); return (vertex_data.to_vec(), index_data.to_vec());
} }
@ -124,4 +138,4 @@ pub fn create_plane(size: f32) -> (Vec<Vertex>, Vec<u16>) {
let index_data: &[u16] = &[0, 1, 2, 2, 1, 3]; let index_data: &[u16] = &[0, 1, 2, 2, 1, 3];
(vertex_data.to_vec(), index_data.to_vec()) (vertex_data.to_vec(), index_data.to_vec())
} }

View file

@ -1,25 +1,25 @@
pub mod camera; pub mod camera;
pub mod shader;
pub mod mesh;
pub mod render_resources;
pub mod passes;
pub mod instancing; pub mod instancing;
pub mod mesh;
pub mod passes;
pub mod render_resources;
pub mod shader;
mod light; mod light;
mod render_graph;
mod material; mod material;
mod rect; mod rect;
mod render_graph;
pub use camera::*;
pub use light::*; pub use light::*;
pub use shader::*;
pub use render_graph::*;
pub use material::*; pub use material::*;
pub use mesh::*; pub use mesh::*;
pub use camera::*;
pub use rect::*; pub use rect::*;
pub use render_graph::*;
pub use shader::*;
use std::mem;
use crate::vertex::Vertex; use crate::vertex::Vertex;
use std::mem;
pub struct UniformBuffer { pub struct UniformBuffer {
pub buffer: wgpu::Buffer, pub buffer: wgpu::Buffer,
@ -30,7 +30,7 @@ impl UniformBuffer {
pub fn get_binding_resource<'a>(&'a self) -> wgpu::BindingResource<'a> { pub fn get_binding_resource<'a>(&'a self) -> wgpu::BindingResource<'a> {
wgpu::BindingResource::Buffer { wgpu::BindingResource::Buffer {
buffer: &self.buffer, buffer: &self.buffer,
range: 0 .. self.size, range: 0..self.size,
} }
} }
} }
@ -53,4 +53,4 @@ pub fn get_vertex_buffer_descriptor<'a>() -> wgpu::VertexBufferDescriptor<'a> {
}, },
], ],
} }
} }

View file

@ -1,7 +1,7 @@
use crate::render::*; use crate::render::*;
use legion::prelude::*; use legion::prelude::*;
use zerocopy::{AsBytes, FromBytes};
use wgpu::{Device, SwapChainDescriptor}; use wgpu::{Device, SwapChainDescriptor};
use zerocopy::{AsBytes, FromBytes};
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, AsBytes, FromBytes)] #[derive(Clone, Copy, AsBytes, FromBytes)]
@ -16,11 +16,13 @@ pub struct ForwardPass {
impl ForwardPass { impl ForwardPass {
pub fn new(depth_format: wgpu::TextureFormat) -> Self { pub fn new(depth_format: wgpu::TextureFormat) -> Self {
ForwardPass { ForwardPass { depth_format }
depth_format,
}
} }
fn get_depth_texture(&self, device: &Device, swap_chain_descriptor: &SwapChainDescriptor) -> wgpu::TextureView { fn get_depth_texture(
&self,
device: &Device,
swap_chain_descriptor: &SwapChainDescriptor,
) -> wgpu::TextureView {
let texture = device.create_texture(&wgpu::TextureDescriptor { let texture = device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d { size: wgpu::Extent3d {
width: swap_chain_descriptor.width, width: swap_chain_descriptor.width,
@ -42,11 +44,18 @@ impl ForwardPass {
const DEPTH_TEXTURE_NAME: &str = "forward_depth"; const DEPTH_TEXTURE_NAME: &str = "forward_depth";
impl Pass for ForwardPass { impl Pass for ForwardPass {
fn initialize(&self, render_graph: &mut RenderGraphData) { fn initialize(&self, render_graph: &mut RenderGraphData) {
let depth_texture = self.get_depth_texture(&render_graph.device, &render_graph.swap_chain_descriptor); let depth_texture =
self.get_depth_texture(&render_graph.device, &render_graph.swap_chain_descriptor);
render_graph.set_texture(DEPTH_TEXTURE_NAME, depth_texture); render_graph.set_texture(DEPTH_TEXTURE_NAME, depth_texture);
} }
fn begin<'a>(&mut self, render_graph: &mut RenderGraphData, _: &mut World, encoder: &'a mut wgpu::CommandEncoder, frame: &'a wgpu::SwapChainOutput) -> Option<wgpu::RenderPass<'a>> { fn begin<'a>(
&mut self,
render_graph: &mut RenderGraphData,
_: &mut World,
encoder: &'a mut wgpu::CommandEncoder,
frame: &'a wgpu::SwapChainOutput,
) -> Option<wgpu::RenderPass<'a>> {
let depth_texture = render_graph.get_texture(DEPTH_TEXTURE_NAME); let depth_texture = render_graph.get_texture(DEPTH_TEXTURE_NAME);
Some(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { Some(encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
@ -74,11 +83,12 @@ impl Pass for ForwardPass {
} }
fn resize(&self, render_graph: &mut RenderGraphData) { fn resize(&self, render_graph: &mut RenderGraphData) {
let depth_texture = self.get_depth_texture(&render_graph.device, &render_graph.swap_chain_descriptor); let depth_texture =
self.get_depth_texture(&render_graph.device, &render_graph.swap_chain_descriptor);
render_graph.set_texture(DEPTH_TEXTURE_NAME, depth_texture); render_graph.set_texture(DEPTH_TEXTURE_NAME, depth_texture);
} }
fn should_repeat(&self) -> bool { fn should_repeat(&self) -> bool {
false false
} }
} }

View file

@ -1,4 +1,4 @@
use crate::{render::*, asset::*, render::mesh::*}; use crate::{asset::*, render::mesh::*, render::*};
use legion::prelude::*; use legion::prelude::*;
use wgpu::SwapChainOutput; use wgpu::SwapChainOutput;
@ -13,120 +13,135 @@ impl ForwardPipeline {
ForwardPipeline { ForwardPipeline {
pipeline: None, pipeline: None,
bind_group: None, bind_group: None,
depth_format: wgpu::TextureFormat::Depth32Float depth_format: wgpu::TextureFormat::Depth32Float,
} }
} }
} }
impl Pipeline for ForwardPipeline { impl Pipeline for ForwardPipeline {
fn initialize(&mut self, render_graph: &mut RenderGraphData, _: &mut World) { fn initialize(&mut self, render_graph: &mut RenderGraphData, _: &mut World) {
let vs_bytes = shader::load_glsl( let vs_bytes = shader::load_glsl(include_str!("forward.vert"), shader::ShaderStage::Vertex);
include_str!("forward.vert"), let fs_bytes =
shader::ShaderStage::Vertex, shader::load_glsl(include_str!("forward.frag"), shader::ShaderStage::Fragment);
);
let fs_bytes = shader::load_glsl(
include_str!("forward.frag"),
shader::ShaderStage::Fragment,
);
let bind_group_layout = let bind_group_layout =
render_graph.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { render_graph
bindings: &[ .device
wgpu::BindGroupLayoutBinding { .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
binding: 0, // global bindings: &[
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, binding: 0, // global
}, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
wgpu::BindGroupLayoutBinding { ty: wgpu::BindingType::UniformBuffer { dynamic: false },
binding: 1, // lights },
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, binding: 1, // lights
} visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
], ty: wgpu::BindingType::UniformBuffer { dynamic: false },
}); },
],
});
self.bind_group = Some({ self.bind_group = Some({
let forward_uniform_buffer = render_graph
let forward_uniform_buffer = render_graph.get_uniform_buffer(render_resources::FORWARD_UNIFORM_BUFFER_NAME).unwrap(); .get_uniform_buffer(render_resources::FORWARD_UNIFORM_BUFFER_NAME)
let light_uniform_buffer = render_graph.get_uniform_buffer(render_resources::LIGHT_UNIFORM_BUFFER_NAME).unwrap(); .unwrap();
let light_uniform_buffer = render_graph
.get_uniform_buffer(render_resources::LIGHT_UNIFORM_BUFFER_NAME)
.unwrap();
// Create bind group // Create bind group
render_graph.device.create_bind_group(&wgpu::BindGroupDescriptor { render_graph
layout: &bind_group_layout, .device
bindings: &[ .create_bind_group(&wgpu::BindGroupDescriptor {
wgpu::Binding { layout: &bind_group_layout,
binding: 0, bindings: &[
resource: forward_uniform_buffer.get_binding_resource(), wgpu::Binding {
}, binding: 0,
wgpu::Binding { resource: forward_uniform_buffer.get_binding_resource(),
binding: 1, },
resource: light_uniform_buffer.get_binding_resource(), wgpu::Binding {
} binding: 1,
], resource: light_uniform_buffer.get_binding_resource(),
}) },
],
})
}); });
let material_bind_group_layout = render_graph.get_bind_group_layout(render_resources::MATERIAL_BIND_GROUP_LAYOUT_NAME).unwrap(); let material_bind_group_layout = render_graph
.get_bind_group_layout(render_resources::MATERIAL_BIND_GROUP_LAYOUT_NAME)
.unwrap();
let pipeline_layout = render_graph.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let pipeline_layout =
bind_group_layouts: &[&bind_group_layout, material_bind_group_layout], render_graph
}); .device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout, material_bind_group_layout],
});
let vertex_buffer_descriptor = get_vertex_buffer_descriptor(); let vertex_buffer_descriptor = get_vertex_buffer_descriptor();
let vs_module = render_graph.device.create_shader_module(&vs_bytes); let vs_module = render_graph.device.create_shader_module(&vs_bytes);
let fs_module = render_graph.device.create_shader_module(&fs_bytes); let fs_module = render_graph.device.create_shader_module(&fs_bytes);
self.pipeline = Some(render_graph.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { self.pipeline = Some(render_graph.device.create_render_pipeline(
layout: &pipeline_layout, &wgpu::RenderPipelineDescriptor {
vertex_stage: wgpu::ProgrammableStageDescriptor { layout: &pipeline_layout,
module: &vs_module, vertex_stage: wgpu::ProgrammableStageDescriptor {
entry_point: "main", module: &vs_module,
}, entry_point: "main",
fragment_stage: Some(wgpu::ProgrammableStageDescriptor { },
module: &fs_module, fragment_stage: Some(wgpu::ProgrammableStageDescriptor {
entry_point: "main", module: &fs_module,
}), entry_point: "main",
rasterization_state: Some(wgpu::RasterizationStateDescriptor { }),
front_face: wgpu::FrontFace::Ccw, rasterization_state: Some(wgpu::RasterizationStateDescriptor {
cull_mode: wgpu::CullMode::Back, front_face: wgpu::FrontFace::Ccw,
depth_bias: 0, cull_mode: wgpu::CullMode::Back,
depth_bias_slope_scale: 0.0, depth_bias: 0,
depth_bias_clamp: 0.0, depth_bias_slope_scale: 0.0,
}), depth_bias_clamp: 0.0,
primitive_topology: wgpu::PrimitiveTopology::TriangleList, }),
color_states: &[ primitive_topology: wgpu::PrimitiveTopology::TriangleList,
wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
format: render_graph.swap_chain_descriptor.format, format: render_graph.swap_chain_descriptor.format,
color_blend: wgpu::BlendDescriptor::REPLACE, color_blend: wgpu::BlendDescriptor::REPLACE,
alpha_blend: wgpu::BlendDescriptor::REPLACE, alpha_blend: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}, }],
], depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor { format: self.depth_format,
format: self.depth_format, depth_write_enabled: true,
depth_write_enabled: true, depth_compare: wgpu::CompareFunction::Less,
depth_compare: wgpu::CompareFunction::Less, stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE, stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE, stencil_read_mask: 0,
stencil_read_mask: 0, stencil_write_mask: 0,
stencil_write_mask: 0, }),
}), index_format: wgpu::IndexFormat::Uint16,
index_format: wgpu::IndexFormat::Uint16, vertex_buffers: &[vertex_buffer_descriptor],
vertex_buffers: &[vertex_buffer_descriptor], sample_count: 1,
sample_count: 1, sample_mask: !0,
sample_mask: !0, alpha_to_coverage_enabled: false,
alpha_to_coverage_enabled: false, },
})); ));
} }
fn render(&mut self, render_graph: &RenderGraphData, pass: &mut wgpu::RenderPass, _: &SwapChainOutput, world: &mut World) { fn render(
&mut self,
render_graph: &RenderGraphData,
pass: &mut wgpu::RenderPass,
_: &SwapChainOutput,
world: &mut World,
) {
pass.set_bind_group(0, self.bind_group.as_ref().unwrap(), &[]); pass.set_bind_group(0, self.bind_group.as_ref().unwrap(), &[]);
let mut mesh_storage = world.resources.get_mut::<AssetStorage<Mesh, MeshType>>().unwrap(); let mut mesh_storage = world
.resources
.get_mut::<AssetStorage<Mesh, MeshType>>()
.unwrap();
let mut last_mesh_id = None; let mut last_mesh_id = None;
let mut mesh_query = let mut mesh_query =
<(Read<Material>, Read<Handle<Mesh>>)>::query() <(Read<Material>, Read<Handle<Mesh>>)>::query().filter(!component::<Instanced>());
.filter(!component::<Instanced>());
for (material, mesh) in mesh_query.iter_immutable(world) { for (material, mesh) in mesh_query.iter_immutable(world) {
let current_mesh_id = *mesh.id.read().unwrap(); let current_mesh_id = *mesh.id.read().unwrap();
@ -145,17 +160,16 @@ impl Pipeline for ForwardPipeline {
if let Some(ref mesh_asset) = mesh_storage.get(*mesh.id.read().unwrap()) { if let Some(ref mesh_asset) = mesh_storage.get(*mesh.id.read().unwrap()) {
pass.set_bind_group(1, material.bind_group.as_ref().unwrap(), &[]); pass.set_bind_group(1, material.bind_group.as_ref().unwrap(), &[]);
pass.draw_indexed(0 .. mesh_asset.indices.len() as u32, 0, 0 .. 1); pass.draw_indexed(0..mesh_asset.indices.len() as u32, 0, 0..1);
}; };
last_mesh_id = Some(current_mesh_id); last_mesh_id = Some(current_mesh_id);
} }
} }
fn resize(&mut self, _: &RenderGraphData) { fn resize(&mut self, _: &RenderGraphData) {}
}
fn get_pipeline(&self) -> &wgpu::RenderPipeline { fn get_pipeline(&self) -> &wgpu::RenderPipeline {
self.pipeline.as_ref().unwrap() self.pipeline.as_ref().unwrap()
} }
} }

View file

@ -1,5 +1,5 @@
mod forward_pipeline;
mod forward_pass; mod forward_pass;
mod forward_pipeline;
pub use forward_pass::*;
pub use forward_pipeline::*; pub use forward_pipeline::*;
pub use forward_pass::*;

View file

@ -1,8 +1,13 @@
use crate::{render::{*, instancing::InstanceBufferInfo}, asset::*, render::mesh::*, LocalToWorld}; use crate::{
asset::*,
render::mesh::*,
render::{instancing::InstanceBufferInfo, *},
LocalToWorld,
};
use legion::prelude::*; use legion::prelude::*;
use std::mem; use std::mem;
use zerocopy::AsBytes;
use wgpu::{Device, SwapChainOutput}; use wgpu::{Device, SwapChainOutput};
use zerocopy::AsBytes;
pub struct ForwardInstancedPipeline { pub struct ForwardInstancedPipeline {
pub pipeline: Option<wgpu::RenderPipeline>, pub pipeline: Option<wgpu::RenderPipeline>,
@ -22,7 +27,12 @@ impl ForwardInstancedPipeline {
} }
fn create_instance_buffer_infos(device: &Device, world: &World) -> Vec<InstanceBufferInfo> { fn create_instance_buffer_infos(device: &Device, world: &World) -> Vec<InstanceBufferInfo> {
let mut entities = <(Read<Material>, Read<LocalToWorld>, Read<Handle<Mesh>>, Read<Instanced>)>::query(); let mut entities = <(
Read<Material>,
Read<LocalToWorld>,
Read<Handle<Mesh>>,
Read<Instanced>,
)>::query();
let entities_count = entities.iter_immutable(world).count(); let entities_count = entities.iter_immutable(world).count();
if entities_count == 0 { if entities_count == 0 {
return Vec::new(); return Vec::new();
@ -31,16 +41,18 @@ impl ForwardInstancedPipeline {
let size = mem::size_of::<SimpleMaterialUniforms>(); let size = mem::size_of::<SimpleMaterialUniforms>();
// TODO: use a staging buffer for more efficient gpu reads // TODO: use a staging buffer for more efficient gpu reads
let temp_buf_data = device let temp_buf_data = device.create_buffer_mapped(
.create_buffer_mapped(entities_count * size, wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::VERTEX); entities_count * size,
wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::VERTEX,
);
// TODO: generate these buffers for multiple meshes // TODO: generate these buffers for multiple meshes
let mut last_mesh_id = None; let mut last_mesh_id = None;
for ((material, transform, mesh, _), slot) in entities.iter_immutable(world) for ((material, transform, mesh, _), slot) in entities
.iter_immutable(world)
.zip(temp_buf_data.data.chunks_exact_mut(size)) .zip(temp_buf_data.data.chunks_exact_mut(size))
{ {
last_mesh_id = Some(*mesh.id.read().unwrap()); last_mesh_id = Some(*mesh.id.read().unwrap());
let (_, _, translation) = transform.0.to_scale_rotation_translation(); let (_, _, translation) = transform.0.to_scale_rotation_translation();
slot.copy_from_slice( slot.copy_from_slice(
@ -51,7 +63,7 @@ impl ForwardInstancedPipeline {
.as_bytes(), .as_bytes(),
); );
} }
let mut instance_buffer_infos = Vec::new(); let mut instance_buffer_infos = Vec::new();
instance_buffer_infos.push(InstanceBufferInfo { instance_buffer_infos.push(InstanceBufferInfo {
mesh_id: last_mesh_id.unwrap(), mesh_id: last_mesh_id.unwrap(),
@ -63,15 +75,21 @@ impl ForwardInstancedPipeline {
} }
#[allow(dead_code)] #[allow(dead_code)]
fn create_instance_buffer_infos_direct(device: &Device, world: &World) -> Vec<InstanceBufferInfo> { fn create_instance_buffer_infos_direct(
let mut entities = <(Read<Material>, Read<LocalToWorld>, Read<Handle<Mesh>>, Read<Instanced>)>::query(); device: &Device,
world: &World,
) -> Vec<InstanceBufferInfo> {
let mut entities = <(
Read<Material>,
Read<LocalToWorld>,
Read<Handle<Mesh>>,
Read<Instanced>,
)>::query();
let entities_count = entities.iter_immutable(world).count(); let entities_count = entities.iter_immutable(world).count();
let mut last_mesh_id = None; let mut last_mesh_id = None;
let mut data = Vec::with_capacity(entities_count); let mut data = Vec::with_capacity(entities_count);
for (material, transform, mesh, _) in entities.iter_immutable(world) for (material, transform, mesh, _) in entities.iter_immutable(world) {
{
last_mesh_id = Some(*mesh.id.read().unwrap()); last_mesh_id = Some(*mesh.id.read().unwrap());
let (_, _, translation) = transform.0.to_scale_rotation_translation(); let (_, _, translation) = transform.0.to_scale_rotation_translation();
@ -81,10 +99,11 @@ impl ForwardInstancedPipeline {
}); });
} }
let buffer = device let buffer = device.create_buffer_with_data(
.create_buffer_with_data(data.as_bytes(), wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::VERTEX); data.as_bytes(),
wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::VERTEX,
);
let mut instance_buffer_infos = Vec::new(); let mut instance_buffer_infos = Vec::new();
instance_buffer_infos.push(InstanceBufferInfo { instance_buffer_infos.push(InstanceBufferInfo {
mesh_id: last_mesh_id.unwrap(), mesh_id: last_mesh_id.unwrap(),
@ -108,40 +127,48 @@ impl Pipeline for ForwardInstancedPipeline {
); );
let bind_group_layout = let bind_group_layout =
render_graph.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { render_graph
bindings: &[ .device
wgpu::BindGroupLayoutBinding { .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
binding: 0, // global bindings: &[
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, binding: 0, // global
}, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
wgpu::BindGroupLayoutBinding { ty: wgpu::BindingType::UniformBuffer { dynamic: false },
binding: 1, // lights },
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, binding: 1, // lights
} visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
], ty: wgpu::BindingType::UniformBuffer { dynamic: false },
}); },
],
});
// TODO: this is the same as normal forward pipeline. we can probably reuse // TODO: this is the same as normal forward pipeline. we can probably reuse
self.local_bind_group = Some({ self.local_bind_group = Some({
let forward_uniform_buffer = render_graph.get_uniform_buffer(render_resources::FORWARD_UNIFORM_BUFFER_NAME).unwrap(); let forward_uniform_buffer = render_graph
let light_uniform_buffer = render_graph.get_uniform_buffer(render_resources::LIGHT_UNIFORM_BUFFER_NAME).unwrap(); .get_uniform_buffer(render_resources::FORWARD_UNIFORM_BUFFER_NAME)
.unwrap();
let light_uniform_buffer = render_graph
.get_uniform_buffer(render_resources::LIGHT_UNIFORM_BUFFER_NAME)
.unwrap();
// Create bind group // Create bind group
render_graph.device.create_bind_group(&wgpu::BindGroupDescriptor { render_graph
layout: &bind_group_layout, .device
bindings: &[ .create_bind_group(&wgpu::BindGroupDescriptor {
wgpu::Binding { layout: &bind_group_layout,
binding: 0, bindings: &[
resource: forward_uniform_buffer.get_binding_resource(), wgpu::Binding {
}, binding: 0,
wgpu::Binding { resource: forward_uniform_buffer.get_binding_resource(),
binding: 1, },
resource: light_uniform_buffer.get_binding_resource(), wgpu::Binding {
} binding: 1,
], resource: light_uniform_buffer.get_binding_resource(),
}) },
],
})
}); });
let simple_material_uniforms_size = mem::size_of::<SimpleMaterialUniforms>(); let simple_material_uniforms_size = mem::size_of::<SimpleMaterialUniforms>();
@ -164,79 +191,99 @@ impl Pipeline for ForwardInstancedPipeline {
let vertex_buffer_descriptor = get_vertex_buffer_descriptor(); let vertex_buffer_descriptor = get_vertex_buffer_descriptor();
let pipeline_layout = render_graph.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let pipeline_layout =
bind_group_layouts: &[&bind_group_layout], render_graph
}); .device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout],
});
let vs_module = render_graph.device.create_shader_module(&vs_bytes); let vs_module = render_graph.device.create_shader_module(&vs_bytes);
let fs_module = render_graph.device.create_shader_module(&fs_bytes); let fs_module = render_graph.device.create_shader_module(&fs_bytes);
self.pipeline = Some(render_graph.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { self.pipeline = Some(render_graph.device.create_render_pipeline(
layout: &pipeline_layout, &wgpu::RenderPipelineDescriptor {
vertex_stage: wgpu::ProgrammableStageDescriptor { layout: &pipeline_layout,
module: &vs_module, vertex_stage: wgpu::ProgrammableStageDescriptor {
entry_point: "main", module: &vs_module,
}, entry_point: "main",
fragment_stage: Some(wgpu::ProgrammableStageDescriptor { },
module: &fs_module, fragment_stage: Some(wgpu::ProgrammableStageDescriptor {
entry_point: "main", module: &fs_module,
}), entry_point: "main",
rasterization_state: Some(wgpu::RasterizationStateDescriptor { }),
front_face: wgpu::FrontFace::Ccw, rasterization_state: Some(wgpu::RasterizationStateDescriptor {
cull_mode: wgpu::CullMode::Back, front_face: wgpu::FrontFace::Ccw,
depth_bias: 0, cull_mode: wgpu::CullMode::Back,
depth_bias_slope_scale: 0.0, depth_bias: 0,
depth_bias_clamp: 0.0, depth_bias_slope_scale: 0.0,
}), depth_bias_clamp: 0.0,
primitive_topology: wgpu::PrimitiveTopology::TriangleList, }),
color_states: &[ primitive_topology: wgpu::PrimitiveTopology::TriangleList,
wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
format: render_graph.swap_chain_descriptor.format, format: render_graph.swap_chain_descriptor.format,
color_blend: wgpu::BlendDescriptor::REPLACE, color_blend: wgpu::BlendDescriptor::REPLACE,
alpha_blend: wgpu::BlendDescriptor::REPLACE, alpha_blend: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}, }],
], depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor { format: self.depth_format,
format: self.depth_format, depth_write_enabled: true,
depth_write_enabled: true, depth_compare: wgpu::CompareFunction::Less,
depth_compare: wgpu::CompareFunction::Less, stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE, stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE, stencil_read_mask: 0,
stencil_read_mask: 0, stencil_write_mask: 0,
stencil_write_mask: 0, }),
}), index_format: wgpu::IndexFormat::Uint16,
index_format: wgpu::IndexFormat::Uint16, vertex_buffers: &[vertex_buffer_descriptor, instance_buffer_descriptor],
vertex_buffers: &[vertex_buffer_descriptor, instance_buffer_descriptor], sample_count: 1,
sample_count: 1, sample_mask: !0,
sample_mask: !0, alpha_to_coverage_enabled: false,
alpha_to_coverage_enabled: false, },
})); ));
self.instance_buffer_infos = Some(Self::create_instance_buffer_infos(&render_graph.device, world)); self.instance_buffer_infos = Some(Self::create_instance_buffer_infos(
&render_graph.device,
world,
));
} }
fn render(&mut self, render_graph: &RenderGraphData, pass: &mut wgpu::RenderPass, _: &SwapChainOutput, world: &mut World) { fn render(
self.instance_buffer_infos = Some(Self::create_instance_buffer_infos(&render_graph.device, world)); &mut self,
render_graph: &RenderGraphData,
pass: &mut wgpu::RenderPass,
_: &SwapChainOutput,
world: &mut World,
) {
self.instance_buffer_infos = Some(Self::create_instance_buffer_infos(
&render_graph.device,
world,
));
pass.set_bind_group(0, self.local_bind_group.as_ref().unwrap(), &[]); pass.set_bind_group(0, self.local_bind_group.as_ref().unwrap(), &[]);
let mut mesh_storage = world.resources.get_mut::<AssetStorage<Mesh, MeshType>>().unwrap(); let mut mesh_storage = world
.resources
.get_mut::<AssetStorage<Mesh, MeshType>>()
.unwrap();
for instance_buffer_info in self.instance_buffer_infos.as_ref().unwrap().iter() { for instance_buffer_info in self.instance_buffer_infos.as_ref().unwrap().iter() {
if let Some(mesh_asset) = mesh_storage.get(instance_buffer_info.mesh_id) { if let Some(mesh_asset) = mesh_storage.get(instance_buffer_info.mesh_id) {
mesh_asset.setup_buffers(&render_graph.device); mesh_asset.setup_buffers(&render_graph.device);
pass.set_index_buffer(mesh_asset.index_buffer.as_ref().unwrap(), 0); 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.set_vertex_buffers(0, &[(&mesh_asset.vertex_buffer.as_ref().unwrap(), 0)]);
pass.set_vertex_buffers(1, &[(&instance_buffer_info.buffer, 0)]); pass.set_vertex_buffers(1, &[(&instance_buffer_info.buffer, 0)]);
pass.draw_indexed(0 .. mesh_asset.indices.len() as u32, 0, 0 .. instance_buffer_info.instance_count as u32); pass.draw_indexed(
0..mesh_asset.indices.len() as u32,
0,
0..instance_buffer_info.instance_count as u32,
);
}; };
} }
} }
fn resize(&mut self, _: &RenderGraphData) { fn resize(&mut self, _: &RenderGraphData) {}
}
fn get_pipeline(&self) -> &wgpu::RenderPipeline { fn get_pipeline(&self) -> &wgpu::RenderPipeline {
self.pipeline.as_ref().unwrap() self.pipeline.as_ref().unwrap()
} }
} }

View file

@ -1,4 +1,4 @@
use crate::{render::*, render::passes::shadow, asset::*, render::mesh::*}; use crate::{asset::*, render::mesh::*, render::passes::shadow, render::*};
use legion::prelude::*; use legion::prelude::*;
use wgpu::SwapChainOutput; use wgpu::SwapChainOutput;
@ -30,138 +30,163 @@ impl Pipeline for ForwardShadowPassNew {
); );
let bind_group_layout = let bind_group_layout =
render_graph.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { render_graph
bindings: &[ .device
wgpu::BindGroupLayoutBinding { .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
binding: 0, // global bindings: &[
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, binding: 0, // global
}, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
wgpu::BindGroupLayoutBinding { ty: wgpu::BindingType::UniformBuffer { dynamic: false },
binding: 1, // lights },
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, binding: 1, // lights
}, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
wgpu::BindGroupLayoutBinding { ty: wgpu::BindingType::UniformBuffer { dynamic: false },
binding: 2, },
visibility: wgpu::ShaderStage::FRAGMENT, wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::SampledTexture { binding: 2,
multisampled: false, visibility: wgpu::ShaderStage::FRAGMENT,
dimension: wgpu::TextureViewDimension::D2Array, ty: wgpu::BindingType::SampledTexture {
}, multisampled: false,
}, dimension: wgpu::TextureViewDimension::D2Array,
wgpu::BindGroupLayoutBinding { },
binding: 3, },
visibility: wgpu::ShaderStage::FRAGMENT, wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::Sampler, binding: 3,
}, visibility: wgpu::ShaderStage::FRAGMENT,
], ty: wgpu::BindingType::Sampler,
}); },
],
});
self.bind_group = Some({ self.bind_group = Some({
let forward_uniform_buffer = render_graph.get_uniform_buffer(render_resources::FORWARD_UNIFORM_BUFFER_NAME).unwrap(); let forward_uniform_buffer = render_graph
let light_uniform_buffer = render_graph.get_uniform_buffer(render_resources::LIGHT_UNIFORM_BUFFER_NAME).unwrap(); .get_uniform_buffer(render_resources::FORWARD_UNIFORM_BUFFER_NAME)
let shadow_sampler = render_graph.get_sampler(shadow::SHADOW_SAMPLER_NAME).unwrap(); .unwrap();
let shadow_texture = render_graph.get_texture(shadow::SHADOW_TEXTURE_NAME).unwrap(); let light_uniform_buffer = render_graph
.get_uniform_buffer(render_resources::LIGHT_UNIFORM_BUFFER_NAME)
.unwrap();
let shadow_sampler = render_graph
.get_sampler(shadow::SHADOW_SAMPLER_NAME)
.unwrap();
let shadow_texture = render_graph
.get_texture(shadow::SHADOW_TEXTURE_NAME)
.unwrap();
// Create bind group // Create bind group
render_graph.device.create_bind_group(&wgpu::BindGroupDescriptor { render_graph
layout: &bind_group_layout, .device
bindings: &[ .create_bind_group(&wgpu::BindGroupDescriptor {
wgpu::Binding { layout: &bind_group_layout,
binding: 0, bindings: &[
resource: forward_uniform_buffer.get_binding_resource(), wgpu::Binding {
}, binding: 0,
wgpu::Binding { resource: forward_uniform_buffer.get_binding_resource(),
binding: 1, },
resource: light_uniform_buffer.get_binding_resource(), wgpu::Binding {
}, binding: 1,
wgpu::Binding { resource: light_uniform_buffer.get_binding_resource(),
binding: 2, },
resource: wgpu::BindingResource::TextureView(shadow_texture), wgpu::Binding {
}, binding: 2,
wgpu::Binding { resource: wgpu::BindingResource::TextureView(shadow_texture),
binding: 3, },
resource: wgpu::BindingResource::Sampler(shadow_sampler), wgpu::Binding {
}, binding: 3,
], resource: wgpu::BindingResource::Sampler(shadow_sampler),
}) },
],
})
}); });
let material_bind_group_layout = render_graph.get_bind_group_layout(render_resources::MATERIAL_BIND_GROUP_LAYOUT_NAME).unwrap(); let material_bind_group_layout = render_graph
.get_bind_group_layout(render_resources::MATERIAL_BIND_GROUP_LAYOUT_NAME)
.unwrap();
let pipeline_layout = render_graph.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let pipeline_layout =
bind_group_layouts: &[&bind_group_layout, material_bind_group_layout], render_graph
}); .device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout, material_bind_group_layout],
});
let vs_module = render_graph.device.create_shader_module(&vs_bytes); let vs_module = render_graph.device.create_shader_module(&vs_bytes);
let fs_module = render_graph.device.create_shader_module(&fs_bytes); let fs_module = render_graph.device.create_shader_module(&fs_bytes);
let vertex_buffer_descriptor = get_vertex_buffer_descriptor(); let vertex_buffer_descriptor = get_vertex_buffer_descriptor();
self.pipeline = Some(render_graph.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { self.pipeline = Some(render_graph.device.create_render_pipeline(
layout: &pipeline_layout, &wgpu::RenderPipelineDescriptor {
vertex_stage: wgpu::ProgrammableStageDescriptor { layout: &pipeline_layout,
module: &vs_module, vertex_stage: wgpu::ProgrammableStageDescriptor {
entry_point: "main", module: &vs_module,
}, entry_point: "main",
fragment_stage: Some(wgpu::ProgrammableStageDescriptor { },
module: &fs_module, fragment_stage: Some(wgpu::ProgrammableStageDescriptor {
entry_point: "main", module: &fs_module,
}), entry_point: "main",
rasterization_state: Some(wgpu::RasterizationStateDescriptor { }),
front_face: wgpu::FrontFace::Ccw, rasterization_state: Some(wgpu::RasterizationStateDescriptor {
cull_mode: wgpu::CullMode::Back, front_face: wgpu::FrontFace::Ccw,
depth_bias: 0, cull_mode: wgpu::CullMode::Back,
depth_bias_slope_scale: 0.0, depth_bias: 0,
depth_bias_clamp: 0.0, depth_bias_slope_scale: 0.0,
}), depth_bias_clamp: 0.0,
primitive_topology: wgpu::PrimitiveTopology::TriangleList, }),
color_states: &[ primitive_topology: wgpu::PrimitiveTopology::TriangleList,
wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
format: render_graph.swap_chain_descriptor.format, format: render_graph.swap_chain_descriptor.format,
color_blend: wgpu::BlendDescriptor::REPLACE, color_blend: wgpu::BlendDescriptor::REPLACE,
alpha_blend: wgpu::BlendDescriptor::REPLACE, alpha_blend: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}, }],
], depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor { format: self.depth_format,
format: self.depth_format, depth_write_enabled: true,
depth_write_enabled: true, depth_compare: wgpu::CompareFunction::Less,
depth_compare: wgpu::CompareFunction::Less, stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE, stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE, stencil_read_mask: 0,
stencil_read_mask: 0, stencil_write_mask: 0,
stencil_write_mask: 0, }),
}), index_format: wgpu::IndexFormat::Uint16,
index_format: wgpu::IndexFormat::Uint16, vertex_buffers: &[vertex_buffer_descriptor],
vertex_buffers: &[vertex_buffer_descriptor], sample_count: 1,
sample_count: 1, sample_mask: !0,
sample_mask: !0, alpha_to_coverage_enabled: false,
alpha_to_coverage_enabled: false, },
})); ));
} }
fn render(&mut self, render_graph: &RenderGraphData, pass: &mut wgpu::RenderPass, _swap_chain_output: &SwapChainOutput, world: &mut World) { fn render(
&mut self,
render_graph: &RenderGraphData,
pass: &mut wgpu::RenderPass,
_swap_chain_output: &SwapChainOutput,
world: &mut World,
) {
let mut mesh_query = <(Read<Material>, Read<Handle<Mesh>>)>::query(); let mut mesh_query = <(Read<Material>, Read<Handle<Mesh>>)>::query();
pass.set_bind_group(0, self.bind_group.as_ref().unwrap(), &[]); pass.set_bind_group(0, self.bind_group.as_ref().unwrap(), &[]);
let mut mesh_storage = world.resources.get_mut::<AssetStorage<Mesh, MeshType>>().unwrap(); let mut mesh_storage = world
.resources
.get_mut::<AssetStorage<Mesh, MeshType>>()
.unwrap();
for (material, mesh) in mesh_query.iter_immutable(world) { for (material, mesh) in mesh_query.iter_immutable(world) {
if let Some(mesh_asset) = mesh_storage.get(*mesh.id.read().unwrap()) { if let Some(mesh_asset) = mesh_storage.get(*mesh.id.read().unwrap()) {
mesh_asset.setup_buffers(&render_graph.device); mesh_asset.setup_buffers(&render_graph.device);
pass.set_bind_group(1, material.bind_group.as_ref().unwrap(), &[]); pass.set_bind_group(1, material.bind_group.as_ref().unwrap(), &[]);
pass.set_index_buffer(mesh_asset.index_buffer.as_ref().unwrap(), 0); 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.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); pass.draw_indexed(0..mesh_asset.indices.len() as u32, 0, 0..1);
}; };
} }
} }
fn resize(&mut self, _render_graph: &RenderGraphData) { fn resize(&mut self, _render_graph: &RenderGraphData) {}
}
fn get_pipeline(&self) -> &wgpu::RenderPipeline { fn get_pipeline(&self) -> &wgpu::RenderPipeline {
self.pipeline.as_ref().unwrap() self.pipeline.as_ref().unwrap()
} }
} }

View file

@ -1,12 +1,11 @@
mod forward; mod forward;
mod forward_shadow;
mod forward_instanced; mod forward_instanced;
mod forward_shadow;
mod shadow; mod shadow;
mod ui; mod ui;
pub use forward::{ForwardUniforms, ForwardPipeline, ForwardPass}; pub use forward::{ForwardPass, ForwardPipeline, ForwardUniforms};
pub use forward_shadow::{ForwardShadowPassNew};
pub use forward_instanced::ForwardInstancedPipeline; pub use forward_instanced::ForwardInstancedPipeline;
pub use forward_shadow::ForwardShadowPassNew;
pub use shadow::ShadowPass; pub use shadow::ShadowPass;
pub use ui::UiPipeline; pub use ui::UiPipeline;

View file

@ -2,4 +2,4 @@ mod shadow_pass;
mod shadow_pipeline; mod shadow_pipeline;
pub use shadow_pass::*; pub use shadow_pass::*;
pub use shadow_pipeline::*; pub use shadow_pipeline::*;

View file

@ -1,4 +1,4 @@
use crate::{render::*, render::passes::shadow, LocalToWorld, Translation}; use crate::{render::passes::shadow, render::*, LocalToWorld, Translation};
use legion::prelude::*; use legion::prelude::*;
use std::mem; use std::mem;
@ -13,7 +13,11 @@ pub struct ShadowPass {
pub const SHADOW_TEXTURE_NAME: &str = "shadow_texture"; pub const SHADOW_TEXTURE_NAME: &str = "shadow_texture";
impl ShadowPass { impl ShadowPass {
pub fn new(shadow_size: wgpu::Extent3d, shadow_format: wgpu::TextureFormat, max_lights: usize) -> Self { pub fn new(
shadow_size: wgpu::Extent3d,
shadow_format: wgpu::TextureFormat,
max_lights: usize,
) -> Self {
ShadowPass { ShadowPass {
light_index: -1, light_index: -1,
shadow_texture: None, shadow_texture: None,
@ -26,15 +30,17 @@ impl ShadowPass {
impl Pass for ShadowPass { impl Pass for ShadowPass {
fn initialize(&self, render_graph: &mut RenderGraphData) { fn initialize(&self, render_graph: &mut RenderGraphData) {
let shadow_texture = render_graph.device.create_texture(&wgpu::TextureDescriptor { let shadow_texture = render_graph
size: self.shadow_size, .device
array_layer_count: self.max_lights as u32, .create_texture(&wgpu::TextureDescriptor {
mip_level_count: 1, size: self.shadow_size,
sample_count: 1, array_layer_count: self.max_lights as u32,
dimension: wgpu::TextureDimension::D2, mip_level_count: 1,
format: self.shadow_format, sample_count: 1,
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT | wgpu::TextureUsage::SAMPLED, dimension: wgpu::TextureDimension::D2,
}); format: self.shadow_format,
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT | wgpu::TextureUsage::SAMPLED,
});
let shadow_view = shadow_texture.create_default_view(); let shadow_view = shadow_texture.create_default_view();
render_graph.set_texture(SHADOW_TEXTURE_NAME, shadow_view); render_graph.set_texture(SHADOW_TEXTURE_NAME, shadow_view);
@ -74,8 +80,12 @@ impl Pass for ShadowPass {
// The light uniform buffer already has the projection, // The light uniform buffer already has the projection,
// let's just copy it over to the shadow uniform buffer. // let's just copy it over to the shadow uniform buffer.
let light_uniform_buffer = render_graph.get_uniform_buffer(render_resources::LIGHT_UNIFORM_BUFFER_NAME).unwrap(); let light_uniform_buffer = render_graph
let shadow_pipeline_uniform_buffer = render_graph.get_uniform_buffer(shadow::SHADOW_PIPELINE_UNIFORMS).unwrap(); .get_uniform_buffer(render_resources::LIGHT_UNIFORM_BUFFER_NAME)
.unwrap();
let shadow_pipeline_uniform_buffer = render_graph
.get_uniform_buffer(shadow::SHADOW_PIPELINE_UNIFORMS)
.unwrap();
encoder.copy_buffer_to_buffer( encoder.copy_buffer_to_buffer(
&light_uniform_buffer.buffer, &light_uniform_buffer.buffer,
(i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress, (i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress,
@ -110,4 +120,4 @@ impl Pass for ShadowPass {
fn should_repeat(&self) -> bool { fn should_repeat(&self) -> bool {
return self.light_index != -1; return self.light_index != -1;
} }
} }

View file

@ -30,22 +30,27 @@ impl ShadowPipeline {
impl Pipeline for ShadowPipeline { impl Pipeline for ShadowPipeline {
fn initialize(&mut self, render_graph: &mut RenderGraphData, _: &mut World) { fn initialize(&mut self, render_graph: &mut RenderGraphData, _: &mut World) {
let bind_group_layout = render_graph.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { let bind_group_layout =
bindings: &[wgpu::BindGroupLayoutBinding { render_graph
binding: 0, // global .device
visibility: wgpu::ShaderStage::VERTEX, .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, bindings: &[wgpu::BindGroupLayoutBinding {
}], binding: 0, // global
}); visibility: wgpu::ShaderStage::VERTEX,
ty: wgpu::BindingType::UniformBuffer { dynamic: false },
}],
});
let material_bind_group_layout = render_graph.get_bind_group_layout(render_resources::MATERIAL_BIND_GROUP_LAYOUT_NAME).unwrap(); let material_bind_group_layout = render_graph
.get_bind_group_layout(render_resources::MATERIAL_BIND_GROUP_LAYOUT_NAME)
.unwrap();
let pipeline_layout = render_graph.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let pipeline_layout =
bind_group_layouts: &[ render_graph
&bind_group_layout, .device
material_bind_group_layout, .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
], bind_group_layouts: &[&bind_group_layout, material_bind_group_layout],
}); });
let uniform_size = mem::size_of::<ShadowUniforms>() as wgpu::BufferAddress; let uniform_size = mem::size_of::<ShadowUniforms>() as wgpu::BufferAddress;
let uniform_buf = render_graph.device.create_buffer(&wgpu::BufferDescriptor { let uniform_buf = render_graph.device.create_buffer(&wgpu::BufferDescriptor {
@ -54,81 +59,91 @@ impl Pipeline for ShadowPipeline {
}); });
// Create bind group // Create bind group
self.bind_group = Some(render_graph.device.create_bind_group(&wgpu::BindGroupDescriptor { self.bind_group = Some(
layout: &bind_group_layout, render_graph
bindings: &[wgpu::Binding { .device
binding: 0, .create_bind_group(&wgpu::BindGroupDescriptor {
resource: wgpu::BindingResource::Buffer { layout: &bind_group_layout,
buffer: &uniform_buf, bindings: &[wgpu::Binding {
range: 0..uniform_size, binding: 0,
}, resource: wgpu::BindingResource::Buffer {
}], buffer: &uniform_buf,
})); range: 0..uniform_size,
},
}],
}),
);
render_graph.set_uniform_buffer(SHADOW_PIPELINE_UNIFORMS, UniformBuffer { render_graph.set_uniform_buffer(
buffer: uniform_buf, SHADOW_PIPELINE_UNIFORMS,
size: uniform_size, UniformBuffer {
}); buffer: uniform_buf,
size: uniform_size,
},
);
// Create other resources // Create other resources
let shadow_sampler = render_graph.device.create_sampler(&wgpu::SamplerDescriptor { let shadow_sampler = render_graph
address_mode_u: wgpu::AddressMode::ClampToEdge, .device
address_mode_v: wgpu::AddressMode::ClampToEdge, .create_sampler(&wgpu::SamplerDescriptor {
address_mode_w: wgpu::AddressMode::ClampToEdge, address_mode_u: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear, address_mode_v: wgpu::AddressMode::ClampToEdge,
min_filter: wgpu::FilterMode::Linear, address_mode_w: wgpu::AddressMode::ClampToEdge,
mipmap_filter: wgpu::FilterMode::Nearest, mag_filter: wgpu::FilterMode::Linear,
lod_min_clamp: -100.0, min_filter: wgpu::FilterMode::Linear,
lod_max_clamp: 100.0, mipmap_filter: wgpu::FilterMode::Nearest,
compare_function: wgpu::CompareFunction::LessEqual, lod_min_clamp: -100.0,
}); lod_max_clamp: 100.0,
compare_function: wgpu::CompareFunction::LessEqual,
});
render_graph.set_sampler(SHADOW_SAMPLER_NAME, shadow_sampler); render_graph.set_sampler(SHADOW_SAMPLER_NAME, shadow_sampler);
let vertex_buffer_descriptor = get_vertex_buffer_descriptor(); let vertex_buffer_descriptor = get_vertex_buffer_descriptor();
// Create the render pipeline // Create the render pipeline
let vs_bytes = let vs_bytes = shader::load_glsl(include_str!("shadow.vert"), shader::ShaderStage::Vertex);
shader::load_glsl(include_str!("shadow.vert"), shader::ShaderStage::Vertex);
let fs_bytes = let fs_bytes =
shader::load_glsl(include_str!("shadow.frag"), shader::ShaderStage::Fragment); shader::load_glsl(include_str!("shadow.frag"), shader::ShaderStage::Fragment);
let vs_module = render_graph.device.create_shader_module(&vs_bytes); let vs_module = render_graph.device.create_shader_module(&vs_bytes);
let fs_module = render_graph.device.create_shader_module(&fs_bytes); let fs_module = render_graph.device.create_shader_module(&fs_bytes);
self.pipeline = Some(render_graph.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { self.pipeline = Some(render_graph.device.create_render_pipeline(
layout: &pipeline_layout, &wgpu::RenderPipelineDescriptor {
vertex_stage: wgpu::ProgrammableStageDescriptor { layout: &pipeline_layout,
module: &vs_module, vertex_stage: wgpu::ProgrammableStageDescriptor {
entry_point: "main", 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: 2, // corresponds to bilinear filtering
depth_bias_slope_scale: 2.0,
depth_bias_clamp: 0.0,
}),
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[],
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
format: self.shadow_format,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
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,
}, },
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: 2, // corresponds to bilinear filtering
depth_bias_slope_scale: 2.0,
depth_bias_clamp: 0.0,
}),
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[],
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
format: self.shadow_format,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
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,
}));
} }
fn render( fn render(
@ -163,4 +178,4 @@ impl Pipeline for ShadowPipeline {
fn get_pipeline(&self) -> &wgpu::RenderPipeline { fn get_pipeline(&self) -> &wgpu::RenderPipeline {
self.pipeline.as_ref().unwrap() self.pipeline.as_ref().unwrap()
} }
} }

View file

@ -1,7 +1,12 @@
use crate::{render::{*, instancing::InstanceBufferInfo}, asset::*, render::mesh::*, math}; use crate::{
asset::*,
math,
render::mesh::*,
render::{instancing::InstanceBufferInfo, *},
};
use legion::prelude::*; use legion::prelude::*;
use zerocopy::{AsBytes, FromBytes};
use wgpu::SwapChainOutput; use wgpu::SwapChainOutput;
use zerocopy::{AsBytes, FromBytes};
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, AsBytes, FromBytes)] #[derive(Clone, Copy, AsBytes, FromBytes)]
@ -25,11 +30,15 @@ impl UiPipeline {
pipeline: None, pipeline: None,
bind_group: None, bind_group: None,
quad: None, quad: None,
depth_format: wgpu::TextureFormat::Depth32Float depth_format: wgpu::TextureFormat::Depth32Float,
} }
} }
pub fn create_rect_buffers(&self, device: &wgpu::Device, world: &World) -> Vec<InstanceBufferInfo> { pub fn create_rect_buffers(
&self,
device: &wgpu::Device,
world: &World,
) -> Vec<InstanceBufferInfo> {
let mut rect_query = <Read<Rect>>::query(); let mut rect_query = <Read<Rect>>::query();
let rect_count = rect_query.iter_immutable(world).count(); let rect_count = rect_query.iter_immutable(world).count();
@ -40,21 +49,22 @@ impl UiPipeline {
let mut data = Vec::with_capacity(rect_count); let mut data = Vec::with_capacity(rect_count);
// TODO: this probably isn't the best way to handle z-ordering // TODO: this probably isn't the best way to handle z-ordering
let mut z = 0.9999; let mut z = 0.9999;
for rect in rect_query.iter_immutable(world) for rect in rect_query.iter_immutable(world) {
{
data.push(RectData { data.push(RectData {
position: rect.position.into(), position: rect.position.into(),
dimensions: rect.dimensions.into(), dimensions: rect.dimensions.into(),
color: rect.color.into(), color: rect.color.into(),
z_index: z, z_index: z,
}); });
z -= 0.0001; z -= 0.0001;
} }
let buffer = device let buffer = device.create_buffer_with_data(
.create_buffer_with_data(data.as_bytes(), wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::VERTEX); data.as_bytes(),
wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::VERTEX,
);
let mesh_id = *self.quad.as_ref().unwrap().id.read().unwrap(); let mesh_id = *self.quad.as_ref().unwrap().id.read().unwrap();
let mut instance_buffer_infos = Vec::new(); let mut instance_buffer_infos = Vec::new();
@ -70,44 +80,42 @@ impl UiPipeline {
impl Pipeline for UiPipeline { impl Pipeline for UiPipeline {
fn initialize(&mut self, render_graph: &mut RenderGraphData, world: &mut World) { fn initialize(&mut self, render_graph: &mut RenderGraphData, world: &mut World) {
let vs_bytes = shader::load_glsl( let vs_bytes = shader::load_glsl(include_str!("ui.vert"), shader::ShaderStage::Vertex);
include_str!("ui.vert"), let fs_bytes = shader::load_glsl(include_str!("ui.frag"), shader::ShaderStage::Fragment);
shader::ShaderStage::Vertex,
);
let fs_bytes = shader::load_glsl(
include_str!("ui.frag"),
shader::ShaderStage::Fragment,
);
let bind_group_layout = let bind_group_layout =
render_graph.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { render_graph
bindings: &[ .device
wgpu::BindGroupLayoutBinding { .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
binding: 0, // global_2d bindings: &[wgpu::BindGroupLayoutBinding {
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, binding: 0, // global_2d
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
}, ty: wgpu::BindingType::UniformBuffer { dynamic: false },
], }],
}); });
self.bind_group = Some({ self.bind_group = Some({
let global_2d_uniform_buffer = render_graph
let global_2d_uniform_buffer = render_graph.get_uniform_buffer(render_resources::GLOBAL_2D_UNIFORM_BUFFER_NAME).unwrap(); .get_uniform_buffer(render_resources::GLOBAL_2D_UNIFORM_BUFFER_NAME)
.unwrap();
// Create bind group // Create bind group
render_graph.device.create_bind_group(&wgpu::BindGroupDescriptor { render_graph
layout: &bind_group_layout, .device
bindings: &[ .create_bind_group(&wgpu::BindGroupDescriptor {
wgpu::Binding { layout: &bind_group_layout,
bindings: &[wgpu::Binding {
binding: 0, binding: 0,
resource: global_2d_uniform_buffer.get_binding_resource(), resource: global_2d_uniform_buffer.get_binding_resource(),
}, }],
], })
})
}); });
{ {
let mut mesh_storage = world.resources.get_mut::<AssetStorage<Mesh, MeshType>>().unwrap(); let mut mesh_storage = world
.resources
.get_mut::<AssetStorage<Mesh, MeshType>>()
.unwrap();
let quad = Mesh::load(MeshType::Quad { let quad = Mesh::load(MeshType::Quad {
north_west: math::vec2(-0.5, 0.5), north_west: math::vec2(-0.5, 0.5),
@ -118,9 +126,12 @@ impl Pipeline for UiPipeline {
self.quad = Some(mesh_storage.add(quad, "ui_quad")); self.quad = Some(mesh_storage.add(quad, "ui_quad"));
} }
let pipeline_layout = render_graph.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let pipeline_layout =
bind_group_layouts: &[&bind_group_layout], render_graph
}); .device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout],
});
let vertex_buffer_descriptor = get_vertex_buffer_descriptor(); let vertex_buffer_descriptor = get_vertex_buffer_descriptor();
let rect_data_size = mem::size_of::<RectData>(); let rect_data_size = mem::size_of::<RectData>();
@ -154,69 +165,81 @@ impl Pipeline for UiPipeline {
let vs_module = render_graph.device.create_shader_module(&vs_bytes); let vs_module = render_graph.device.create_shader_module(&vs_bytes);
let fs_module = render_graph.device.create_shader_module(&fs_bytes); let fs_module = render_graph.device.create_shader_module(&fs_bytes);
self.pipeline = Some(render_graph.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { self.pipeline = Some(render_graph.device.create_render_pipeline(
layout: &pipeline_layout, &wgpu::RenderPipelineDescriptor {
vertex_stage: wgpu::ProgrammableStageDescriptor { layout: &pipeline_layout,
module: &vs_module, vertex_stage: wgpu::ProgrammableStageDescriptor {
entry_point: "main", module: &vs_module,
}, entry_point: "main",
fragment_stage: Some(wgpu::ProgrammableStageDescriptor { },
module: &fs_module, fragment_stage: Some(wgpu::ProgrammableStageDescriptor {
entry_point: "main", module: &fs_module,
}), entry_point: "main",
rasterization_state: Some(wgpu::RasterizationStateDescriptor { }),
front_face: wgpu::FrontFace::Ccw, rasterization_state: Some(wgpu::RasterizationStateDescriptor {
cull_mode: wgpu::CullMode::None, front_face: wgpu::FrontFace::Ccw,
depth_bias: 0, cull_mode: wgpu::CullMode::None,
depth_bias_slope_scale: 0.0, depth_bias: 0,
depth_bias_clamp: 0.0, depth_bias_slope_scale: 0.0,
}), depth_bias_clamp: 0.0,
primitive_topology: wgpu::PrimitiveTopology::TriangleList, }),
color_states: &[ primitive_topology: wgpu::PrimitiveTopology::TriangleList,
wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
format: render_graph.swap_chain_descriptor.format, format: render_graph.swap_chain_descriptor.format,
color_blend: wgpu::BlendDescriptor::REPLACE, color_blend: wgpu::BlendDescriptor::REPLACE,
alpha_blend: wgpu::BlendDescriptor::REPLACE, alpha_blend: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}, }],
], depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor { format: self.depth_format,
format: self.depth_format, depth_write_enabled: true,
depth_write_enabled: true, depth_compare: wgpu::CompareFunction::Less,
depth_compare: wgpu::CompareFunction::Less, stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE, stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE, stencil_read_mask: 0,
stencil_read_mask: 0, stencil_write_mask: 0,
stencil_write_mask: 0, }),
}), index_format: wgpu::IndexFormat::Uint16,
index_format: wgpu::IndexFormat::Uint16, vertex_buffers: &[vertex_buffer_descriptor, instance_buffer_descriptor],
vertex_buffers: &[vertex_buffer_descriptor, instance_buffer_descriptor], sample_count: 1,
sample_count: 1, sample_mask: !0,
sample_mask: !0, alpha_to_coverage_enabled: false,
alpha_to_coverage_enabled: false, },
})); ));
} }
fn render(&mut self, render_graph: &RenderGraphData, pass: &mut wgpu::RenderPass, _: &SwapChainOutput, world: &mut World) { fn render(
&mut self,
render_graph: &RenderGraphData,
pass: &mut wgpu::RenderPass,
_: &SwapChainOutput,
world: &mut World,
) {
let instance_buffer_infos = Some(self.create_rect_buffers(&render_graph.device, world)); let instance_buffer_infos = Some(self.create_rect_buffers(&render_graph.device, world));
pass.set_bind_group(0, self.bind_group.as_ref().unwrap(), &[]); pass.set_bind_group(0, self.bind_group.as_ref().unwrap(), &[]);
let mut mesh_storage = world.resources.get_mut::<AssetStorage<Mesh, MeshType>>().unwrap(); let mut mesh_storage = world
.resources
.get_mut::<AssetStorage<Mesh, MeshType>>()
.unwrap();
for instance_buffer_info in instance_buffer_infos.as_ref().unwrap().iter() { for instance_buffer_info in instance_buffer_infos.as_ref().unwrap().iter() {
if let Some(mesh_asset) = mesh_storage.get(instance_buffer_info.mesh_id) { if let Some(mesh_asset) = mesh_storage.get(instance_buffer_info.mesh_id) {
mesh_asset.setup_buffers(&render_graph.device); mesh_asset.setup_buffers(&render_graph.device);
pass.set_index_buffer(mesh_asset.index_buffer.as_ref().unwrap(), 0); 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.set_vertex_buffers(0, &[(&mesh_asset.vertex_buffer.as_ref().unwrap(), 0)]);
pass.set_vertex_buffers(1, &[(&instance_buffer_info.buffer, 0)]); pass.set_vertex_buffers(1, &[(&instance_buffer_info.buffer, 0)]);
pass.draw_indexed(0 .. mesh_asset.indices.len() as u32, 0, 0 .. instance_buffer_info.instance_count as u32); pass.draw_indexed(
0..mesh_asset.indices.len() as u32,
0,
0..instance_buffer_info.instance_count as u32,
);
}; };
} }
} }
fn resize(&mut self, _: &RenderGraphData) { fn resize(&mut self, _: &RenderGraphData) {}
}
fn get_pipeline(&self) -> &wgpu::RenderPipeline { fn get_pipeline(&self) -> &wgpu::RenderPipeline {
self.pipeline.as_ref().unwrap() self.pipeline.as_ref().unwrap()
} }
} }

View file

@ -14,4 +14,4 @@ impl Rect {
color, color,
} }
} }
} }

View file

@ -7,8 +7,8 @@ pub use pipeline::Pipeline;
pub use render_resource_manager::RenderResourceManager; pub use render_resource_manager::RenderResourceManager;
use crate::render::UniformBuffer; use crate::render::UniformBuffer;
use std::collections::HashMap;
use legion::world::World; use legion::world::World;
use std::collections::HashMap;
pub struct RenderGraph { pub struct RenderGraph {
pub data: Option<RenderGraphData>, pub data: Option<RenderGraphData>,
@ -29,7 +29,12 @@ pub struct RenderGraphData {
bind_group_layouts: HashMap<String, wgpu::BindGroupLayout>, bind_group_layouts: HashMap<String, wgpu::BindGroupLayout>,
} }
impl RenderGraphData { impl RenderGraphData {
pub fn new(device: wgpu::Device, swap_chain_descriptor: wgpu::SwapChainDescriptor, queue: wgpu::Queue, surface: wgpu::Surface) -> Self { pub fn new(
device: wgpu::Device,
swap_chain_descriptor: wgpu::SwapChainDescriptor,
queue: wgpu::Queue,
surface: wgpu::Surface,
) -> Self {
RenderGraphData { RenderGraphData {
textures: HashMap::new(), textures: HashMap::new(),
samplers: HashMap::new(), samplers: HashMap::new(),
@ -43,7 +48,8 @@ impl RenderGraphData {
} }
pub fn set_uniform_buffer(&mut self, name: &str, uniform_buffer: UniformBuffer) { pub fn set_uniform_buffer(&mut self, name: &str, uniform_buffer: UniformBuffer) {
self.uniform_buffers.insert(name.to_string(), uniform_buffer); self.uniform_buffers
.insert(name.to_string(), uniform_buffer);
} }
pub fn get_uniform_buffer(&self, name: &str) -> Option<&UniformBuffer> { pub fn get_uniform_buffer(&self, name: &str) -> Option<&UniformBuffer> {
@ -51,7 +57,8 @@ impl RenderGraphData {
} }
pub fn set_bind_group_layout(&mut self, name: &str, bind_group_layout: wgpu::BindGroupLayout) { pub fn set_bind_group_layout(&mut self, name: &str, bind_group_layout: wgpu::BindGroupLayout) {
self.bind_group_layouts.insert(name.to_string(), bind_group_layout); self.bind_group_layouts
.insert(name.to_string(), bind_group_layout);
} }
pub fn get_bind_group_layout(&self, name: &str) -> Option<&wgpu::BindGroupLayout> { pub fn get_bind_group_layout(&self, name: &str) -> Option<&wgpu::BindGroupLayout> {
@ -86,7 +93,14 @@ impl RenderGraph {
} }
} }
pub fn initialize(&mut self, world: &mut World, device: wgpu::Device, swap_chain_descriptor: wgpu::SwapChainDescriptor, queue: wgpu::Queue, surface: wgpu::Surface) { pub fn initialize(
&mut self,
world: &mut World,
device: wgpu::Device,
swap_chain_descriptor: wgpu::SwapChainDescriptor,
queue: wgpu::Queue,
surface: wgpu::Surface,
) {
let mut data = RenderGraphData::new(device, swap_chain_descriptor, queue, surface); let mut data = RenderGraphData::new(device, swap_chain_descriptor, queue, surface);
for render_resource_manager in self.render_resource_managers.iter_mut() { for render_resource_manager in self.render_resource_managers.iter_mut() {
render_resource_manager.initialize(&mut data, world); render_resource_manager.initialize(&mut data, world);
@ -95,7 +109,7 @@ impl RenderGraph {
for pass in self.passes.values_mut() { for pass in self.passes.values_mut() {
pass.initialize(&mut data); pass.initialize(&mut data);
} }
for pipeline in self.pipelines.values_mut() { for pipeline in self.pipelines.values_mut() {
pipeline.initialize(&mut data, world); pipeline.initialize(&mut data, world);
} }
@ -109,8 +123,9 @@ impl RenderGraph {
.expect("Timeout when acquiring next swap chain texture"); .expect("Timeout when acquiring next swap chain texture");
let data = self.data.as_mut().unwrap(); let data = self.data.as_mut().unwrap();
let mut encoder = let mut encoder = data
data.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); .device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
for render_resource_manager in self.render_resource_managers.iter_mut() { for render_resource_manager in self.render_resource_managers.iter_mut() {
render_resource_manager.update(data, &mut encoder, world); render_resource_manager.update(data, &mut encoder, world);
@ -121,7 +136,7 @@ impl RenderGraph {
let render_pass = pass.begin(data, world, &mut encoder, &frame); let render_pass = pass.begin(data, world, &mut encoder, &frame);
if let Some(mut render_pass) = render_pass { if let Some(mut render_pass) = render_pass {
// TODO: assign pipelines to specific passes // TODO: assign pipelines to specific passes
if let Some(pipeline_names) = self.pass_pipelines.get(pass_name) { if let Some(pipeline_names) = self.pass_pipelines.get(pass_name) {
for pipeline_name in pipeline_names.iter() { for pipeline_name in pipeline_names.iter() {
let pipeline = self.pipelines.get_mut(pipeline_name).unwrap(); let pipeline = self.pipelines.get_mut(pipeline_name).unwrap();
render_pass.set_pipeline(pipeline.get_pipeline()); render_pass.set_pipeline(pipeline.get_pipeline());
@ -144,9 +159,12 @@ impl RenderGraph {
let data = self.data.as_mut().unwrap(); let data = self.data.as_mut().unwrap();
data.swap_chain_descriptor.width = width; data.swap_chain_descriptor.width = width;
data.swap_chain_descriptor.height = height; data.swap_chain_descriptor.height = height;
let swap_chain = data.device.create_swap_chain(&data.surface, &data.swap_chain_descriptor); let swap_chain = data
let mut encoder = .device
data.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); .create_swap_chain(&data.surface, &data.swap_chain_descriptor);
let mut encoder = data
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
for render_resource_manager in self.render_resource_managers.iter_mut() { for render_resource_manager in self.render_resource_managers.iter_mut() {
render_resource_manager.resize(data, &mut encoder, world); render_resource_manager.resize(data, &mut encoder, world);
@ -166,11 +184,19 @@ impl RenderGraph {
swap_chain swap_chain
} }
pub fn add_render_resource_manager(&mut self, render_resource_manager: Box<dyn RenderResourceManager>) { pub fn add_render_resource_manager(
&mut self,
render_resource_manager: Box<dyn RenderResourceManager>,
) {
self.render_resource_managers.push(render_resource_manager); self.render_resource_managers.push(render_resource_manager);
} }
pub fn set_pipeline(&mut self, pass_name: &str, pipeline_name: &str, pipeline: Box<dyn Pipeline>) { pub fn set_pipeline(
&mut self,
pass_name: &str,
pipeline_name: &str,
pipeline: Box<dyn Pipeline>,
) {
self.pipelines.insert(pipeline_name.to_string(), pipeline); self.pipelines.insert(pipeline_name.to_string(), pipeline);
if let None = self.pass_pipelines.get_mut(pass_name) { if let None = self.pass_pipelines.get_mut(pass_name) {
let pipelines = Vec::new(); let pipelines = Vec::new();
@ -185,4 +211,4 @@ impl RenderGraph {
pub fn set_pass(&mut self, name: &str, pass: Box<dyn Pass>) { pub fn set_pass(&mut self, name: &str, pass: Box<dyn Pass>) {
self.passes.insert(name.to_string(), pass); self.passes.insert(name.to_string(), pass);
} }
} }

View file

@ -3,7 +3,13 @@ use legion::world::World;
pub trait Pass { pub trait Pass {
fn initialize(&self, render_graph: &mut RenderGraphData); fn initialize(&self, render_graph: &mut RenderGraphData);
fn begin<'a>(&mut self, render_graph: &mut RenderGraphData, world: &mut World, encoder: &'a mut wgpu::CommandEncoder, frame: &'a wgpu::SwapChainOutput) -> Option<wgpu::RenderPass<'a>>; fn begin<'a>(
&mut self,
render_graph: &mut RenderGraphData,
world: &mut World,
encoder: &'a mut wgpu::CommandEncoder,
frame: &'a wgpu::SwapChainOutput,
) -> Option<wgpu::RenderPass<'a>>;
fn should_repeat(&self) -> bool; fn should_repeat(&self) -> bool;
fn resize(&self, render_graph: &mut RenderGraphData); fn resize(&self, render_graph: &mut RenderGraphData);
} }

View file

@ -1,10 +1,16 @@
use crate::render::RenderGraphData;
use legion::world::World; use legion::world::World;
use wgpu::SwapChainOutput; use wgpu::SwapChainOutput;
use crate::render::RenderGraphData;
pub trait Pipeline { pub trait Pipeline {
fn initialize(&mut self, render_graph: &mut RenderGraphData, world: &mut World); fn initialize(&mut self, render_graph: &mut RenderGraphData, world: &mut World);
fn render(&mut self, render_graph: &RenderGraphData, pass: &mut wgpu::RenderPass, frame: &SwapChainOutput, world: &mut World); fn render(
&mut self,
render_graph: &RenderGraphData,
pass: &mut wgpu::RenderPass,
frame: &SwapChainOutput,
world: &mut World,
);
fn resize(&mut self, render_graph: &RenderGraphData); fn resize(&mut self, render_graph: &RenderGraphData);
fn get_pipeline(&self) -> &wgpu::RenderPipeline; fn get_pipeline(&self) -> &wgpu::RenderPipeline;
} }

View file

@ -1,8 +1,18 @@
use legion::world::World;
use crate::render::RenderGraphData; use crate::render::RenderGraphData;
use legion::world::World;
pub trait RenderResourceManager { pub trait RenderResourceManager {
fn initialize(&self, render_graph: &mut RenderGraphData, world: &mut World); fn initialize(&self, render_graph: &mut RenderGraphData, world: &mut World);
fn update<'a>(&mut self, render_graph: &mut RenderGraphData, encoder: &'a mut wgpu::CommandEncoder, world: &mut World); fn update<'a>(
fn resize<'a>(&self, render_graph: &mut RenderGraphData, encoder: &'a mut wgpu::CommandEncoder, world: &mut World); &mut self,
} render_graph: &mut RenderGraphData,
encoder: &'a mut wgpu::CommandEncoder,
world: &mut World,
);
fn resize<'a>(
&self,
render_graph: &mut RenderGraphData,
encoder: &'a mut wgpu::CommandEncoder,
world: &mut World,
);
}

View file

@ -1,4 +1,4 @@
use crate::{render::*, math}; use crate::{math, render::*};
use legion::prelude::*; use legion::prelude::*;
use std::mem; use std::mem;
@ -33,19 +33,40 @@ impl RenderResourceManager for Global2dResourceManager {
render_graph.set_uniform_buffer(GLOBAL_2D_UNIFORM_BUFFER_NAME, uniform_buffer); render_graph.set_uniform_buffer(GLOBAL_2D_UNIFORM_BUFFER_NAME, uniform_buffer);
} }
fn update<'a>(&mut self, _render_graph: &mut RenderGraphData, _encoder: &'a mut wgpu::CommandEncoder, _world: &mut World) { fn update<'a>(
&mut self,
_render_graph: &mut RenderGraphData,
_encoder: &'a mut wgpu::CommandEncoder,
_world: &mut World,
) {
} }
fn resize<'a>(&self, render_graph: &mut RenderGraphData, encoder: &'a mut wgpu::CommandEncoder, world: &mut World) { fn resize<'a>(
&self,
render_graph: &mut RenderGraphData,
encoder: &'a mut wgpu::CommandEncoder,
world: &mut World,
) {
for (mut camera, _) in <(Write<Camera>, Read<ActiveCamera2d>)>::query().iter(world) { for (mut camera, _) in <(Write<Camera>, Read<ActiveCamera2d>)>::query().iter(world) {
camera.update(render_graph.swap_chain_descriptor.width, render_graph.swap_chain_descriptor.height); camera.update(
render_graph.swap_chain_descriptor.width,
render_graph.swap_chain_descriptor.height,
);
let camera_matrix: [[f32; 4]; 4] = camera.view_matrix.to_cols_array_2d(); let camera_matrix: [[f32; 4]; 4] = camera.view_matrix.to_cols_array_2d();
let matrix_size = mem::size_of::<[[f32; 4]; 4]>() as u64; let matrix_size = mem::size_of::<[[f32; 4]; 4]>() as u64;
let temp_camera_buffer = let temp_camera_buffer = render_graph
render_graph.device.create_buffer_with_data(camera_matrix.as_bytes(), wgpu::BufferUsage::COPY_SRC); .device
let global_2d_uniform_buffer = render_graph.get_uniform_buffer(GLOBAL_2D_UNIFORM_BUFFER_NAME).unwrap(); .create_buffer_with_data(camera_matrix.as_bytes(), wgpu::BufferUsage::COPY_SRC);
encoder.copy_buffer_to_buffer(&temp_camera_buffer, 0, &global_2d_uniform_buffer.buffer, 0, matrix_size); let global_2d_uniform_buffer = render_graph
.get_uniform_buffer(GLOBAL_2D_UNIFORM_BUFFER_NAME)
.unwrap();
encoder.copy_buffer_to_buffer(
&temp_camera_buffer,
0,
&global_2d_uniform_buffer.buffer,
0,
matrix_size,
);
} }
} }
} }

View file

@ -1,4 +1,4 @@
use crate::{render::*, render::passes::ForwardUniforms, LocalToWorld, math}; use crate::{math, render::passes::ForwardUniforms, render::*, LocalToWorld};
use legion::prelude::*; use legion::prelude::*;
use std::mem; use std::mem;
@ -28,18 +28,42 @@ impl RenderResourceManager for GlobalResourceManager {
}; };
render_graph.set_uniform_buffer(FORWARD_UNIFORM_BUFFER_NAME, uniform_buffer); render_graph.set_uniform_buffer(FORWARD_UNIFORM_BUFFER_NAME, uniform_buffer);
} }
fn update<'a>(&mut self, _render_graph: &mut RenderGraphData, _encoder: &'a mut wgpu::CommandEncoder, _world: &mut World) { fn update<'a>(
&mut self,
_render_graph: &mut RenderGraphData,
_encoder: &'a mut wgpu::CommandEncoder,
_world: &mut World,
) {
} }
fn resize<'a>(&self, render_graph: &mut RenderGraphData, encoder: &'a mut wgpu::CommandEncoder, world: &mut World) { fn resize<'a>(
for (mut camera, local_to_world, _) in <(Write<Camera>, Read<LocalToWorld>, Read<ActiveCamera>)>::query().iter(world) { &self,
camera.update(render_graph.swap_chain_descriptor.width, render_graph.swap_chain_descriptor.height); render_graph: &mut RenderGraphData,
let camera_matrix: [[f32; 4]; 4] = (camera.view_matrix * local_to_world.0).to_cols_array_2d(); encoder: &'a mut wgpu::CommandEncoder,
world: &mut World,
) {
for (mut camera, local_to_world, _) in
<(Write<Camera>, Read<LocalToWorld>, Read<ActiveCamera>)>::query().iter(world)
{
camera.update(
render_graph.swap_chain_descriptor.width,
render_graph.swap_chain_descriptor.height,
);
let camera_matrix: [[f32; 4]; 4] =
(camera.view_matrix * local_to_world.0).to_cols_array_2d();
let matrix_size = mem::size_of::<[[f32; 4]; 4]>() as u64; let matrix_size = mem::size_of::<[[f32; 4]; 4]>() as u64;
let temp_camera_buffer = let temp_camera_buffer = render_graph
render_graph.device.create_buffer_with_data(camera_matrix.as_bytes(), wgpu::BufferUsage::COPY_SRC); .device
let forward_uniform_buffer = render_graph.get_uniform_buffer(FORWARD_UNIFORM_BUFFER_NAME).unwrap(); .create_buffer_with_data(camera_matrix.as_bytes(), wgpu::BufferUsage::COPY_SRC);
encoder.copy_buffer_to_buffer(&temp_camera_buffer, 0, &forward_uniform_buffer.buffer, 0, matrix_size); let forward_uniform_buffer = render_graph
.get_uniform_buffer(FORWARD_UNIFORM_BUFFER_NAME)
.unwrap();
encoder.copy_buffer_to_buffer(
&temp_camera_buffer,
0,
&forward_uniform_buffer.buffer,
0,
matrix_size,
);
} }
} }
} }

View file

@ -23,7 +23,7 @@ impl LightResourceManager {
impl RenderResourceManager for LightResourceManager { impl RenderResourceManager for LightResourceManager {
fn initialize(&self, render_graph: &mut RenderGraphData, _world: &mut World) { fn initialize(&self, render_graph: &mut RenderGraphData, _world: &mut World) {
let light_uniform_size = let light_uniform_size =
(self.max_lights * mem::size_of::<LightRaw>()) as wgpu::BufferAddress; (self.max_lights * mem::size_of::<LightRaw>()) as wgpu::BufferAddress;
let light_uniform_buffer = UniformBuffer { let light_uniform_buffer = UniformBuffer {
buffer: render_graph.device.create_buffer(&wgpu::BufferDescriptor { buffer: render_graph.device.create_buffer(&wgpu::BufferDescriptor {
@ -37,7 +37,12 @@ impl RenderResourceManager for LightResourceManager {
render_graph.set_uniform_buffer(LIGHT_UNIFORM_BUFFER_NAME, light_uniform_buffer); render_graph.set_uniform_buffer(LIGHT_UNIFORM_BUFFER_NAME, light_uniform_buffer);
} }
fn update<'a>(&mut self, render_graph: &mut RenderGraphData, encoder: &'a mut wgpu::CommandEncoder, world: &mut World) { fn update<'a>(
&mut self,
render_graph: &mut RenderGraphData,
encoder: &'a mut wgpu::CommandEncoder,
world: &mut World,
) {
if self.lights_are_dirty { if self.lights_are_dirty {
let mut light_query = <(Read<Light>, Read<LocalToWorld>, Read<Translation>)>::query(); let mut light_query = <(Read<Light>, Read<LocalToWorld>, Read<Translation>)>::query();
let light_count = light_query.iter(world).count(); let light_count = light_query.iter(world).count();
@ -49,16 +54,21 @@ impl RenderResourceManager for LightResourceManager {
self.lights_are_dirty = false; self.lights_are_dirty = false;
let size = mem::size_of::<LightRaw>(); let size = mem::size_of::<LightRaw>();
let total_size = size * light_count; let total_size = size * light_count;
let temp_buf_data = let temp_buf_data = render_graph
render_graph.device.create_buffer_mapped(total_size, wgpu::BufferUsage::COPY_SRC); .device
.create_buffer_mapped(total_size, wgpu::BufferUsage::COPY_SRC);
for ((light, local_to_world, translation), slot) in light_query for ((light, local_to_world, translation), slot) in light_query
.iter(world) .iter(world)
.zip(temp_buf_data.data.chunks_exact_mut(size)) .zip(temp_buf_data.data.chunks_exact_mut(size))
{ {
slot.copy_from_slice(LightRaw::from(&light, &local_to_world.0, &translation).as_bytes()); slot.copy_from_slice(
LightRaw::from(&light, &local_to_world.0, &translation).as_bytes(),
);
} }
let light_uniform_buffer = render_graph.get_uniform_buffer(LIGHT_UNIFORM_BUFFER_NAME).unwrap(); let light_uniform_buffer = render_graph
.get_uniform_buffer(LIGHT_UNIFORM_BUFFER_NAME)
.unwrap();
encoder.copy_buffer_to_buffer( encoder.copy_buffer_to_buffer(
&temp_buf_data.finish(), &temp_buf_data.finish(),
0, 0,
@ -66,8 +76,13 @@ impl RenderResourceManager for LightResourceManager {
0, 0,
total_size as wgpu::BufferAddress, total_size as wgpu::BufferAddress,
); );
} }
} }
fn resize<'a>(&self, _render_graph: &mut RenderGraphData, _encoder: &'a mut wgpu::CommandEncoder, _world: &mut World) { } fn resize<'a>(
} &self,
_render_graph: &mut RenderGraphData,
_encoder: &'a mut wgpu::CommandEncoder,
_world: &mut World,
) {
}
}

View file

@ -11,30 +11,40 @@ pub struct MaterialResourceManager;
impl RenderResourceManager for MaterialResourceManager { impl RenderResourceManager for MaterialResourceManager {
fn initialize(&self, render_graph: &mut RenderGraphData, _world: &mut World) { fn initialize(&self, render_graph: &mut RenderGraphData, _world: &mut World) {
let material_bind_group_layout = let material_bind_group_layout =
render_graph.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { render_graph
bindings: &[wgpu::BindGroupLayoutBinding { .device
binding: 0, .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, bindings: &[wgpu::BindGroupLayoutBinding {
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, binding: 0,
}], visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
}); ty: wgpu::BindingType::UniformBuffer { dynamic: false },
}],
});
render_graph.set_bind_group_layout(MATERIAL_BIND_GROUP_LAYOUT_NAME, material_bind_group_layout); render_graph
.set_bind_group_layout(MATERIAL_BIND_GROUP_LAYOUT_NAME, material_bind_group_layout);
} }
fn update<'a>(&mut self, render_graph: &mut RenderGraphData, encoder: &'a mut wgpu::CommandEncoder, world: &mut World) { fn update<'a>(
let mut entities = <(Write<Material>, Read<LocalToWorld>)>::query() &mut self,
.filter(!component::<Instanced>()); render_graph: &mut RenderGraphData,
encoder: &'a mut wgpu::CommandEncoder,
world: &mut World,
) {
let mut entities =
<(Write<Material>, Read<LocalToWorld>)>::query().filter(!component::<Instanced>());
let entities_count = entities.iter(world).count(); let entities_count = entities.iter(world).count();
if entities_count == 0 { if entities_count == 0 {
return; return;
} }
let size = mem::size_of::<MaterialUniforms>(); let size = mem::size_of::<MaterialUniforms>();
let temp_buf_data = render_graph.device let temp_buf_data = render_graph
.device
.create_buffer_mapped(entities_count * size, wgpu::BufferUsage::COPY_SRC); .create_buffer_mapped(entities_count * size, wgpu::BufferUsage::COPY_SRC);
for ((material, transform), slot) in entities.iter(world) for ((material, transform), slot) in entities
.iter(world)
.zip(temp_buf_data.data.chunks_exact_mut(size)) .zip(temp_buf_data.data.chunks_exact_mut(size))
{ {
slot.copy_from_slice( slot.copy_from_slice(
@ -45,27 +55,36 @@ impl RenderResourceManager for MaterialResourceManager {
.as_bytes(), .as_bytes(),
); );
} }
let material_bind_group_layout = render_graph.get_bind_group_layout(MATERIAL_BIND_GROUP_LAYOUT_NAME).unwrap();
for mut material in <Write<Material>>::query().filter(!component::<Instanced>()).iter(world) { let material_bind_group_layout = render_graph
.get_bind_group_layout(MATERIAL_BIND_GROUP_LAYOUT_NAME)
.unwrap();
for mut material in <Write<Material>>::query()
.filter(!component::<Instanced>())
.iter(world)
{
if let None = material.bind_group { if let None = material.bind_group {
let material_uniform_size = mem::size_of::<MaterialUniforms>() as wgpu::BufferAddress; let material_uniform_size =
mem::size_of::<MaterialUniforms>() as wgpu::BufferAddress;
let uniform_buf = render_graph.device.create_buffer(&wgpu::BufferDescriptor { let uniform_buf = render_graph.device.create_buffer(&wgpu::BufferDescriptor {
size: material_uniform_size, size: material_uniform_size,
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
}); });
let bind_group = render_graph.device.create_bind_group(&wgpu::BindGroupDescriptor { let bind_group =
layout: material_bind_group_layout, render_graph
bindings: &[wgpu::Binding { .device
binding: 0, .create_bind_group(&wgpu::BindGroupDescriptor {
resource: wgpu::BindingResource::Buffer { layout: material_bind_group_layout,
buffer: &uniform_buf, bindings: &[wgpu::Binding {
range: 0 .. material_uniform_size, binding: 0,
}, resource: wgpu::BindingResource::Buffer {
}], buffer: &uniform_buf,
}); range: 0..material_uniform_size,
},
}],
});
material.bind_group = Some(bind_group); material.bind_group = Some(bind_group);
material.uniform_buf = Some(uniform_buf); material.uniform_buf = Some(uniform_buf);
@ -83,7 +102,11 @@ impl RenderResourceManager for MaterialResourceManager {
); );
} }
} }
fn resize<'a>(&self, _render_graph: &mut RenderGraphData, _encoder: &'a mut wgpu::CommandEncoder, _world: &mut World) { fn resize<'a>(
&self,
_render_graph: &mut RenderGraphData,
_encoder: &'a mut wgpu::CommandEncoder,
_world: &mut World,
) {
} }
} }

View file

@ -1,9 +1,9 @@
mod light_resource_manager;
mod global_resource_manager;
mod global_2d_resource_manager; mod global_2d_resource_manager;
mod global_resource_manager;
mod light_resource_manager;
mod material_resource_manager; mod material_resource_manager;
pub use light_resource_manager::*;
pub use global_resource_manager::*;
pub use global_2d_resource_manager::*; pub use global_2d_resource_manager::*;
pub use material_resource_manager::*; pub use global_resource_manager::*;
pub use light_resource_manager::*;
pub use material_resource_manager::*;

View file

@ -13,4 +13,4 @@ pub fn load_glsl(code: &str, stage: ShaderStage) -> Vec<u32> {
}; };
wgpu::read_spirv(glsl_to_spirv::compile(&code, ty).unwrap()).unwrap() wgpu::read_spirv(glsl_to_spirv::compile(&code, ty).unwrap()).unwrap()
} }

View file

@ -1,5 +1,5 @@
use zerocopy::{AsBytes, FromBytes};
use std::convert::From; use std::convert::From;
use zerocopy::{AsBytes, FromBytes};
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, AsBytes, FromBytes)] #[derive(Clone, Copy, AsBytes, FromBytes)]
@ -9,7 +9,7 @@ pub struct Vertex {
} }
impl From<([f32; 4], [f32; 4])> for Vertex { impl From<([f32; 4], [f32; 4])> for Vertex {
fn from((position, normal): ([f32; 4], [f32; 4])) -> Self { fn from((position, normal): ([f32; 4], [f32; 4])) -> Self {
Vertex { Vertex {
position: position, position: position,
normal: normal, normal: normal,
@ -18,28 +18,48 @@ impl From<([f32; 4], [f32; 4])> for Vertex {
} }
impl From<([f32; 3], [f32; 3])> for Vertex { impl From<([f32; 3], [f32; 3])> for Vertex {
fn from((position, normal): ([f32; 3], [f32; 3])) -> Self { fn from((position, normal): ([f32; 3], [f32; 3])) -> Self {
Vertex { Vertex {
position: [position[0] as f32, position[1] as f32, position[2] as f32, 1.0], position: [
position[0] as f32,
position[1] as f32,
position[2] as f32,
1.0,
],
normal: [normal[0] as f32, normal[1] as f32, normal[2] as f32, 0.0], normal: [normal[0] as f32, normal[1] as f32, normal[2] as f32, 0.0],
} }
} }
} }
impl From<([i8; 4], [i8; 4])> for Vertex { impl From<([i8; 4], [i8; 4])> for Vertex {
fn from((position, normal): ([i8; 4], [i8; 4])) -> Self { fn from((position, normal): ([i8; 4], [i8; 4])) -> Self {
Vertex { Vertex {
position: [position[0] as f32, position[1] as f32, position[2] as f32, position[3] as f32], position: [
normal: [normal[0] as f32, normal[1] as f32, normal[2] as f32, normal[3] as f32], position[0] as f32,
position[1] as f32,
position[2] as f32,
position[3] as f32,
],
normal: [
normal[0] as f32,
normal[1] as f32,
normal[2] as f32,
normal[3] as f32,
],
} }
} }
} }
impl From<([i8; 3], [i8; 3])> for Vertex { impl From<([i8; 3], [i8; 3])> for Vertex {
fn from((position, normal): ([i8; 3], [i8; 3])) -> Self { fn from((position, normal): ([i8; 3], [i8; 3])) -> Self {
Vertex { Vertex {
position: [position[0] as f32, position[1] as f32, position[2] as f32, 1.0], position: [
position[0] as f32,
position[1] as f32,
position[2] as f32,
1.0,
],
normal: [normal[0] as f32, normal[1] as f32, normal[2] as f32, 0.0], normal: [normal[0] as f32, normal[1] as f32, normal[2] as f32, 0.0],
} }
} }
} }