Problem with glDrawElements when using indices

Started by
3 comments, last by GlassBil 14 years, 2 months ago
Hi, I have the following data structure of my heightmap: GLfloat **vertices; // Vertices GLuint *indices; // Vertex indices bool mesh; // Mesh ON/OFF GLfloat **normals; // Triangle normals int sizeX; // Terrain "width" (in pixels) int sizeZ; // Terrain "height" (in pixels) int numTriangles; // Number of triangles vertices is [sizeX*sizeZ][3], where sizeX*sizeZ is the area of my heightmap. normals are stored like [numTriangles][3] where numTriangles is (sizeX - 1)*(sizeZ - 1)*2. It all works fine when I draw it like this: for(int i = 0, n = 0; i < 3 * numTriangles; i = i + 3, n++) { if(mesh) { glBegin(GL_LINE_STRIP); } else { glBegin(GL_TRIANGLES); } glNormal3fv(normals[n]); glVertex3fv(vertices[indices]); glVertex3fv(vertices[indices[i+1]]); glVertex3fv(vertices[indices[i+2]]); glEnd(); } However, I want to draw it with glDrawElements. I use the following code and it doesn't work: glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glVertexPointer(3, GL_FLOAT, 0, vertices); glNormalPointer(GL_FLOAT, 0, normals); if(mesh) { glDrawElements(GL_LINE_STRIP, 3 * numTriangles, GL_UNSIGNED_INT, indices); } else { glDrawElements(GL_TRIANGLES, 3 * numTriangles, GL_UNSIGNED_INT, indices); } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); Any idea what I'm doing wrong? I've been searching the web and I've noticed that most people store the vertices in a 1D array instead of a 2D array. Do I have to do that to make it work? A 2D array feels more intuitive. :) //GlassBil
Advertisement
You can store your vertices in a 2D-array if you want, but that's not what you're doing. You're storing them in an array of pointers to vertices, which is an entirely different layout in memory and is not compatible with OpenGL's vertex arrays. The pointer passed to OpenGL is assumed to point to the vertex data, but instead you point to pointers to vertex data.

If you want to store them in a dynamic 2D-array, make an array of arrays, not an array of pointers.
GLfloat (*vertices)[3];GLfloat (*normals)[3];...vertices = new vertices[numVertices][3];normals = new vertices[numnormals][3];

These arrays are compatible with OpenGL, because they point an array of vertices, not to an array of pointers to vertices.
Thanks alot! That helped. I have one issue still though.

I believe it's the normals that are the issue. Do I have to store one normal for every vertex, or one normal for every triangle when using DrawElements? (As in, does DrawElement use indices to look up the normals?)
One normal for each vertex, and the same applies for any enabled array as well. The same index is used to look up every enabled attribute array.
Thank you! Now it looks great :)

This topic is closed to new replies.

Advertisement