Skip to content
systemcoding.dev
GPU

Draw indexed triangles with glDrawElements

Draw indexed triangles with glDrawElements and an element buffer so a quad shares two vertices between its two triangles in OpenGL 3.3 core.

1 min read
Summarize in AI

A quad is four corners but two triangles, so drawing it with glDrawArrays needs six vertices. An element buffer lets you store four and reuse two of them by index.

quad.cc
const unsigned int idx[] = { 0, 1, 2,   2, 3, 0 };

glBindVertexArray(vao);
GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof idx, idx, GL_STATIC_DRAW);

glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void *)0);
printf("drew %d indices, %d vertices stored\n", 6, 4);
Text
drew 6 indices, 4 vertices stored

The element buffer binding is part of the VAO state, so bind the VAO first or the binding is lost with it. The last argument of glDrawElements is a byte offset into that buffer, not a pointer to client memory in the core profile, as the glDrawElements page says. Use GL_UNSIGNED_SHORT when you have under 65,536 vertices to halve the index size.

Duplicated vertices are still needed when a corner has different normals or texture coordinates per face, as on a cube.

Taggedcopengl
Share

More snippets

Get new posts by email

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

Unsubscribe in one click. No spam, ever.