How to use glVertexPointer correctly.

Hi guys,

I’m trying to get the following data structure to work with glVertexPointer and subsequently glDrawArrays:


struct Vertex
{
   float x, y, z, w, nx, ny, nz, tx, ty;
}

typedef std::vector<Vertex> Face;
typedef std::vector<Face> Mesh;

So if I create a cube object, it’s Mesh will have 6 vectors, and those 6 vectors will have 4 Vertex’s each.

If I make the following calls, I get a single face the way I’d expect:

glVertexPointer(4, GL_FLOAT, sizeof(Vertex), &mesh[0][0];
glDrawArrays(GL_QUADS, 0, 4);

However subsequent calls to glDrawArrays with different first values don’t give me the other faces, instead I get garbage like random polygons to random points in the screen.

I’ve tried a heap of different values for first, like 1 through to 10, and none of them work. I’m sure the problem is that I don’t understand glVertexPointer properly. Any help would be greatly appreciated.

A std::vector<T> manages a contiguous array of data (somewhere on the heap). However that does not mean that all the Faces of your Mesh are contiguous as well, each of them is allocated somewhere on the heap, only the pointers to that memory (which is what std::vector stores internally) are contiguous in your Mesh.

Try this:


Mesh::const_iterator faceIt(mesh.begin());
Mesh::const_iterator faceEnd(mesh.end());

for(; faceIt != faceEnd; ++faceIt)
{
    std::cout << "Address of first vertex: "
              << &(faceIt->front())
              << std::endl;
}

you will see that the addresses are not in increasing order with a fixed distance between them.

You will have to keep all your vertices in one big array and keep information about which belong to a face separate. On the upside that will mean you can draw a whole mesh with a single draw call.

Awesome, thanks heaps for that. I understand that a vector of vectors of Vertex is bad, I’d been wondering about that for a while.

Just to be clear though, would a vector of Vertex not be correct either? Because I was taught to use vectors of Vertex, and it was working until I made it a vector of vectors.

Edit: Nevermind! I used it with a vector of Vertex and it’s working perfectly now.