Skip to content
systemcoding.dev
GPU

Describe interleaved vertices with glVertexAttribPointer

Describe interleaved vertices with glVertexAttribPointer using one stride and two byte offsets for position and colour in OpenGL 3.3.

1 min read
Summarize in AI

When position and colour live in the same vertex struct, one buffer feeds two attributes. The trick is that the stride is the size of the whole vertex and the last argument is a byte offset into it, cast to a pointer.

vertex.cc
typedef struct { float pos[3]; float col[3]; } Vertex;

glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                      (void *)offsetof(Vertex, pos));
glEnableVertexAttribArray(0);

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                      (void *)offsetof(Vertex, col));
glEnableVertexAttribArray(1);

printf("stride=%zu colour offset=%zu\n", sizeof(Vertex), offsetof(Vertex, col));
Text
stride=24 colour offset=12

Both calls capture the buffer that is bound to GL_ARRAY_BUFFER at that moment, which is why the bind comes first; the glVertexAttribPointer page states that the binding is stored with the attribute. Use offsetof instead of hand-counted numbers so the layout survives a reordered struct. A stride of 0 means tightly packed, but only for a single attribute; with two it silently reads the wrong floats.

Integer attributes need glVertexAttribIPointer instead, or the values are converted to floats.

Taggedcopengl
Share

More snippets

GPU

List platforms with clGetPlatformIDs

Call clGetPlatformIDs twice, once for the count and once for the handles, then print each platform name with clGetPlatformInfo in OpenCL 3.0 C.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.