mesh.c (2225B)
1 #include "mesh.h" 2 3 #include "glad/glad.h" 4 5 #include <stdlib.h> 6 7 void Mesh_init(Mesh *m, u32 vertex_count, u32 index_count) 8 { 9 m->vertex_capacity = vertex_count; 10 m->vertex_count = 0; 11 12 m->index_capacity = index_count; 13 m->index_count = 0; 14 15 glGenVertexArrays(1, &m->vao); 16 glBindVertexArray(m->vao); 17 18 glGenBuffers(1, &m->vbo); 19 glBindBuffer(GL_ARRAY_BUFFER, m->vbo); 20 glBufferData( 21 GL_ARRAY_BUFFER, 22 sizeof *m->vertices * vertex_count, 23 NULL, 24 GL_STATIC_DRAW 25 ); 26 27 glVertexAttribPointer( 28 0, 29 3, 30 GL_FLOAT, 31 GL_FALSE, 32 sizeof(Vertex), 33 (GLvoid*)0 34 ); 35 glEnableVertexAttribArray(0); 36 37 glVertexAttribPointer( 38 1, 39 3, 40 GL_FLOAT, 41 GL_FALSE, 42 sizeof(Vertex), 43 (GLvoid*)sizeof(Vec3) 44 ); 45 glEnableVertexAttribArray(1); 46 47 glGenBuffers(1, &m->ebo); 48 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ebo); 49 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof *m->indices * index_count, 50 NULL, GL_STATIC_DRAW); 51 52 glBindVertexArray(0); 53 } 54 55 void Mesh_free(Mesh *m) 56 { 57 m->vertex_capacity = 0; 58 m->vertex_count = 0; 59 60 m->index_capacity = 0; 61 m->index_count = 0; 62 63 Mesh_unmapBuffers(m); 64 65 glDeleteVertexArrays(1, &m->vao); 66 glDeleteBuffers(1, &m->vbo); 67 glDeleteBuffers(1, &m->ebo); 68 } 69 70 void Mesh_mapBuffers(Mesh *m) 71 { 72 glBindBuffer(GL_ARRAY_BUFFER, m->vbo); 73 m->vertices = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); 74 75 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ebo); 76 m->indices = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY); 77 78 m->buffers_mapped = true; 79 } 80 81 void Mesh_unmapBuffers(Mesh *m) 82 { 83 glBindBuffer(GL_ARRAY_BUFFER, m->vbo); 84 glUnmapBuffer(GL_ARRAY_BUFFER); 85 m->vertices = NULL; 86 87 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ebo); 88 glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); 89 m->indices = NULL; 90 91 m->buffers_mapped = false; 92 } 93 94 void Mesh_draw(const Mesh *m) 95 { 96 if (!m->buffers_mapped) 97 { 98 glBindVertexArray(m->vao); 99 glDrawElements(GL_TRIANGLES, m->index_count, GL_UNSIGNED_INT, 0); 100 glBindVertexArray(0); 101 } 102 }