Home > Mobile >  Draw function with glDrawArrays() needs to be called twice for anything to show
Draw function with glDrawArrays() needs to be called twice for anything to show

Time:05-19

This is a strange problem. I have a function:

void drawLines(std::vector<GLfloat> lines) {
    glBindVertexArray(VAO2);

    //positions
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (void*)0);
    glEnableVertexAttribArray(0);

    //colors
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);

    glBindBuffer(GL_ARRAY_BUFFER, VBO2);
    glBufferData(GL_ARRAY_BUFFER, sizeof(lines[0]) * lines.size(), &lines[0], GL_STATIC_DRAW);

    glUseProgram(pShaderProgram);
    glDrawArrays(GL_TRIANGLES, 0, lines.size() / 6);
}

It draws lines of a specified thickness (this is built into the data of lines which contains three floats for position and three floats for color, per point with over 200 points to mark line endings). Calling the function once does not yield any result, even after following with SwapBuffers(HDC) and glFlush(). However, when I call the function twice, then everything shows. I suspect there is some nuance that I am missing with pushing the buffers through the render pipeline, that might be activated by binding the buffer multiple times. I am unsure. Any thoughts?

CodePudding user response:

glVertexAttribPointer expects a buffer bound to the GL_ARRAY_BUFFER binding point in order to establish an association between the generic vertex attribute and the buffer object to source the data from.

However, you bind the buffer with glBindBuffer(GL_ARRAY_BUFFER, VBO2) after the call to glVertexAttribPointer.

This is why you need two calls, because the first call will not associate any buffer object to the generic vertex attributes, since likely no buffer was bound before.

The way you are using VAOs is dubious, however, since everything you do in this method/function will already be saved as VAO state. So, you neither need to reestablish the association between generic vertex attributes and buffer objects every time, nor do you need to enable the generic vertex attributes every time you draw.

All of this can be done once when doing the vertex specification for the VAO.

  • Related