Reputation: 21966
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:
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?
Upvotes: 1
Views: 912
Reputation: 210908
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);
Upvotes: 2