From 1a9fc9fb63b9b56217492739136406f08f46cc68 Mon Sep 17 00:00:00 2001 From: Florian RICHER Date: Sun, 12 Jun 2022 22:18:35 +0200 Subject: [PATCH] [INSTANCING] From tutorial --- engine_core/src/instance.rs | 60 +++++++++++++++++++++++ engine_core/src/lib.rs | 1 + engine_core/src/shader.wgsl | 16 ++++++- engine_core/src/state.rs | 95 +++++++++++++++++++++++++++---------- 4 files changed, 147 insertions(+), 25 deletions(-) create mode 100644 engine_core/src/instance.rs diff --git a/engine_core/src/instance.rs b/engine_core/src/instance.rs new file mode 100644 index 0000000..46f789d --- /dev/null +++ b/engine_core/src/instance.rs @@ -0,0 +1,60 @@ +pub struct Instance { + pub position: cgmath::Vector3, + pub rotation: cgmath::Quaternion, +} + +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +pub struct InstanceRaw { + model: [[f32; 4]; 4], +} + +impl Instance { + pub fn to_raw(&self) -> InstanceRaw { + InstanceRaw { + model: (cgmath::Matrix4::from_translation(self.position) + * cgmath::Matrix4::from(self.rotation)) + .into(), + } + } +} + +impl InstanceRaw { + pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> { + use std::mem; + wgpu::VertexBufferLayout { + array_stride: mem::size_of::() as wgpu::BufferAddress, + // We need to switch from using a step mode of Vertex to Instance + // This means that our shaders will only change to use the next + // instance when the shader starts processing a new instance + step_mode: wgpu::VertexStepMode::Instance, + attributes: &[ + wgpu::VertexAttribute { + offset: 0, + // While our vertex shader only uses locations 0, and 1 now, in later tutorials we'll + // be using 2, 3, and 4, for Vertex. We'll start at slot 5 not conflict with them later + shader_location: 5, + format: wgpu::VertexFormat::Float32x4, + }, + // A mat4 takes up 4 vertex slots as it is technically 4 vec4s. We need to define a slot + // for each vec4. We'll have to reassemble the mat4 in + // the shader. + wgpu::VertexAttribute { + offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress, + shader_location: 6, + format: wgpu::VertexFormat::Float32x4, + }, + wgpu::VertexAttribute { + offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress, + shader_location: 7, + format: wgpu::VertexFormat::Float32x4, + }, + wgpu::VertexAttribute { + offset: mem::size_of::<[f32; 12]>() as wgpu::BufferAddress, + shader_location: 8, + format: wgpu::VertexFormat::Float32x4, + }, + ], + } + } +} diff --git a/engine_core/src/lib.rs b/engine_core/src/lib.rs index 133eeca..e0f253f 100644 --- a/engine_core/src/lib.rs +++ b/engine_core/src/lib.rs @@ -2,6 +2,7 @@ mod state; pub(self) mod vertex; pub(self) mod texture; pub(self) mod camera; +pub(self) mod instance; use winit::{ event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}, diff --git a/engine_core/src/shader.wgsl b/engine_core/src/shader.wgsl index 38be381..1e8fed4 100644 --- a/engine_core/src/shader.wgsl +++ b/engine_core/src/shader.wgsl @@ -1,3 +1,10 @@ +struct InstanceInput { + [[location(5)]] model_matrix_0: vec4; + [[location(6)]] model_matrix_1: vec4; + [[location(7)]] model_matrix_2: vec4; + [[location(8)]] model_matrix_3: vec4; +}; + struct CameraUniform { view_proj: mat4x4; }; @@ -17,10 +24,17 @@ struct VertexOutput { [[stage(vertex)]] fn vs_main( model: VertexInput, + instance: InstanceInput, ) -> VertexOutput { + let model_matrix = mat4x4( + instance.model_matrix_0, + instance.model_matrix_1, + instance.model_matrix_2, + instance.model_matrix_3, + ); var out: VertexOutput; out.tex_coords = model.tex_coords; - out.clip_position = camera.view_proj * vec4(model.position, 1.0); + out.clip_position = camera.view_proj * model_matrix * vec4(model.position, 1.0); return out; } diff --git a/engine_core/src/state.rs b/engine_core/src/state.rs index b88df44..dceb8ed 100644 --- a/engine_core/src/state.rs +++ b/engine_core/src/state.rs @@ -1,4 +1,5 @@ use super::vertex::Vertex; +use cgmath::prelude::*; use wgpu::util::DeviceExt; use winit::{event::WindowEvent, window::Window}; @@ -27,6 +28,13 @@ const VERTICES: &[Vertex] = &[ const INDICES: &[u16] = &[0, 1, 4, 1, 2, 4, 2, 3, 4]; +const NUM_INSTANCES_PER_ROW: u32 = 10; +const INSTANCE_DISPLACEMENT: cgmath::Vector3 = cgmath::Vector3::new( + NUM_INSTANCES_PER_ROW as f32 * 0.5, + 0.0, + NUM_INSTANCES_PER_ROW as f32 * 0.5, +); + pub struct State { pub surface: wgpu::Surface, pub device: wgpu::Device, @@ -40,6 +48,8 @@ pub struct State { camera_buffer: wgpu::Buffer, camera_bind_group: wgpu::BindGroup, camera_controller: super::camera::CameraController, + instances: Vec, + instance_buffer: wgpu::Buffer, // num_vertices: u32, index_buffer: wgpu::Buffer, num_indices: u32, @@ -182,17 +192,15 @@ impl State { let mut camera_uniform = super::camera::CameraUniform::new(); camera_uniform.update_view_proj(&camera); - 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_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 { + let camera_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { @@ -201,19 +209,16 @@ impl State { min_binding_size: None, }, count: None, - } - ], - label: Some("camera_bind_group_layout"), - }); + }], + 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(), - } - ], + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: camera_buffer.as_entire_binding(), + }], label: Some("camera_bind_group"), }); @@ -226,13 +231,48 @@ impl State { push_constant_ranges: &[], }); + let instances = (0..NUM_INSTANCES_PER_ROW) + .flat_map(|z| { + (0..NUM_INSTANCES_PER_ROW).map(move |x| { + let position = cgmath::Vector3 { + x: x as f32, + y: 0.0, + z: z as f32, + } - INSTANCE_DISPLACEMENT; + + let rotation = if position.is_zero() { + // this is needed so an object at (0, 0, 0) won't get scaled to zero + // as Quaternions can effect scale if they're not created correctly + cgmath::Quaternion::from_axis_angle( + cgmath::Vector3::unit_z(), + cgmath::Deg(0.0), + ) + } else { + cgmath::Quaternion::from_axis_angle(position.normalize(), cgmath::Deg(45.0)) + }; + + super::instance::Instance { position, rotation } + }) + }) + .collect::>(); + + let instance_data = instances + .iter() + .map(super::instance::Instance::to_raw) + .collect::>(); + let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Instance Buffer"), + contents: bytemuck::cast_slice(&instance_data), + usage: wgpu::BufferUsages::VERTEX, + }); + let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Render Pipeline"), layout: Some(&render_pipeline_layout), vertex: wgpu::VertexState { module: &shader, entry_point: "vs_main", - buffers: &[Vertex::desc()], + buffers: &[Vertex::desc(), super::instance::InstanceRaw::desc()], }, fragment: Some(wgpu::FragmentState { module: &shader, @@ -262,7 +302,7 @@ impl State { alpha_to_coverage_enabled: false, }, multiview: None, - }); + }); Self { surface, @@ -282,6 +322,8 @@ impl State { num_indices, diffuse_bind_group, diffuse_texture, + instances, + instance_buffer, } } @@ -301,7 +343,11 @@ impl State { pub fn update(&mut self) { self.camera_controller.update_camera(&mut self.camera); self.camera_uniform.update_view_proj(&self.camera); - self.queue.write_buffer(&self.camera_buffer, 0, bytemuck::cast_slice(&[self.camera_uniform])); + self.queue.write_buffer( + &self.camera_buffer, + 0, + bytemuck::cast_slice(&[self.camera_uniform]), + ); } pub fn render(&mut self) -> Result<(), wgpu::SurfaceError> { @@ -342,9 +388,10 @@ impl State { render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]); render_pass.set_bind_group(1, &self.camera_bind_group, &[]); render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..)); + render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..)); render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16); // render_pass.draw(0..self.num_vertices, 0..1); - render_pass.draw_indexed(0..self.num_indices, 0, 0..1); + render_pass.draw_indexed(0..self.num_indices, 0, 0..self.instances.len() as _); } // submit will accept anything that implements IntoIter