ECS'ing it up, lost rendering though, bummer

This commit is contained in:
2021-02-02 00:46:47 -08:00
parent a38c8e3f36
commit df13db5270
4 changed files with 387 additions and 225 deletions

View File

@@ -1,14 +1,19 @@
use bytemuck::{Pod, Zeroable};
use bytemuck::__core::mem;
use wgpu::util::DeviceExt;
use std::sync::Arc;
use std::{iter, num::NonZeroU32, ops::Range, rc::Rc};
use crate::{OPENGL_TO_WGPU_MATRIX, Velocity};
use crate::light::LightRaw;
use crate::geometry::{Vertex, import_mesh, create_plane};
use wgpu::{Buffer, Device};
use winit::dpi::Position;
use winit::platform::unix::x11::ffi::Time;
use bytemuck::__core::mem;
use bytemuck::{Pod, Zeroable};
use legion::*;
use wgpu::util::DeviceExt;
use wgpu::{Buffer, Device, SwapChain, Queue, SwapChainFrame, Surface, SwapChainDescriptor, Instance};
use winit::dpi::{Position, PhysicalSize};
use winit::platform::unix::x11::ffi::Time;
use winit::window::Window;
use crate::geometry::{create_plane, import_mesh, Vertex};
use crate::light::LightRaw;
use crate::{Velocity, OPENGL_TO_WGPU_MATRIX};
use futures::executor::LocalPool;
#[repr(C)]
#[derive(Clone, Copy)]
@@ -44,7 +49,16 @@ pub struct Pass {
}
pub struct Renderer {
device: Rc<Device>,
window: Window,
swapchain: SwapChain,
swapchain_description: Arc<SwapChainDescriptor>,
instance: Arc<Instance>,
device: Arc<Device>,
queue: Arc<Queue>,
size: PhysicalSize<u32>,
surface: Arc<Surface>,
lights_are_dirty: bool,
shadow_pass: Pass,
forward_pass: Pass,
@@ -79,38 +93,178 @@ impl Renderer {
}
#[system(for_each)]
pub fn render_test(pos: &mut Position, vel: &Velocity) {
pub fn render_test(pos: &mut Position, vel: &Velocity, #[resource] renderer: &mut Renderer) {
let frame = renderer.get_current_frame();
//pos.x += vel.dx * time.elapsed_seconds;
//pos.y += vel.dy * time.elapsed_seconds;
// frame: &wgpu::SwapChainTexture,
// device: &wgpu::Device,
// queue: &wgpu::Queue,
// _spawner: &impl futures::task::LocalSpawn,
// )
// {
// update uniforms
// for entity in self.entities.iter_mut() {
//
// // Revolve the entity by the rotation speed, only if it is non-zero
// if entity.rotation_speed != 0.0 {
// let rotation = cgmath::Matrix4::from_angle_x(cgmath::Deg(entity.rotation_speed));
// entity.mx_world = entity.mx_world * rotation;
// }
//
// let data = EntityUniforms {
// model: entity.mx_world.into(),
// color: [
// entity.color.r as f32,
// entity.color.g as f32,
// entity.color.b as f32,
// entity.color.a as f32,
// ],
// };
// queue.write_buffer(&entity.uniform_buf, 0, bytemuck::bytes_of(&data));
// }
// if self.lights_are_dirty {
// self.lights_are_dirty = false;
// for (i, light) in self.lights.iter().enumerate() {
// queue.write_buffer(
// &self.light_uniform_buf,
// (i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress,
// bytemuck::bytes_of(&light.to_raw()),
// );
// }
// }
let mut encoder = renderer
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
encoder.push_debug_group("shadow passes");
/*for (i, light) in self.lights.iter().enumerate() {
encoder.push_debug_group(&format!(
"shadow pass {} (light at position {:?})",
i, light.pos
));
// The light uniform buffer already has the projection,
// let's just copy it over to the shadow uniform buffer.
encoder.copy_buffer_to_buffer(
&self.light_uniform_buf,
(i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress,
&self.shadow_pass.uniform_buf,
0,
64,
);
encoder.insert_debug_marker("render entities");
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[],
depth_stencil_attachment: Some(
wgpu::RenderPassDepthStencilAttachmentDescriptor {
attachment: &light.target_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: true,
}),
stencil_ops: None,
},
),
});
pass.set_pipeline(&self.shadow_pass.pipeline);
pass.set_bind_group(0, &self.shadow_pass.bind_group, &[]);
for entity in &self.entities {
pass.set_bind_group(1, &entity.bind_group, &[]);
pass.set_index_buffer(entity.index_buf.slice(..));
pass.set_vertex_buffer(0, entity.vertex_buf.slice(..));
pass.draw_indexed(0..entity.index_count as u32, 0, 0..1);
}
}
encoder.pop_debug_group();
}*/
encoder.pop_debug_group();
// forward pass
encoder.push_debug_group("forward rendering pass");
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
attachment: &frame.output.view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }),
store: true,
},
}],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
attachment: &renderer.forward_depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: false,
}),
stencil_ops: None,
}),
});
pass.set_pipeline(&renderer.forward_pass.pipeline);
pass.set_bind_group(0, &renderer.forward_pass.bind_group, &[]);
// for entity in &self.entities {
// pass.set_bind_group(1, &entity.bind_group, &[]);
// pass.set_index_buffer(entity.index_buf.slice(..));
// pass.set_vertex_buffer(0, entity.vertex_buf.slice(..));
// pass.draw_indexed(0..entity.index_count as u32, 0, 0..1);
// }
}
encoder.pop_debug_group();
renderer.queue.submit(iter::once(encoder.finish()));
renderer.window.request_redraw();
}
impl Renderer {
pub fn get_current_frame(&mut self) -> SwapChainFrame {
// Update the renderers swapchain state
match self.swapchain.get_current_frame() {
Ok(frame) => frame,
Err(_) => {
self.swapchain = self.device.create_swap_chain(&self.surface, &self.swapchain_description);
self.swapchain
.get_current_frame()
.expect("Failed to acquire next swap chain texture!")
}
}
}
pub fn create_buffer(device: &wgpu::Device,
indices: Vec<u32>,
vertices: Vec<Vertex>) -> (Rc<Buffer>, Rc<Buffer>) {
pub fn create_buffer(
device: &wgpu::Device,
indices: Vec<u32>,
vertices: Vec<Vertex>,
) -> (Arc<Buffer>, Arc<Buffer>) {
// Creates the vertex and index buffers for the cube
let vertex_size = mem::size_of::<Vertex>();
//import_mesh("/home/mrh/source/3d-min-viable-eng/resources/my_tree.obj");
let vertex_buf = Rc::new(device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
let vertex_buf = Arc::new(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("vertex-buffer"),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsage::VERTEX,
},
));
}),
);
let index_buf = Rc::new(device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
let index_buf = Arc::new(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("index-buffer"),
contents: bytemuck::cast_slice(&indices),
usage: wgpu::BufferUsage::INDEX,
},
));
}),
);
// // Creates the vertex and index buffers for the plane
// let (plane_vertex_data, plane_index_data) = create_plane(7.0);
@@ -131,15 +285,109 @@ impl Renderer {
(vertex_buf, index_buf)
}
pub fn load_mesh_to_buffer(device: Rc<wgpu::Device>, filepath: &str) -> (Rc<Buffer>, Rc<Buffer>) {
pub fn load_mesh_to_buffer(&self, filepath: &str) -> (Arc<Buffer>, Arc<Buffer>) {
let (vertices, indices) = import_mesh(filepath);
Renderer::create_buffer(&device, indices, vertices)
Renderer::create_buffer(&self.device, indices, vertices)
}
pub fn init(window: Window) -> Renderer {
log::info!("Initializing the surface...");
pub fn init(device: Rc<wgpu::Device>, sc_desc: &wgpu::SwapChainDescriptor) -> Renderer {
// Grab the GPU instance, and query its features
let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
let (size, surface) = unsafe {
let size = window.inner_size();
let surface = instance.create_surface(&window);
(size, surface)
};
let surface = Arc::new(surface);
let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
});
let adapter = futures::executor::block_on(adapter).unwrap();
let optional_features = Renderer::optional_features();
let required_features = Renderer::required_features();
let adapter_features = adapter.features();
// assert!(
// adapter_features.contains(required_features),
// "Adapter does not support required features for this example: {:?}",
// required_features - adapter_features
// );
let needed_limits = wgpu::Limits::default(); //Renderer::required_limits();
// Maybe for debug tracing???
let trace_dir = std::env::var("WGPU_TRACE");
// And then get the device we want
let device = adapter.request_device(
&wgpu::DeviceDescriptor {
features: (optional_features & adapter_features) | required_features,
limits: needed_limits,
shader_validation: true,
},
trace_dir.ok().as_ref().map(std::path::Path::new),
);
let (device, queue) = futures::executor::block_on(device).unwrap();
let queue = Arc::new(queue);
let device = Arc::new(device);
// This is some gross-ass web shit
/*#[cfg(target_arch = "wasm32")]
let spawner = {
use futures::{future::LocalFutureObj, task::SpawnError};
use winit::platform::web::WindowExtWebSys;
struct WebSpawner {}
impl LocalSpawn for WebSpawner {
fn spawn_local_obj(
&self,
future: LocalFutureObj<'static, ()>,
) -> Result<(), SpawnError> {
Ok(wasm_bindgen_futures::spawn_local(future))
}
}
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
// On wasm, append the canvas to the document body
web_sys::window()
.and_then(|win| win.document())
.and_then(|doc| doc.body())
.and_then(|body| {
body.append_child(&web_sys::Element::from(window.canvas()))
.ok()
})
.expect("couldn't append canvas to document body");
WebSpawner {}
};*/
log::info!("Done doing the loading part...");
let mut sc_desc = Arc::new(wgpu::SwapChainDescriptor {
// Allows a texture to be a output attachment of a renderpass.
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
format: if cfg!(target_arch = "wasm32") {
wgpu::TextureFormat::Bgra8Unorm
} else {
wgpu::TextureFormat::Bgra8UnormSrgb
},
width: size.width,
height: size.height,
// The presentation engine waits for the next vertical blanking period to update
present_mode: wgpu::PresentMode::Mailbox,
});
let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
let entity_uniform_size = mem::size_of::<EntityUniforms>() as wgpu::BufferAddress;
let plane_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
@@ -239,8 +487,10 @@ impl Renderer {
});
// Create the render pipeline
let vs_module = device.create_shader_module(wgpu::include_spirv!("../resources/bake.vert.spv"));
let fs_module = device.create_shader_module(wgpu::include_spirv!("../resources/bake.frag.spv"));
let vs_module =
device.create_shader_module(wgpu::include_spirv!("../resources/bake.vert.spv"));
let fs_module =
device.create_shader_module(wgpu::include_spirv!("../resources/bake.frag.spv"));
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("shadow"),
@@ -297,7 +547,8 @@ impl Renderer {
dynamic: false,
min_binding_size: wgpu::BufferSize::new(mem::size_of::<
ForwardUniforms,
>()
>(
)
as _),
},
count: None,
@@ -346,7 +597,6 @@ impl Renderer {
num_lights: [1 as u32, 0, 0, 0],
};
let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Uniform Buffer"),
contents: bytemuck::bytes_of(&forward_uniforms),
@@ -380,7 +630,6 @@ impl Renderer {
// shadow_target_views[0].take().unwrap(),
// pub(crate) target_view: wgpu::TextureView,
let shadow_view = shadow_texture.create_view(&wgpu::TextureViewDescriptor::default());
let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
@@ -395,7 +644,6 @@ impl Renderer {
..Default::default()
});
// Create bind group
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
@@ -421,8 +669,10 @@ impl Renderer {
});
// Create the render pipeline
let vs_module = device.create_shader_module(wgpu::include_spirv!("../resources/forward.vert.spv"));
let fs_module = device.create_shader_module(wgpu::include_spirv!("../resources/forward.frag.spv"));
let vs_module =
device.create_shader_module(wgpu::include_spirv!("../resources/forward.vert.spv"));
let fs_module =
device.create_shader_module(wgpu::include_spirv!("../resources/forward.frag.spv"));
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("main"),
@@ -479,18 +729,25 @@ impl Renderer {
});
Renderer {
window,
swapchain: swap_chain,
queue: queue,
size,
device: device,
lights_are_dirty: false,
shadow_pass,
forward_pass,
forward_depth: depth_texture.create_view(&wgpu::TextureViewDescriptor::default()),
light_uniform_buf,
// plane_uniform_buf,
// plane_vertex_buf: (),
// plane_index_buf: ()
// plane_uniform_buf,
// plane_vertex_buf: (),
// plane_index_buf: ()
swapchain_description: sc_desc,
surface,
instance: Arc::new(instance)
}
}
//
pub fn render(
@@ -499,8 +756,7 @@ impl Renderer {
device: &wgpu::Device,
queue: &wgpu::Queue,
_spawner: &impl futures::task::LocalSpawn,
)
{
) {
// update uniforms
// for entity in self.entities.iter_mut() {
//
@@ -622,6 +878,7 @@ impl Renderer {
encoder.pop_debug_group();
queue.submit(iter::once(encoder.finish()));
}
pub(crate) fn required_features() -> wgpu::Features {
@@ -632,26 +889,20 @@ impl Renderer {
wgpu::Features::DEPTH_CLAMPING
}
pub fn resize(
&mut self,
sc_desc: &wgpu::SwapChainDescriptor,
device: &wgpu::Device,
queue: &wgpu::Queue,
)
{
pub fn resize(&mut self, width: u32, height: u32) {
// update view-projection matrix
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let mx_total = Self::generate_matrix(width as f32 / height as f32);
let mx_ref: &[f32; 16] = mx_total.as_ref();
queue.write_buffer(
self.queue.write_buffer(
&self.forward_pass.uniform_buf,
0,
bytemuck::cast_slice(mx_ref),
);
let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
let depth_texture = self.device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width: sc_desc.width,
height: sc_desc.height,
width: width,
height: height,
depth: 1,
},
mip_level_count: 1,
@@ -664,4 +915,3 @@ impl Renderer {
self.forward_depth = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());
}
}