Vertex & Index Buffers

Introduction

In previous notes we rendered primitives by populating a vertex array and using the array as data to a primitive drawing function. While effective, this approach has drawbacks;

  1. For most surfaces, vertex data will need to be repeated
  2. The winding of triangles in a triangle list alternates between clockwise and anti-clockwise
  3. TheVertex array is loaded to the graphics card each frame

These problems can be easily solved using Vertex and index buffer.

VertexBuffer

The VertexBuffer represent a set of vertices streamed to the graphics card.

// an array of the vertices that have to be drawn
VertexPositionColor[] vertices = new VertexPositionColor[4];

Then replace the declaration of your vertices by the following code (explanation below):
// create our square by setting up the vertices
// because we are using an indexbuffer, we only need 4 vertices instead of 6 (2 triangles)
vertices[0].Position = new Vector3(650, 100, 0);
vertices[0].Color = Color.Red;

vertices[1].Position = new Vector3(750, 200, 0);
vertices[1].Color = Color.Red;

vertices[2].Position = new Vector3(650, 200, 0);
vertices[2].Color = Color.Red;

vertices[3].Position = new Vector3(750, 100, 0);
vertices[3].Color = Color.Red;


vertexbuffer = new VertexBuffer(GraphicsDevice, VertexPositionColor.SizeInBytes * vertices.Length, BufferUsage.WriteOnly);

vertexbuffer.SetData(vertices);

IndexBuffer

IndexBuffer stores a list of indices to a vertexbuffer. The primitive drawing code uses these indices to determine the drawing ordere of the vertices

// set up our indices
// because a square consist of 2 triangles, we need 6 points in our indexbuffer
short[] indices = new short[6];

indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 0;
indices[4] = 3;
indices[5] = 1;

indexbuffer = new IndexBuffer(GraphicsDevice, typeof(short), 6,BufferUsage.WriteOnly);
indexbuffer.SetData(indices);

Drawing Indexed Primitives

These are two method for drawing indexed primitives;

  1. DrawUserIndexedPrimitives. This function draws the indexed primnitives without the vertex or index buffers. See How to: Draw Points, Lines, and Other 3D Primitives for example code.
  2. DrawIndexedPrimitivesThis function is much more efficient, using the vertex and indexbuffers. See Getting started with XNA - Primitives: Introducing the Index Buffer for example code.
            graphics.GraphicsDevice.Vertices[0].SetSource( vertexbuffer, 0,VertexPositionColor.SizeInBytes);

            graphics.GraphicsDevice.Indices = indexbuffer;

            basicEffect.Begin();
            basicEffect.CurrentTechnique.Passes[0].Begin();

            graphics.GraphicsDevice.DrawIndexedPrimitives(PrimitiveTyp.Linelist, 0, 0, points, 0,2);

            // tell basic effect that we're done.
            basicEffect.CurrentTechnique.Passes[0].End();
            basicEffect.End();