copengl3dglslvertex-attributes

Clarification on glVertexAttribPointer index paramter


I have a very simple program to display a 3D triangle in OpenGL. hat value I put in, it does not display correctly. I put in the following array into the vertex buffer

float triangle[] = {
//  x     y       z      r      g      b      a
    0.2f, -0.2f, -0.5f,  0.0f,  0.0f,  0.0f,  1.0f,
   -0.2f, -0.2f, -0.5f,  0.0f,  0.0f,  0.0f,  1.0f,
   -0.2f,  0.2f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
    0.0f, -0.2f,  0.0f,  0.0f,  0.0f,  0.0f,  1.0f
};

And I use the following to pass them to the vertex shader

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, 0);

glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 7, 0);

But the output triangle has a strange blue area, even though the positions are correct, which doesn't make sense since the input colours should be black. I have seen some use the index as sizeof(float) * 3 and sizeof(float) * 4, but that makes the triangle green and makes the positions wrong. The docs.gl entry is pretty vague, and doesn't provide any examples. Here are my shaders

Fragment Shader

#version 330 core
out vec4 color;

in vec4 outColor;

void main() {
    out vec4 outColor;
    uniform mat4 transform;

    void main() {
      gl_Position = transform * inPos;
      outColor = inColor;
    };

What is wrong here?


Solution

  • If a named buffer object is bound, then the last argument of glVertexAttribPointer is treated as a byte offset in the buffers data store.
    The offset of the color attribute is 3*sizeof(float) bytes:

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, 0);
    
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 7, 
        (void*)(sizeof(float) * 3)); // <--- byte offset
    

    The attribute consists of 7 components (x, y, z, r, g, b, a). The offset of the vertex coordinate is 0, because this are the first 3 components in the tuple. The offset of the color is 3*sizeof(float), because this are the components from 4 to 7.