VBO必须绑定在VAO之后

VBO must be bound after VAO

代码:

void render()
{
    glClear(GL_COLOR_BUFFER_BIT);

    GLfloat vertices[6][4] = {
        { 1.0f, 1.0f, 1.0f, 1.0f },
        { 1.0f, 1.0f, 1.0f, 1.0f },
        { 1.0f, 1.0f, 1.0f, 1.0f },

        { 1.0f, 1.0f, 1.0f, 1.0f },
        { 1.0f, 1.0f, 1.0f, 1.0f },
        { 1.0f, 1.0f, 1.0f, 1.0f }
    };

    glUseProgram(shadptr->progGraphics);
    glBindVertexArray(vao_g);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_g);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, vertices, GL_DYNAMIC_DRAW);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    glUseProgram(shadptr->progText);
    glBindVertexArray(vao_t);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_t);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, vertices, GL_DYNAMIC_DRAW);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    SDL_GL_SwapWindow(winptr->window);
}

void set_buffers()
{
    glGenVertexArrays(1, &vao_g);
    glBindVertexArray(vao_g);

    glGenBuffers(1, &vbo_g);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_g);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr);

    glGenVertexArrays(1, &vao_t);
    glBindVertexArray(vao_t);

    glGenBuffers(1, &vbo_t);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_t);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr);
}

我有问题。不知道为什么在render函数中绑定vao之后还要绑定vbo。当我不绑定 vbo 时,在 RenderDoc 中出现错误 "glDrawArrays has generated an error (GL_OUT_OF_MEMORY)",在网格输出中,在 VS 输入中我看到错误的值或 --- 值。

I don't know why I have to bind vbo after binding vao in render function"

因为您尝试通过 glBufferData 创建和初始化缓冲区对象的数据存储,为此必须绑定缓冲区。

我建议将创建和初始化缓冲区的代码移动到 set_buffers。然后在函数 render:

中只绑定顶点数组对象就足够了
void render()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(shadptr->progGraphics);
    glBindVertexArray(vao_g);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    glUseProgram(shadptr->progText);
    glBindVertexArray(vao_t);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    SDL_GL_SwapWindow(winptr->window);
}

void set_buffers()
{
    ....

    GLfloat vertices[6][4] = {
        { 1.0f, 1.0f, 1.0f, 1.0f },
        { 1.0f, 1.0f, 1.0f, 1.0f },
        { 1.0f, 1.0f, 1.0f, 1.0f },

        { 1.0f, 1.0f, 1.0f, 1.0f },
        { 1.0f, 1.0f, 1.0f, 1.0f },
        { 1.0f, 1.0f, 1.0f, 1.0f }
    };

    glBindBuffer(GL_ARRAY_BUFFER, vbo_g);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, vertices, GL_DYNAMIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, vbo_t);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, vertices, GL_DYNAMIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

我推荐使用glBufferSubData来改变缓冲区的内容。这将更新缓冲区,但不会创建和初始化一个全新的数据存储,因此效率会更高。