Indexed Triangles (d3d3.cpp)In the above code, you told DirectX to draw straight from the vertex array. The main issues with this are size and, indirectly, speed. Take a cube for example. A cube has eight vertices. Using the above code, you would need to draw 12 triangles, each with three vertices, for a total of 36 vertices in your vertex array. This is more than four times the number of vertices in the cube itself! It would be better if you could just list each vertex once and index into this array. This way, you only have to transform eight vertices instead of 36. As it turns out, you can do this. First you set up an index buffer. This is the list of indices into the vertex array.
The variable indices is defined as: WORD indices[] = { 0, 1, 2 }; CreateIndexBuffer is similar to your CreateVertexBuffer call above. First you pass the size of the buffer in bytes. Other flags are the same as before; D3DUSAGE_WRITEONLY because you only write to the buffer, D3DPOOL_DEFAULT to use the default memory configuration, and a pointer to receive the interface. D3DFMT_INDEX16 is the only new flag. This simply specifies the size of each element in the buffer. Since indices is defined as WORDs and since a WORD is 16 bits in Windows, you pass D3DFMT_INDEX16. You could pass D3DFMT_INDEX32, but a cube does not need that many indices. Next you fill in this buffer, just as you did with the vertex buffers:
You lock the buffer, copy the elements into the buffer, and unlock it. This is the same as before. The second parameter to Lock is supposed to be the count of bytes to lock, but sending 0 (which is undocumented) locks the whole buffer. Now you set this buffer as our index buffer, and then you can draw: pID3DDevice->SetIndices(pIndexBuffer, 0); In your DrawScene function, you can get rid of the DrawPrimitive method in exchange for a DrawIndexedPrimitive method:
You are still drawing a triangle list as before. You also pass the minimum vertex index used (zero in this case), the number of indices used (three), the index number to start on (zero), and the number of triangles to render (one). If all goes well, this program should produce the exact same output as the last one. It’s a bit more work, but it is also more scalable. |
|||||||||||