Dynamic Vertex Buffers in XNA
Geometry in a 3D game ultimately is defined as a set of vertices. Commonly, a game either needs to modify the position of one or more existing vertices or generate the vertices at run time. Because the graphics device can access these buffers at any time, take care when you modify existing vertex buffers and render the resulting geometry defined by these buffers. The following sections discuss several techniques you can implement in your game.
Updating a Set of Primitives Dynamically
You can use the DrawUserPrimitives method as the basis for rendering a set of primitives that are generated dynamically each frame. The Primitives Sample, located on the XNA Creators Club Online Web site, implements an abstraction layer around this method similar to the SpriteBatch class.
The sample renders primitives by first calling
Begin, adding the necessary vertices, using the
Add method, and then calling
End. This forces the buffer to be drawn to the current device. The
Flush method calls DrawUserPrimitives method when
End is called or when the buffer has no room for new vertices. If there is no room, the buffer is written to the device, it is reset, and the pending vertices are added.
For a complete code listing, download the Primitives Sample from the XNA Creators Club Online Web site.
Dynamically Rendering a Persistent Set of Primitives
The Particle 3D Sample, located on the XNA Creators Club Online Web site, implements a dynamic vertex buffer that contains custom vertices with a limited lifespan. The application adds particles and removes them to a fixed length buffer. The custom shader of the sample renders the active subset of vertices dynamically.
Because particles have a limited lifespan, the sample code must manage the vertex buffer in real time. The
ParticleSystem class handles all adding, updating, and deleting.
Generating Geometry Programmatically
Sometimes, geometry to be rendered either is not known at design-time or it changes based on events during run time.
To generate geometry
Create a vertex buffer to store the vertices of the geometry to be generated.
Create an index buffer that stores the indices used to render the geometry represented by the vertex buffer.
In the method that renders your frame (the Draw method for a default XNA game project), set the vertex stream and index data of the current graphics device.
For a specific example of this, see DrawIndexedPrimitives.
For a more advanced solution for this problem, download the Generated Geometry Sample from the XNA Creators Club Online Web site. This sample uses the MeshBuilder helper class and a custom processor to generate a terrain map from a bitmap loaded by the content manager. Specifically, examine the
Process method, located in TerrainProcessor.cs. This method programmatically creates the terrain geometry based on input from the specified bitmap.