From c12966c5b69841f49713f97f3d9fa7ba99fc42e7 Mon Sep 17 00:00:00 2001 From: HampusM Date: Mon, 23 Oct 2023 20:25:42 +0200 Subject: feat(engine): add using element buffers --- engine/src/renderer/mod.rs | 59 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 6 deletions(-) (limited to 'engine/src/renderer') diff --git a/engine/src/renderer/mod.rs b/engine/src/renderer/mod.rs index f31196d..a02bbc2 100644 --- a/engine/src/renderer/mod.rs +++ b/engine/src/renderer/mod.rs @@ -5,7 +5,12 @@ use cstr::cstr; use glfw::WindowSize; use crate::object::Object; -use crate::opengl::buffer::{Buffer, Usage}; +use crate::opengl::buffer::{ + ArrayKind as ArrayBufferKind, + Buffer, + ElementArrayKind as ElementArrayBufferKind, + Usage as BufferUsage, +}; #[cfg(feature = "debug")] use crate::opengl::debug::{MessageSeverity, MessageSource, MessageType}; use crate::opengl::shader::Program as ShaderProgram; @@ -106,7 +111,21 @@ pub fn render<'obj>(objects: impl IntoIterator) .set_uniform_matrix_4fv(cstr!("transform"), &obj.transform().as_matrix()); obj.renderable().vertex_arr.bind(|vert_arr_curr_bound| { - VertexArray::draw(&vert_arr_curr_bound, PrimitiveKind::Triangles, 0, 3); + if let Some(index_info) = &obj.renderable().index_info { + VertexArray::draw_elements( + &vert_arr_curr_bound, + PrimitiveKind::Triangles, + 0, + index_info.cnt, + ); + } else { + VertexArray::draw_arrays( + &vert_arr_curr_bound, + PrimitiveKind::Triangles, + 0, + 3, + ); + } }); } } @@ -122,29 +141,57 @@ pub struct Renderable shader_program: ShaderProgram, vertex_arr: VertexArray, - /// Vertex buffer has to live as long as the vertex array - _vertex_buffer: Buffer, + /// Vertex and index buffer has to live as long as the vertex array + _vertex_buffer: Buffer, + index_info: Option, +} + +#[derive(Debug)] +struct IndexInfo +{ + _buffer: Buffer, + cnt: u32, } impl Renderable { - pub fn new(shader_program: ShaderProgram, vertices: &[Vertex]) -> Self + pub fn new( + shader_program: ShaderProgram, + vertices: &[Vertex], + indices: Option<&[u32]>, + ) -> Self { let vertex_arr = VertexArray::new(); let vertex_buffer = Buffer::new(); + let mut index_info = None; + vertex_arr.bind(|vert_arr_curr_bound| { vertex_buffer.bind(|vert_buf_curr_bound| { - Buffer::store(&vert_buf_curr_bound, vertices, Usage::Static); + Buffer::store(&vert_buf_curr_bound, vertices, BufferUsage::Static); VertexArray::configure_attrs(&vert_arr_curr_bound, &vert_buf_curr_bound); }); + + if let Some(indices) = indices { + let new_index_buffer = Buffer::new(); + + new_index_buffer.bind(|index_buf_curr_bound| { + Buffer::store(&index_buf_curr_bound, indices, BufferUsage::Static); + }); + + index_info = Some(IndexInfo { + _buffer: new_index_buffer, + cnt: indices.len().try_into().unwrap(), + }); + } }); Self { shader_program, vertex_arr, _vertex_buffer: vertex_buffer, + index_info, } } } -- cgit v1.2.3-18-g5258