eqemu

view src/mesh.cc @ 3:f9274bebe55e

adding 3d graphics stuff
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 17 Jul 2014 02:35:19 +0300
parents
children 3d3656360a82
line source
1 #include <stdio.h>
2 #include <string.h>
3 #include <GL/glew.h>
4 #include "mesh.h"
6 #define ALL_VALID 0xffffffff
8 Mesh::Mesh()
9 {
10 buf_valid = ALL_VALID;
12 for(int i=0; i<vcount; i++) {
13 attr[i] = 0;
14 attr_size[i] = 0;
15 buf_valid &= ~(1 << i);
16 }
17 vcount = 0;
18 glGenBuffers(NUM_MESH_ATTRIBS, vbo);
19 }
21 Mesh::~Mesh()
22 {
23 for(int i=0; i<vcount; i++) {
24 delete [] attr[i];
25 }
26 glDeleteBuffers(NUM_MESH_ATTRIBS, vbo);
27 }
29 float *Mesh::set_attrib(int aidx, int count, int elemsz, float *data)
30 {
31 if(attr[aidx]) {
32 delete [] attr[aidx];
33 }
34 attr[aidx] = new float[count * elemsz];
35 attr_size[aidx] = elemsz;
36 buf_valid &= ~(1 << aidx);
37 return attr[aidx];
38 }
40 float *Mesh::get_attrib(int aidx)
41 {
42 buf_valid &= ~(1 << aidx);
43 return attr[aidx];
44 }
46 const float *Mesh::get_attrib(int aidx) const
47 {
48 return attr[aidx];
49 }
51 void Mesh::draw() const
52 {
53 update_buffers();
55 if(!vbo[MESH_ATTR_VERTEX]) {
56 fprintf(stderr, "trying to render without a vertex buffer\n");
57 return;
58 }
60 glBindBuffer(GL_ARRAY_BUFFER, vbo[MESH_ATTR_VERTEX]);
61 glEnableClientState(GL_VERTEX_ARRAY);
62 glVertexPointer(attr_size[MESH_ATTR_VERTEX], GL_FLOAT, 0, 0);
64 if(vbo[MESH_ATTR_NORMAL]) {
65 glBindBuffer(GL_ARRAY_BUFFER, vbo[MESH_ATTR_NORMAL]);
66 glEnableClientState(GL_NORMAL_ARRAY);
67 glNormalPointer(GL_FLOAT, 0, 0);
68 }
69 if(vbo[MESH_ATTR_TEXCOORD]) {
70 glBindBuffer(GL_ARRAY_BUFFER, vbo[MESH_ATTR_TEXCOORD]);
71 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
72 glTexCoordPointer(attr_size[MESH_ATTR_TEXCOORD], GL_FLOAT, 0, 0);
73 }
74 glBindBuffer(GL_ARRAY_BUFFER, 0);
76 glDrawArrays(GL_TRIANGLES, 0, vcount);
78 glDisableClientState(GL_VERTEX_ARRAY);
79 if(vbo[MESH_ATTR_NORMAL]) {
80 glDisableClientState(GL_NORMAL_ARRAY);
81 }
82 if(vbo[MESH_ATTR_TEXCOORD]) {
83 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
84 }
85 }
87 void Mesh::update_buffers() const
88 {
89 if(buf_valid == ALL_VALID) {
90 return;
91 }
93 for(int i=0; i<NUM_MESH_ATTRIBS; i++) {
94 if((buf_valid & (1 << i)) == 0) {
95 glBindBuffer(GL_ARRAY_BUFFER, vbo[i]);
96 glBufferData(GL_ARRAY_BUFFER, vcount * attr_size[i] * sizeof(float),
97 attr[i], GL_STATIC_DRAW);
98 buf_valid |= 1 << i;
99 }
100 }
101 }