Search code examples
c++openglopengl-3

OpenGL 3.x - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER) and VAOs


I have a method for initializing my VBO/VAO:

        glBindBuffer(GL_ARRAY_BUFFER, mVBO_VertexShader);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions, GL_STATIC_DRAW);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexData), indexData, GL_STATIC_DRAW);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);


        // setup VAO
        glBindVertexArray(mVAO);

        glBindBuffer(GL_ARRAY_BUFFER, mVBO_VertexShader);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);

And then a separate method for drawing;

    glBindVertexArray(mVAO);
    glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_SHORT, &mIndexBuffer);
    glBindVertexArray(0);

Do I need to unbind the GL_ELEMENT_ARRAY_BUFFER after my call to glDrawElements or is its state 'tied' to the VAO? (So if I unbind the VAO, the GL_ELEMENT_ARRAY_BUFFER will also be unbound)?


Solution

  • GL_ELEMENT_ARRAY_BUFFER is tied to the VAO state. I quote the OpenGL 3.3 spec: "The resulting vertex array object is a new state vector, comprising all the state values listed in tables 6.4 and 6.5." Table 6.4 contains ELEMENT ARRAY BUFFER BINDING. So no, you do not need to unbind it.

    Additionally, you probably want to pass NULL as the last parameter to glDrawElements in your example, since the address is relative to the bound element array buffer..