Read and Write VertexBuffer Data With Arrays

This example demonstrates how to use arrays to fill and retrieve data from a VertexBuffer and IndexBuffer objects.

[C#]

In the following C# code example, a VertexBuffer object is created using a flexible vertex format (FVF) type defined by the PositionNormalTexVertex structure. The first part of the code sample shows the use of Lock to lock an arbitrary number of vertices and fill them with data. The second part shows how to lock an entire VertexBuffer for reading and retrieving data from the array. A similar procedure can be used to write to and read from nearly all Microsoft Direct3D resource types.

Using ArraysLeave Site is not the most efficient method for filling and reading from Direct3D resources; it requires extra memory and cycles to copy the unmanaged resources into managed arrays. However, it makes for very readable code with no unsafe access.

using System;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

public struct PositionNormalTexVertex
{
	public Vector3 Position;
	public Vector3 Normal;
	public float Tu0, Tv0;
	public static readonly VertexFormats FVF = VertexFormats.Position | VertexFormats.Texture1;
}

public class Example
{
	public void ArrayBasedReadWrite()
	{
		//Create a vertex buffer in the managed pool
		VertexBuffer vb = new VertexBuffer(typeof(PositionNormalTexVertex), 100, device, Usage.None, PositionNormalTex1Vertex.FVF, Pool.Managed);

		//Fill an array of the appropriate type with the VB data using Lock()
		PositionNormalTexVertex[] vbData = (PositionNormalTexVertex[]) vb.Lock(0, typeof(PositionNormalTexVertex), LockFlags.None, 50);
		for(int i=0; i<50; i++)
		{
			//set your vertices to something...
			vbData[i].Position = new Vector3(2f,2f,2f);  
			vbData[i].Normal = new Vector3(1f,0f,0f);
			vbData[i].Tu0 = i;
			vbData[i].Tv0 = i;
		}
		//Unlock the vb before you can use it elsewhere
		vb.Unlock();

		//This lock overload simply locks the entire VB -- setting ReadOnly can improve perf when reading a vertexbuffer
		vbData = (PositionNormalTexVertex[]) vb.Lock(0, LockFlags.ReadOnly);
		for(int i=0; i<100; i++)
		{
			//read some vertex data
			Console.WriteLine("Vertex " + i + "Tu: " +  vbData[i].Tu0 + " , Tv: " + vbData[i].Tv0);
		}

		//Unlock the buffer
		vb.Unlock();


		vb.Dispose();
	}
}

Related Topics

Show:
© 2014 Microsoft