How To Use - glDrawElements()

I’ve found a lot of documentation but I’ve yet to locate a simple working example of glDrawElements. The OpenGL programmer’s guide provides an obscure pseudo example but it doesn’t explain how the vertex data is stored in the array.

Could someone show me a version of glDrawElements() drawing a simple primative?

Here’s a simple example that draws a quad with per vertex position, color, and texcoords.

struct Vertex
{
	float pos[3];
	float color[4];
	float st[2];
} quadVerts[4] = {
	{{0,0,0}    ,{1,0,0,1}, {0,0}},
	{{0,100,0}  ,{0,1,0,1}, {0,1}},
	{{100,100,0},{0,0,1,1},	{1,1}},
	{{100,0,0}  ,{1,1,1,1},	{1,0}}
};
GLushort quadIndices[4] = { 0, 1, 2, 3 };
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), quadVerts[0].pos);
glEnableClientState(GL_VERTEX_ARRAY);
glColorPointer(4, GL_FLOAT, sizeof(Vertex), quadVerts[0].color);
glEnableClientState(GL_COLOR_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), quadVerts[0].st);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_SHORT, quadIndices);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

That’s exactly what what I was looking for. Thank you.

My pleasure. If you want to use multiple texcoords per vertex, you’ll probably need to grab the extension header(s). Really the only difference is that you need to activate the texture you want (using glClientActiveTexture) before you call glTexCoordPointer/glEnableClientState/glDisableClientState. This can trip you up if you’re not careful (I know from personal experience in this area :-/).

You can find all the extension stuff you may need here. Grab glext.h and wglext.h for Windows.
http://oss.sgi.com/projects/ogl-sample/registry/