1
votes

I am trying to draw two quads using vertex buffer objects in OpenGL. They should be draw with different colors. Like you see, the first quad has a red, green, blue and yellow vertices. The second quad has different colors, but the problem is that they second quad gets drawn completely yellow. This is my code:

GLfloat vertices[24] = {10.0, 10.0, 0.0,  10.0, -10.0, 0.0,  -10.0, -10.0, 0.0,  -10.0, 10.0, 0.0,
                        20.0, 20.0, 0.0,  20.0, 10.0, 0.0,    10.0, 10.0, 0.0,    10.0, 20.0, 0.0 };    
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 24, vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

GLfloat colors[24] = {1.0, 0.0, 0.0,  0.0, 1.0, 0.0,  0.0, 0.0, 1.0,  1.0, 1.0, 0.0,
                      0.5, 0.5, 0.5,   0.7, 0.2, 1.0,  0.2, 1.0, 0.7,  0.8, 0.0, 0.45 };
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLfloat) * 24, colors, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);


glEnableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glVertexPointer(3, GL_FLOAT, 0, 0);

glEnableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, colorBuffer);
glColorPointer(3, GL_FLOAT, 0, 0);

glDrawArrays(GL_QUADS, 0, 8);

This is how the quads are drawn:

enter image description here

The second quad is the one on top right. It should be multicolored, but it's drawn using the 4th element of the color buffer. What should I do to fix it?

1
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer); instead of glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, colorBuffer); Note, in your case buffer keeps bound and is used for glColorPointer too.Rabbid76
@Rabbid76 If you make your comment an answer I can accept it. I don't see why the question should be closed, it doesn't violate any guide line.Ramy Al Zuhouri

1 Answers

2
votes

See OpenGL 2.1 Reference Pages; glColorPointer:

glColorPointer specifies the location and data format of an array of color components to use when rendering. ...

If a non-zero named buffer object is bound to the GL_ARRAY_BUFFER target while a color array is specified, pointer is treated as a byte offset into the buffer object's data store.

In your code buffer is bound to the target GL_ARRAY_BUFFER;

glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);

Then colorBuffer is bound to the target GL_ELEMENT_ARRAY_BUFFER and the color array is defined:

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, colorBuffer);
glColorPointer(3, GL_FLOAT, 0, 0);

Since buffer is still bound to the target GL_ARRAY_BUFFER at this point, glColorPointer uses buffer. This causes that the vertex coordinates are treated as colors and that`s what you can see in the rendering.

To solve the issue you have to bint colorBuffer to the target GL_ARRAY_BUFFER:

glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);