VBO: Array not drawn

2019-08-28 04:46发布

问题:

I'm following this guide and I'm trying to draw a quad to the screen. I also saw the source code, it's the same and it should work, but in my case nothing is displayed on the screen. I'm using OpenGL 2.0 with a vertex shader that just sets the color to be red in a way that the quad should be visible on the screen.

Before callig glutMainLoop I generate the vertex buffer object:

#include <GL/glut.h>
#include <GL/glew.h>

vector<GLfloat> quad; 
GLuint buffer;

void init()
{
    // This routine gets called before glutMainLoop(), I omitted all the code
    // that has to do with shaders, since it's correct.
    glewInit();
    quad= vector<GLfloat>{-1,-1,0, 1,-1,0, 1,1,0, -1,1,0};
    glGenBuffers(1,&buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*12,quad.data(),GL_STATIC_DRAW);
}

This is my rendering routine:

void display()
{
    glClearColor(0,0,0,0);
    glClear(GL_COLOR_BUFFER_BIT);

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER,buffer);
    glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0);
    // I also tried passing quad.data() as last argument, but nothing to do.
    glDrawArrays(GL_QUADS,0,12);
    glDisableVertexAttribArray(0);

    glutSwapBuffers();
}

The problem is that nothing is drawn to the screen, I just see a black window. The quad should be red because I set the red color in the vertex shader.

回答1:

So maybe the problem is the count in the glDrawArrays(GL_QUADS, 0, 12); which must be glDrawArrays(GL_QUADS, 0, 4);



回答2:

I was missing glEnableClientState like this:

glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_QUADS,0,12);
glDisableClientState(GL_VERTEX_ARRAY);