VBO必须在VAO之后绑定

时间:2018-09-09 13:53:10

标签: c++ opengl sdl 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);
}

我有问题。我不知道为什么在渲染功能中绑定vao之后必须绑定vbo。当我不绑定vbo时,在RenderDoc中出现错误“ glDrawArrays产生了错误(GL_OUT_OF_MEMORY)”,并且在网格输出中,在VS输入中,我看到了错误的值或---值。

1 个答案:

答案 0 :(得分:1)

  

我不知道为什么在渲染功能中绑定vao之后必须绑定vbo”

由于您尝试通过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来更改缓冲区的内容。这将更新缓冲区,但不会创建和初始化全新的数据存储,因此效率更高。