CMZTECH.NET
  • Blog
  • Graphics
  • Virtual Reality
  • 3D Printing
  • Fun Stuff
  • Contact
Picture

Reading and Writing STL files

Picture
The STL file format is very simple.  You can read about it on wikipedia by clicking here.
Basically the file consists of a header which includes the triangle count and then a list of triangles.  Each triangle has 3 vertices and a face normal.   This makes loading and saving the files very simple.


Reading an STL file

Here is a code snippet that loads an STL file.  Saving a file is essentially the same but in reverse.  Hard to imagine anything much simpler.  Many 3D packages can read and write STL files.

//=======================================================================
typedef struct _STLFACET
{
float norm[3];
float ver1[3];
float ver2[3];
float ver3[3];
UINT16 att; //unused attribute byte count
}STLFACET;



fread(&header,sizeof(char),80,pFile);
fread(&numfacet,sizeof(int),1,pFile);

mFaceCount = numfacet;
mData = new STLFACET[mFaceCount];

for(unsigned int i=0; i<mFaceCount; i++)
{
   fread(&mData[i].norm,sizeof(float),3,pFile);
   fread(&mData[i].ver1,sizeof(float),3,pFile);
   fread(&mData[i].ver2,sizeof(float),3,pFile);
   fread(&mData[i].ver3,sizeof(float),3,pFile);
   fread(&mData[i].att,sizeof(UINT16),1,pFile);
}/

/=======================================================================