Hello everyone I am pretty much a newbie and I would appreciate your assistance.
I have made a simple OpenGL application which reads an .obj file and renders it.
I read the file and put the vertex and indices data in two vectors: std::vector vertices<Vertex> and std::vector indices<GLuint>. Vertex is a struct I constructed:
struct Vertex{
glm::vec3 Position;
glm::vec3 Normal;
}
So now lets suppose I have read an .obj and have filled the above vectors with its data. After that, using the following code I setup my buffers before I render the mesh.
void Mesh::setupBuffers()
{
glGenVertexArrays(1,&VAO);
glGenBuffers(1,&VBO);
glGenBuffers(1,&EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER,VBO);
glBufferData(GL_ARRAY_BUFFER,vertices.size()*sizeof(MyVertex),&vertices[0],GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,indices.size()*sizeof(GLuint),&indices[0],GL_STATIC_DRAW);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(MyVertex),(GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,sizeof(MyVertex),(GLvoid*)offsetof(MyVertex,Normal));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
}
Note that the above code is called only once, namely after I load a new .obj .
Finally to render the mesh I use:
void Mesh::Draw()
{
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES,indices.size(),GL_UNSIGNED_INT,0);
glBindVertexArray(0);
GLenum error = glGetError();
if(error) std::cout << error << std::endl;
}
the Draw function is being called in every render iteration.
The problem arises when I have rendered the first model and want to draw another one. Lets say that by pressing button ‘a’ another model is being loaded (by clearing and filling the same vertices and indices vectors as above), setupBuffer() is being called and the program enters the rendering loop. That way the mesh is not being drawn and I get error 1282
I found out that if I instead call the setupBuffer() in every render iteration,namely:
void Mesh::Draw()
{
setupBuffers();
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES,indices.size(),GL_UNSIGNED_INT,0);
glBindVertexArray(0);
GLenum error = glGetError();
if(error) std::cout << error << std::endl;
}
everything works fine and I get no errors.
Since the vertices and indices data don’t change why do I have to use setupBuffers in every rendering iteration? If not how do I fix this or do you have any hints what I might be missing/doing wrong ?
Regards