Having trouble Rendering Meshes created "by hand".

I was hoping someone could give the following code a quick look. I was looking at this all night and cannot see a problem. I build a Mesh using the following code:

int numberVerts = 4;

short[] indices = {

0,1,2, // Front Face

1,3,2 // Front Face

};

mesh = new Mesh(numberVerts * 3, 4, MeshFlags.Managed, CustomVertex.PositionNormal.Format, Device);

using (VertexBuffer vb = mesh.VertexBuffer)

{

GraphicsStream data = vb.Lock(0, 0, LockFlags.None);

data.Write(new CustomVertex.PositionNormal(-1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f));

data.Write(new CustomVertex.PositionNormal(-1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f));

data.Write(new CustomVertex.PositionNormal(1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f));

data.Write(new CustomVertex.PositionNormal(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f));

vb.Unlock();

}

using (IndexBuffer ib = mesh.IndexBuffer)

{

ib.SetData(indices, 0, LockFlags.None);

}

I then render with the following code:

Device.Transform.World = Matrix.Identity;

Device.Material = mat;

Device.VertexFormat = CustomVertex.PositionNormal.Format;

mesh.DrawSubset(0);



Answer this question

Having trouble Rendering Meshes created "by hand".

  • Tim Raleigh

    Don’t use “using“ with buffers from a mesh. I know it is in the documentation but the sample there is wrong. The reason is that a using block will call Dispose at the end. This will destroy the buffers in the mesh.

    This should work better:

    VertexBuffer vb = mesh.VertexBuffer;

    GraphicsStream data = vb.Lock(0, 0, LockFlags.None);

    data.Write(new CustomVertex.PositionNormal(-1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f));

    data.Write(new CustomVertex.PositionNormal(-1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f));

    data.Write(new CustomVertex.PositionNormal(1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f));

    data.Write(new CustomVertex.PositionNormal(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f));

    vb.Unlock();

    IndexBuffer ib = mesh.IndexBuffer;

    ib.SetData(indices, 0, LockFlags.None);



  • Vinay Ahuja

    This makes sense, and I really thought this would fix the problem, but it doesn't. I will have to look at the code more. The problem must be coming from somewhere else.
  • Having trouble Rendering Meshes created "by hand".