Skip to content

Instantly share code, notes, and snippets.

@jl2
Created April 19, 2012 00:02
Show Gist options
  • Save jl2/2417462 to your computer and use it in GitHub Desktop.
Save jl2/2417462 to your computer and use it in GitHub Desktop.
Simple code to generate a binary .STL file
#!/usr/bin/env python3
import sys
import struct
import math
class Vertex:
def __init__(self, x,y,z):
self.val = [x,y,z]
def to_stl(self):
return struct.pack('fff',self.val[0],self.val[1],self.val[2])
class Triangle:
def __init__(self, v1,v2,v3, n1):
self.verts = [v1,v2,v3]
self.norms = n1
def to_stl(self):
return self.norms.to_stl() + self.verts[0].to_stl() + self.verts[1].to_stl() + self.verts[2].to_stl() + struct.pack('H', 0)
class STL_File:
def __init__(self, msg=None):
self.tris = []
if msg is None:
self.header = (80*' ').encode('utf-8')
else:
if len(msg)>80:
self.header=msg[0:80].encode('utf-8')
else:
self.header = (msg + (80-len(msg))*' ').encode('utf-8')
def add_tri(self, tri):
self.tris.append(tri)
def to_stl(self):
rval = self.header
rval += struct.pack('I', len(self.tris))
for t in self.tris:
rval += t.to_stl()
return rval
def main(args):
verts = [Vertex(0,0,0),
Vertex(1,0,0),
Vertex(0,1,0),
Vertex(0,0,1),
]
norms = [Vertex(0,0,-1),
Vertex(0,-1,0),
Vertex(-1,0,0),
Vertex(1/math.sqrt(3),1/math.sqrt(3),1/math.sqrt(3)),
]
tris = [Triangle(verts[0],verts[1],verts[2], norms[0]),
Triangle(verts[0],verts[1],verts[3], norms[1]),
Triangle(verts[0],verts[2],verts[3], norms[2]),
Triangle(verts[1],verts[2],verts[3], norms[3]),
]
bob = STL_File()
bob.add_tri(tris[0])
bob.add_tri(tris[1])
bob.add_tri(tris[2])
bob.add_tri(tris[3])
with open(args[0], 'wb') as outf:
outf.write(bob.to_stl())
# print(bob.to_stl(), file=outf)
if __name__=='__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment