c++openglvertex-attributes

Don't fully understand the concept of Vertex Attributes


I was following the OpenGL tutorial on learnopengl.com, and decided to test if I've fully grasped the concept of Vertex Attributes. I tried tweaking the code just to see if it works behind the scenes the way I think it does.

Here's what my modified vertices array looks like:

float vertices[] = {
    -0.5f, -0.5f, 0.0f, -0.5f,  0.5f,
     0.5f, -0.5f, 0.0f,  0.5f,  0.5f,
     0.0f,  0.5f, 0.0f,  0.0f, -0.5f,
};

Each vertex is now 5 floats wide, and what I instead want as my position attribute is the last two floats of each vertex (as x and y respectively, with z defaulting to 0.0).

So here's my modified vertex attribute specifications:

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*) 3);
glEnableVertexAttribArray(0);

Currently, how I read the first function (from left to right) is - "The 0th vertex-attribute consists of 2 floats that aren't normalized. Each vertex consists of 5 floats, and the 0th attribute is located 3 indices from the left of each vertex."

My modified vertex shader looks like this:

#version 330 core
layout(location = 0) in vec2 aPos;

void main() {
    gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);
}

My current understanding is that location = 0 specifies we're looking at the 0th attribute, which is my position attribute. I used vec2 since the attribute only has 2 floats.

What I want the program to render is an upside down isosceles triangle, but it ends up rendering is nothing other than the background. So what exactly is missing from my understanding of how vertex attributes work behind the scenes?


Solution

  • The last argument of glVertexAttribPointer is a byte offset into the buffer object's data store. The offset of the 3rd component is 3 * sizeof(float) instead of 3:

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*) 3);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 
        5 * sizeof(float), (void*)(3 * sizeof(float)));