Question

I am trying to create a very basic mesh renderer using D3D11 to use in my final project for school. Although I followed the basic online tutorials like the rastertek site's and Frank De Luna's book to the letter, used the simplest passthrough shader imaginable, etc, I couldn't get my triangles to show up on the screen. Finally I found out about VS 2013's graphics debugging ability, and I was able to see that my vertex and index buffers were filled with garbage data. I've hosted the solution here if you want to run the code, but can someone familiar with D3D and/or its SharpDX C# wrapper tell me what I'm doing wrong in the following code?

This is my geometry data. The Vertex struct has Vector4 position and color fields, and Index is an alias for ushort.

var vertices = new[]
{
    new Vertex(new Vector4(-1, 1, 0, 1), Color.Red),
    new Vertex(new Vector4(1, 1, 0, 1), Color.Green),
    new Vertex(new Vector4(1, -1, 0, 1), Color.Blue),
    new Vertex(new Vector4(-1, -1, 0, 1), Color.White)
};
var indices = new Index[]
{
    0, 2, 1,
    0, 3, 2
};

And here is the code that fails to initialize my vertex and index buffers with the above data.

var vStream = new DataStream(sizeInBytes: vertices.Length * sizeof(Vertex), canRead: false, canWrite: true);
var iStream = new DataStream(sizeInBytes: indices.Length * sizeof(Index), canRead: false, canWrite: true);
{
    vStream.WriteRange(vertices);
    iStream.WriteRange(indices);
    vBuffer = new Buffer(
        device, vStream, new BufferDescription(
            vertices.Length * sizeof(Vertex),
            ResourceUsage.Immutable,
            BindFlags.VertexBuffer,
            CpuAccessFlags.None,
            ResourceOptionFlags.None,
            0)) { DebugName = "Vertex Buffer" };
    iBuffer = new Buffer(
        device, iStream, new BufferDescription(
            indices.Length * sizeof(Index),
            ResourceUsage.Immutable,
            BindFlags.IndexBuffer,
            CpuAccessFlags.None,
            ResourceOptionFlags.None,
            0)) { DebugName = "Index Buffer" };
}

If I replace the above code with the following, however, it works. I have no idea what I'm doing wrong.

vBuffer = Buffer.Create(
    device, vertices, new BufferDescription(
        vertices.Length * sizeof(Vertex),
        ResourceUsage.Immutable,
        BindFlags.VertexBuffer,
        CpuAccessFlags.None,
        ResourceOptionFlags.None,
        0));
vBuffer.DebugName = "Vertex Buffer";
iBuffer = Buffer.Create(
    device, indices, new BufferDescription(
        indices.Length * sizeof(Index),
        ResourceUsage.Immutable,
        BindFlags.IndexBuffer,
        CpuAccessFlags.None,
        ResourceOptionFlags.None,
        0));
iBuffer.DebugName = "Index Buffer";
Was it helpful?

Solution

You need to reset the stream position to zero (like iStream.Position = 0) before passing it to new Buffer(...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top