Wednesday, 13 October 2010

XNA 4.0 - Binary Model Loader

So i was trying to avoid the standard xna pipeline classes to start porting some features of my "graphic engine" to XNA. The first thing i wanted was to render a model with my custom file format, the C# and the XNA API stood well to the task, allowing me to read a buffers of bytes from filestream and copying it to vertex and index buffer.
 public class CustomModel  
 {  
      int m_Vertices;  
      int m_Triangles;  
   
      byte[] m_VerticeData;  
      byte[] m_TrianglesData;  
   
      GraphicsDevice m_GraphicsDevice;  
      VertexBuffer m_VertexBuffer;  
      IndexBuffer m_IndexBuffer;  
   
      public CustomModel()  
      {  
           m_Vertices = 0;  
           m_Triangles = 0;  
      }  
   
      public void Render()  
      {  
           m_GraphicsDevice.SetVertexBuffer(m_VertexBuffer);  
           m_GraphicsDevice.Indices = m_IndexBuffer;  
           m_GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, m_Vertices, 0, m_Triangles);  
   
           m_GraphicsDevice.SetVertexBuffer(null);  
           m_GraphicsDevice.Indices = null;  
      }  
   
      public void Load(GraphicsDevice graphics, ContentManager manager, string filename)  
      {  
           m_GraphicsDevice = graphics;  
   
           String StageIndexPath = manager.RootDirectory + "\\" + filename;  
   
           StreamReader st = new StreamReader(StageIndexPath);  
           BinaryReader bin = new BinaryReader(st.BaseStream);  
   
           m_Vertices = bin.ReadInt32();  
           m_Triangles = bin.ReadInt32();  
   
           m_VerticeData = new byte[m_Vertices * 32];  
           m_TrianglesData = new byte[m_Triangles * 12];  
   
           bin.Read(m_VerticeData, 0, m_Vertices * 32);  
           bin.Read(m_TrianglesData, 0, m_Triangles * 12);  
   
           bin.Close();  
           st.Close();  
   
           VertexDeclaration vdx = new VertexDeclaration(  
                new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),  
                new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),  
                new VertexElement(24, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0)  
           );  
   
           m_VertexBuffer = new VertexBuffer(m_GraphicsDevice, vdx, m_Vertices, BufferUsage.None);  
           m_IndexBuffer = new IndexBuffer(m_GraphicsDevice, IndexElementSize.ThirtyTwoBits, 3 * m_Triangles, BufferUsage.None);  
   
           m_VertexBuffer.SetData<byte>(m_VerticeData);  
           m_IndexBuffer.SetData<byte>(m_TrianglesData);  
      }  
 }  

No comments: