]> git.lizzy.rs Git - dragonblocks_alpha.git/blob - src/client/mesh.c
refactoring
[dragonblocks_alpha.git] / src / client / mesh.c
1 #include <stddef.h>
2 #include <stdlib.h>
3 #include "client/mesh.h"
4
5 // upload data to GPU (only done once)
6 void mesh_upload(Mesh *mesh)
7 {
8         glGenVertexArrays(1, &mesh->vao);
9         glGenBuffers(1, &mesh->vbo);
10
11         glBindVertexArray(mesh->vao);
12         glBindBuffer(GL_ARRAY_BUFFER, mesh->vbo);
13
14         glBufferData(GL_ARRAY_BUFFER, mesh->count * mesh->layout->size,
15                 mesh->data, GL_STATIC_DRAW);
16
17         size_t offset = 0;
18         for (GLuint i = 0; i < mesh->layout->count; i++) {
19                 VertexAttribute *attrib = &mesh->layout->attributes[i];
20
21                 glVertexAttribPointer(i, attrib->length, attrib->type, GL_FALSE,
22                         mesh->layout->size, (GLvoid *) offset);
23                 glEnableVertexAttribArray(i);
24
25                 offset += attrib->size;
26         }
27
28         glBindBuffer(GL_ARRAY_BUFFER, 0);
29         glBindVertexArray(0);
30
31         if (mesh->free_data)
32                 free(mesh->data);
33
34         mesh->data = NULL;
35 }
36
37 void mesh_render(Mesh *mesh)
38 {
39         if (mesh->data)
40                 mesh_upload(mesh);
41
42         // render
43         glBindVertexArray(mesh->vao);
44         glDrawArrays(GL_TRIANGLES, 0, mesh->count);
45 }
46
47 void mesh_destroy(Mesh *mesh)
48 {
49         if (mesh->data && mesh->free_data)
50                 free(mesh->data);
51
52         if (mesh->vao)
53                 glDeleteVertexArrays(1, &mesh->vao);
54
55         if (mesh->vbo)
56                 glDeleteBuffers(1, &mesh->vbo);
57
58         mesh->vao = mesh->vbo = 0;
59 }