//! Single mesh use crate::vertex::*; use std::ops::Range; use bytemuck::cast_slice; use wgpu::{ util::{BufferInitDescriptor, DeviceExt}, * }; pub const INDEX_FORMAT: IndexFormat = IndexFormat::Uint32; pub struct Mesh { vertices: Buffer, indices: Buffer, index_count: u32 } impl Mesh { /// Create a new mesh from vertices and indices pub fn new(device: &Device, vertex_data: &[V], index_data: &[Index]) -> Self { let vertices = device.create_buffer_init(&BufferInitDescriptor { label: Some("Mesh Vertices"), contents: cast_slice(vertex_data), usage: BufferUsages::VERTEX }); let indices = device.create_buffer_init(&BufferInitDescriptor { label: Some("Mesh Indices"), contents: cast_slice(index_data), usage: BufferUsages::INDEX }); let index_count = index_data.len() as u32; Self { vertices, indices, index_count } } /// Draw a single instance of this mesh. /// Drawing indexed or indirectly is prefered. pub fn draw<'a>(&'a self, pass: &mut RenderPass<'a>) { pass.set_vertex_buffer(0, self.vertices.slice(..)); pass.set_index_buffer(self.indices.slice(..), INDEX_FORMAT); pass.draw_indexed(0..self.index_count, 0, 0..1); } /// Draw multiple instances of this mesh, the instance buffer must be bound already. /// Drawing indirectly is prefered. pub fn draw_instanced<'a>(&'a self, pass: &mut RenderPass<'a>, instances: Range) { pass.set_vertex_buffer(0, self.vertices.slice(..)); pass.set_index_buffer(self.indices.slice(..), INDEX_FORMAT); pass.draw_indexed(0..self.index_count, 0, instances); } }