wgpu-renderer/src/core/state.rs

525 lines
19 KiB
Rust
Raw Normal View History

2022-10-02 18:59:20 +03:00
use cgmath::prelude::*;
use std::time::Duration;
2022-10-03 22:31:01 +03:00
use wgpu::util::DeviceExt;
2022-10-01 23:58:09 +03:00
use winit::{event::*, window::Window};
2022-10-02 18:59:20 +03:00
use super::camera::{Camera, CameraController, CameraUniform};
use super::instance::{Instance, InstanceRaw};
2022-10-03 22:31:01 +03:00
use super::light::{DrawLight, LightUniform};
2022-10-02 22:03:50 +03:00
use super::model::{DrawModel, Model, ModelVertex, Vertex};
2023-01-29 14:54:23 +02:00
use super::pass::RenderPass;
2022-10-02 22:03:50 +03:00
use super::resources;
2022-10-02 18:59:20 +03:00
use super::texture::Texture;
2022-10-02 22:03:50 +03:00
2022-10-01 23:58:09 +03:00
pub struct State {
pub size: winit::dpi::PhysicalSize<u32>,
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
2023-01-29 14:54:23 +02:00
geometry_pass: RenderPass,
2022-10-02 18:59:20 +03:00
camera: Camera,
camera_uniform: CameraUniform,
camera_buffer: wgpu::Buffer,
camera_bind_group: wgpu::BindGroup,
camera_controller: CameraController,
instances: Vec<Instance>,
instance_buffer: wgpu::Buffer,
2022-10-02 22:03:50 +03:00
depth_texture: Texture,
model: Model,
light_model: Model,
2022-10-03 22:31:01 +03:00
light_uniform: LightUniform,
light_buffer: wgpu::Buffer,
2023-01-29 14:54:23 +02:00
light_debug_pass: RenderPass,
2022-10-03 22:31:01 +03:00
light_bind_group: wgpu::BindGroup,
2023-01-29 18:57:29 +02:00
light_depth_pass: RenderPass,
light_depth_texture: Texture,
2022-10-01 23:58:09 +03:00
}
impl State {
// Creating some of the wgpu types requires async code
pub async fn new(window: &Window) -> Self {
let size = window.inner_size();
let instance = wgpu::Instance::new(wgpu::Backends::all());
let surface = unsafe { instance.create_surface(window) };
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.await
.unwrap();
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
features: wgpu::Features::empty(),
2023-01-28 12:23:43 +02:00
limits: if cfg!(target_arch = "wasm32") {
wgpu::Limits::downlevel_webgl2_defaults()
} else {
wgpu::Limits::default()
},
2022-10-01 23:58:09 +03:00
label: None,
},
None, // Trace path
)
.await
.unwrap();
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface.get_supported_formats(&adapter)[0],
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
2023-01-23 17:15:02 +02:00
alpha_mode: wgpu::CompositeAlphaMode::Opaque,
2022-10-01 23:58:09 +03:00
};
surface.configure(&device, &config);
2022-10-02 18:59:20 +03:00
// Camera
let camera = Camera::new(
2023-01-28 13:23:41 +02:00
(-500.0, 150.0, 0.0).into(),
2022-10-02 18:59:20 +03:00
0.0,
0.0,
2023-01-24 17:00:51 +02:00
55.0,
2022-10-02 18:59:20 +03:00
config.width as f32 / config.height as f32,
2022-10-01 23:58:09 +03:00
);
2022-10-02 18:59:20 +03:00
let mut camera_uniform = CameraUniform::new();
2022-10-03 22:31:01 +03:00
camera_uniform.update(&camera);
2022-10-02 18:59:20 +03:00
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Camera Buffer"),
contents: bytemuck::cast_slice(&[camera_uniform]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let camera_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
2022-10-03 22:31:01 +03:00
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
2022-10-02 18:59:20 +03:00
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: Some("camera_bind_group_layout"),
});
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &camera_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: camera_buffer.as_entire_binding(),
}],
label: Some("camera_bind_group"),
2022-10-01 23:58:09 +03:00
});
2022-10-02 18:59:20 +03:00
2023-01-28 13:23:41 +02:00
let camera_controller = CameraController::new(400.0, 2.0);
2022-10-02 18:59:20 +03:00
2023-01-29 18:57:29 +02:00
let depth_texture = Texture::create_depth_texture(
&device,
&config,
"depth_texture",
Some(wgpu::CompareFunction::LessEqual),
);
let light_depth_texture = Texture::create_depth_texture(
&device,
&config,
"light_depth_texture",
Some(wgpu::CompareFunction::LessEqual),
);
2023-01-28 14:03:14 +02:00
let light_uniform = LightUniform::new([100.0, 60.0, 0.0], [1.0, 1.0, 1.0, 200000.0]);
2022-10-03 22:31:01 +03:00
// We'll want to update our lights position, so we use COPY_DST
let light_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Light VB"),
contents: bytemuck::cast_slice(&[light_uniform]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let light_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2023-01-29 18:57:29 +02:00
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
2022-10-03 22:31:01 +03:00
},
2023-01-29 18:57:29 +02:00
// depth
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Depth,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
count: None,
},
],
label: Some("Light Bind Group Layout"),
2022-10-03 22:31:01 +03:00
});
let light_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &light_bind_group_layout,
2023-01-29 18:57:29 +02:00
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: light_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&light_depth_texture.view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&light_depth_texture.sampler),
},
],
label: Some("Light Bind Group"),
2022-10-03 22:31:01 +03:00
});
2022-10-02 18:59:20 +03:00
surface.configure(&device, &config);
2022-10-01 23:58:09 +03:00
let texture_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
2022-10-04 01:30:50 +03:00
// diffuse
2022-10-01 23:58:09 +03:00
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
2022-10-04 01:30:50 +03:00
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
// normal
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
2022-10-01 23:58:09 +03:00
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
2023-01-24 03:59:06 +02:00
// metallic + roughness
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
2022-10-01 23:58:09 +03:00
],
label: Some("texture_bind_group_layout"),
});
2023-01-29 14:54:23 +02:00
let model = resources::load_model_gltf(
2023-01-27 21:45:08 +02:00
"models/Sponza.glb",
2023-01-23 17:15:02 +02:00
&device,
&queue,
&texture_bind_group_layout,
)
.await
.unwrap();
2022-10-02 22:03:50 +03:00
let light_model = resources::load_model_gltf(
"models/Cube.glb",
&device,
&queue,
&texture_bind_group_layout,
)
.await
.unwrap();
2023-01-27 02:40:40 +02:00
let instances = vec![Instance {
position: [0.0, 0.0, 0.0].into(),
rotation: cgmath::Quaternion::one(),
}];
2022-10-02 22:03:50 +03:00
2022-10-02 18:59:20 +03:00
let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<_>>();
let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Instance Buffer"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsages::VERTEX,
});
2023-01-29 14:54:23 +02:00
let geometry_pass = RenderPass::new(
&device,
&[
&camera_bind_group_layout,
&light_bind_group_layout,
2023-01-29 18:57:29 +02:00
&texture_bind_group_layout,
2023-01-29 14:54:23 +02:00
],
&[],
"pbr.wgsl",
2023-01-29 18:57:29 +02:00
Some(config.format),
2023-01-29 14:54:23 +02:00
Some(Texture::DEPTH_FORMAT),
&[ModelVertex::desc(), InstanceRaw::desc()],
2023-01-29 18:57:29 +02:00
"geometry pass",
2023-01-29 14:54:23 +02:00
);
2022-10-01 23:58:09 +03:00
2023-01-29 14:54:23 +02:00
let light_debug_pass = RenderPass::new(
&device,
&[&camera_bind_group_layout, &light_bind_group_layout],
&[],
"light.wgsl",
2023-01-29 18:57:29 +02:00
Some(config.format),
2023-01-29 14:54:23 +02:00
Some(Texture::DEPTH_FORMAT),
&[ModelVertex::desc()],
2023-01-29 18:57:29 +02:00
"light debug pass",
);
let light_depth_pass = RenderPass::new(
&device,
&[
&camera_bind_group_layout,
&light_bind_group_layout,
&texture_bind_group_layout,
],
&[],
"depth.wgsl",
None,
Some(Texture::DEPTH_FORMAT),
&[ModelVertex::desc(), InstanceRaw::desc()],
"light depth pass",
2023-01-29 14:54:23 +02:00
);
2022-10-01 23:58:09 +03:00
2023-01-28 14:11:54 +02:00
Self {
2022-10-01 23:58:09 +03:00
size,
surface,
device,
queue,
config,
2023-01-29 14:54:23 +02:00
geometry_pass,
2022-10-02 18:59:20 +03:00
camera,
camera_uniform,
camera_buffer,
camera_bind_group,
camera_controller,
instances,
instance_buffer,
2022-10-02 22:03:50 +03:00
depth_texture,
2023-01-29 14:54:23 +02:00
model,
light_model,
2022-10-03 22:31:01 +03:00
light_uniform,
light_buffer,
2023-01-29 14:54:23 +02:00
light_debug_pass,
2022-10-03 22:31:01 +03:00
light_bind_group,
2023-01-29 18:57:29 +02:00
light_depth_pass,
light_depth_texture,
2023-01-28 14:11:54 +02:00
}
2022-10-01 23:58:09 +03:00
}
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
if new_size.width > 0 && new_size.height > 0 {
self.size = new_size;
self.config.width = new_size.width;
self.config.height = new_size.height;
self.surface.configure(&self.device, &self.config);
2022-10-02 18:59:20 +03:00
self.camera
.projection
.resize(new_size.width, new_size.height);
2023-01-29 18:57:29 +02:00
self.depth_texture = Texture::create_depth_texture(
&self.device,
&self.config,
"depth_texture",
Some(wgpu::CompareFunction::LessEqual),
);
self.light_depth_texture = Texture::create_depth_texture(
&self.device,
&self.config,
"light_depth_texture",
Some(wgpu::CompareFunction::LessEqual),
);
2022-10-01 23:58:09 +03:00
}
}
2022-10-02 18:59:20 +03:00
pub fn input(
&mut self,
window_event: Option<&WindowEvent>,
device_event: Option<&DeviceEvent>,
) -> bool {
2023-01-29 14:54:23 +02:00
self.camera_controller
2023-01-28 14:11:54 +02:00
.process_events(window_event, device_event)
2022-10-01 23:58:09 +03:00
}
2022-10-02 18:59:20 +03:00
pub fn update(&mut self, dt: Duration) {
2022-10-03 22:31:01 +03:00
// Update camera
2022-10-02 18:59:20 +03:00
self.camera.update(dt, &self.camera_controller);
self.camera_controller.reset(false);
2022-10-03 22:31:01 +03:00
self.camera_uniform.update(&self.camera);
2022-10-02 18:59:20 +03:00
self.queue.write_buffer(
&self.camera_buffer,
0,
bytemuck::cast_slice(&[self.camera_uniform]),
);
2022-10-03 22:31:01 +03:00
// Update the light
let old_position: cgmath::Vector3<_> = self.light_uniform.position.into();
self.light_uniform.position =
2023-01-23 17:15:02 +02:00
(cgmath::Quaternion::from_angle_y(cgmath::Deg(90.0 * dt.as_secs_f32())) * old_position)
.into();
2022-10-03 22:31:01 +03:00
self.queue.write_buffer(
&self.light_buffer,
0,
bytemuck::cast_slice(&[self.light_uniform]),
);
2022-10-02 18:59:20 +03:00
}
2022-10-01 23:58:09 +03:00
pub fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
2023-01-29 15:40:37 +02:00
let surface_texture = self.surface.get_current_texture()?;
let surface_view = surface_texture
2022-10-01 23:58:09 +03:00
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
2023-01-29 18:57:29 +02:00
/*
{
let mut light_depth_render_pass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Light Depth Render Pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.light_depth_texture.view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: true,
}),
stencil_ops: None,
}),
});
light_depth_render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
light_depth_render_pass.set_pipeline(&self.light_depth_pass.pipeline);
light_depth_render_pass.draw_model_instanced(
&self.model,
0..self.instances.len() as u32,
&self.camera_bind_group, // TODO light projection
&self.light_bind_group, // TODO remove
);
}
*/
2022-10-01 23:58:09 +03:00
{
2023-01-29 15:40:37 +02:00
let mut geom_render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Geometry Render Pass"),
2022-10-03 22:31:01 +03:00
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2023-01-29 15:40:37 +02:00
view: &surface_view,
2022-10-03 22:31:01 +03:00
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.0,
g: 0.0,
b: 0.0,
a: 1.0,
}),
store: true,
},
})],
2022-10-02 22:03:50 +03:00
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_texture.view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: true,
}),
stencil_ops: None,
}),
2022-10-01 23:58:09 +03:00
});
2023-01-29 15:40:37 +02:00
geom_render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
geom_render_pass.set_pipeline(&self.geometry_pass.pipeline);
geom_render_pass.draw_model_instanced(
&self.model,
0..self.instances.len() as u32,
2022-10-03 22:31:01 +03:00
&self.camera_bind_group,
&self.light_bind_group,
);
2023-01-29 15:40:37 +02:00
}
2022-10-03 22:31:01 +03:00
2023-01-29 15:40:37 +02:00
{
let mut light_debug_render_pass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Light Debug Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &surface_view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: true,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_texture.view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: true,
}),
stencil_ops: None,
}),
});
light_debug_render_pass.set_pipeline(&self.light_debug_pass.pipeline);
light_debug_render_pass.draw_light_model(
&self.light_model,
2022-10-02 22:03:50 +03:00
&self.camera_bind_group,
2022-10-03 22:31:01 +03:00
&self.light_bind_group,
2022-10-02 22:03:50 +03:00
);
2022-10-01 23:58:09 +03:00
}
// submit will accept anything that implements IntoIter
self.queue.submit(std::iter::once(encoder.finish()));
2023-01-29 15:40:37 +02:00
surface_texture.present();
2022-10-01 23:58:09 +03:00
2023-01-28 14:11:54 +02:00
Ok(())
2022-10-01 23:58:09 +03:00
}
}