SparrowRenderer/mesh.cpp

81 lines
1.9 KiB
C++

#include "mesh.h"
#include "glassert.h"
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
Mesh::~Mesh()
{
destroyGL();
}
void Mesh::addVertex(const Vertex& v)
{
if(!locked)
vertices.push_back(v);
}
void Mesh::addFace(int i1, int i2, int i3)
{
if(!locked)
{
indices.push_back(i1);
indices.push_back(i2);
indices.push_back(i3);
}
}
void Mesh::initGL()
{
if(locked)
destroyGL();
// create VAO
glAssert(glGenVertexArrays(1, &vao));
glAssert(glBindVertexArray(vao));
// create VBOs
glAssert(glGenBuffers(NB_BUFFERS, vbo));
// init vertex vbo
glAssert(glBindBuffer(GL_ARRAY_BUFFER, vbo[VERTEX_BUFFER]));
glAssert(glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW));
// position attribute
glAssert(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), BUFFER_OFFSET(0)));
glAssert(glEnableVertexAttribArray(0));
// normal attribute
glAssert(glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), BUFFER_OFFSET(sizeof(glm::vec3))));
glAssert(glEnableVertexAttribArray(1));
// texCoord attribute
glAssert(glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), BUFFER_OFFSET(2*sizeof(glm::vec3))));
glAssert(glEnableVertexAttribArray(2));
// init indices vbo
glAssert(glBindBuffer(GL_ARRAY_BUFFER, vbo[INDICES_BUFFER]));
glAssert(glBufferData(GL_ARRAY_BUFFER, indices.size() * sizeof(GLuint), indices.data(), GL_STATIC_DRAW));
// unbind vao
glAssert(glBindVertexArray(0));
locked = true;
}
void Mesh::destroyGL()
{
if(locked)
{
locked = false;
glAssert(glDeleteVertexArrays(1, &vao));
glAssert(glDeleteBuffers(2, vbo));
}
}
void Mesh::draw()
{
if(locked)
{
glAssert(glBindVertexArray(vao));
glAssert(glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, indices.data()));
}
}