# How can I render an .stl file in XNA or Monogame?

How should I go about rendering a .stl file as a 3d model in XNA? The .stl file contains a bunch of triangles that add up to a solid mesh. I have already figured out how to read the contained data. The file firstly contains the amount of facets. The file then consists of groups of data that represent the triangles. For each triangle the is a normal and 3 vectors that represent the 3 corners of the triangle.

My question is how I should go about rendering theses triangles in XNA. I guess I have to use a vertex buffer or something but I have almost no experience with 3D at all. Could someone please help?

Here is a tutorial on using vertex and index buffers in XNA; vertex buffers are probably the ideal way to approach this, but if that seems a bit daunting to you right now you could use the simpler DrawUserPrimitives function. A related tutorial outlines that process.

Essentially, you'll want extract the vertex data from the .stl file (the format is described here). The most straightforward way to do this is probably to call File.ReadAllLines and parse the data line-by-line, assuming you are using the ASCII version of .stl (otherwise try File.ReadAllBytes). The File methods may not be available to you if you want to deploy to the 360, though.

You turn each vertex in the .stl file into an appropriate vertex structure in your C# code, write that vertex into a vertex buffer or an array of vertex objects you're going to use DrawUserPrimitives with, and then draw the buffer or call DrawUserPrimitives.

The .stl format doesn't appear to support indexed data, so you don't need to worry about index buffers, although you could in theory look for duplicate vertex data as you load and build an index buffer that way (I wouldn't recommend trying this first though, keep it simple).

• Thanks, this seems like it could definitely work. I just have no idea what to do with the normals, are they important? May 29 '13 at 15:41
• Yes and no. You could certainly ignore them to start off with. However, normals are pretty important to having reasonable-looking lighting, so you'd want to include them eventually. See en.wikipedia.org/wiki/Vertex_normal
– user1430
May 29 '13 at 16:03
• Great answer. I like the way you also included references to to the STL format for people who might not know how to load them. Thanks. May 29 '13 at 23:07
• Why wouldn't you have File methods on the 360? Oct 3 '13 at 3:42
• Because XNA's framework implementation on that platform only provides access to a subset of the .NET framework, and you don't have unrestricted access to the filesystem.
– user1430
Oct 3 '13 at 3:54