Per-vertex position/normal and per-index texture coordinate
- by Boreal
In my game, I have a mesh with a vertex buffer and index buffer up and running. The vertex buffer stores a Vector3 for the position and a Vector2 for the UV coordinate for each vertex. The index buffer is a list of ushorts. It works well, but I want to be able to use 3 discrete texture coordinates per triangle.
I assume I have to create another vertex buffer, but how do I even use it?
Here is my vertex/index buffer creation code:
// vertices is a Vertex[]
// indices is a ushort[]
// VertexDefs stores the vertex size (sizeof(float) * 5)
// vertex data
numVertices = vertices.Length;
DataStream data = new DataStream(VertexDefs.size * numVertices, true, true);
data.WriteRange<Vertex>(vertices);
data.Position = 0;
// vertex buffer parameters
BufferDescription vbDesc = new BufferDescription()
{
BindFlags = BindFlags.VertexBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
SizeInBytes = VertexDefs.size * numVertices,
StructureByteStride = VertexDefs.size,
Usage = ResourceUsage.Default
};
// create vertex buffer
vertexBuffer = new Buffer(Graphics.device, data, vbDesc);
vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexDefs.size, 0);
data.Dispose();
// index data
numIndices = indices.Length;
data = new DataStream(sizeof(ushort) * numIndices, true, true);
data.WriteRange<ushort>(indices);
data.Position = 0;
// index buffer parameters
BufferDescription ibDesc = new BufferDescription()
{
BindFlags = BindFlags.IndexBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
SizeInBytes = sizeof(ushort) * numIndices,
StructureByteStride = sizeof(ushort),
Usage = ResourceUsage.Default
};
// create index buffer
indexBuffer = new Buffer(Graphics.device, data, ibDesc);
data.Dispose();
Engine.Log(MessageType.Success, string.Format("Mesh created with {0} vertices and {1} indices", numVertices, numIndices));
And my drawing code:
// ShaderEffect, ShaderTechnique, and ShaderPass all store effect data
// e is of type ShaderEffect
// get the technique
ShaderTechnique t;
if(!e.techniques.TryGetValue(techniqueName, out t))
return;
// effect variables
e.SetMatrix("worldView", worldView);
e.SetMatrix("projection", projection);
e.SetResource("diffuseMap", texture);
e.SetSampler("textureSampler", sampler);
// set per-mesh/technique settings
Graphics.context.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
Graphics.context.InputAssembler.SetIndexBuffer(indexBuffer, SlimDX.DXGI.Format.R16_UInt, 0);
Graphics.context.PixelShader.SetSampler(sampler, 0);
// render for each pass
foreach(ShaderPass p in t.passes)
{
Graphics.context.InputAssembler.InputLayout = p.layout;
p.pass.Apply(Graphics.context);
Graphics.context.DrawIndexed(numIndices, 0, 0);
}
How can I do this?