1 # ##### BEGIN GPL LICENSE BLOCK #####
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software Foundation,
15 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # ##### END GPL LICENSE BLOCK #####
22 Import and export STL files
24 Used as a blender script, it load all the stl files in the scene:
26 blender --python stl_utils.py -- file1.stl file2.stl file3.stl ...
33 from mathutils
.geometry
import normal
39 Set struct with order.
42 - insert data into without doubles
43 - get the list of data in insertion order with self.list
45 Like collections.OrderedDict, but quicker, can be replaced if
56 Add a value to the Set, return its position in it.
58 value
= self
.setdefault(item
, self
._len
)
59 if value
== self
._len
:
60 self
.list.append(item
)
66 # an stl binary file is
67 # - 80 bytes of description
68 # - 4 bytes of size (unsigned int)
71 # - 12 bytes of normal
72 # - 9 * 4 bytes of coordinate (3*3 floats)
73 # - 2 bytes of garbage (usually 0)
75 BINARY_STRIDE
= 12 * 4 + 2
78 def _header_version():
80 return "Exported from Blender-" + bpy
.app
.version_string
83 def _is_ascii_file(data
):
85 This function returns True if the data represents an ASCII file.
87 Please note that a False value does not necessary means that the data
88 represents a binary file. It can be a (very *RARE* in real life, but
89 can easily be forged) ascii file.
92 data
.seek(BINARY_HEADER
)
93 size
= struct
.unpack('<I', data
.read(4))[0]
94 # Use seek() method to get size of the file.
95 data
.seek(0, os
.SEEK_END
)
96 file_size
= data
.tell()
97 # Reset to the start of the file.
100 if size
== 0: # Odds to get that result from an ASCII file are null...
101 print("WARNING! Reported size (facet number) is 0, assuming invalid binary STL file.")
102 return False # Assume binary in this case.
104 return (file_size
!= BINARY_HEADER
+ 4 + BINARY_STRIDE
* size
)
107 def _binary_read(data
):
109 data
.seek(BINARY_HEADER
)
110 size
= struct
.unpack('<I', data
.read(4))[0]
113 # Workaround invalid crap.
114 data
.seek(0, os
.SEEK_END
)
115 file_size
= data
.tell()
116 # Reset to after-the-size in the file.
117 data
.seek(BINARY_HEADER
+ 4)
119 file_size
-= BINARY_HEADER
+ 4
120 size
= file_size
// BINARY_STRIDE
121 print("WARNING! Reported size (facet number) is 0, inferring %d facets from file size." % size
)
123 # We read 4096 elements at once, avoids too much calls to read()!
125 chunks
= [CHUNK_LEN
] * (size
// CHUNK_LEN
)
126 chunks
.append(size
% CHUNK_LEN
)
128 unpack
= struct
.Struct('<12f').unpack_from
129 for chunk_len
in chunks
:
132 buf
= data
.read(BINARY_STRIDE
* chunk_len
)
133 for i
in range(chunk_len
):
134 # read the normal and points coordinates of each triangle
135 pt
= unpack(buf
, BINARY_STRIDE
* i
)
136 yield pt
[:3], (pt
[3:6], pt
[6:9], pt
[9:])
139 def _ascii_read(data
):
140 # an stl ascii file is like
141 # HEADER: solid some name
159 if l
.startswith(b
'facet'):
160 curr_nor
= tuple(map(float, l
.split()[2:]))
161 # if we encounter a vertex, read next 2
162 if l
.startswith(b
'vertex'):
163 yield curr_nor
, [tuple(map(float, l_item
.split()[1:])) for l_item
in (l
, data
.readline(), data
.readline())]
166 def _binary_write(filepath
, faces
):
167 with
open(filepath
, 'wb') as data
:
170 # we write padding at header beginning to avoid to
171 # call len(list(faces)) which may be expensive
172 fw(struct
.calcsize('<80sI') * b
'\0')
175 pack
= struct
.Struct('<9f').pack
177 # number of vertices written
181 # calculate face normal
182 # write normal + vertexes + pad as attributes
183 fw(struct
.pack('<3f', *normal(*face
)) + pack(*itertools
.chain
.from_iterable(face
)))
184 # attribute byte count (unused)
188 # header, with correct value now
190 fw(struct
.pack('<80sI', _header_version().encode('ascii'), nb
))
193 def _ascii_write(filepath
, faces
):
194 with
open(filepath
, 'w') as data
:
196 header
= _header_version()
197 fw('solid %s\n' % header
)
200 # calculate face normal
201 fw('facet normal %f %f %f\nouter loop\n' % normal(*face
)[:])
203 fw('vertex %f %f %f\n' % vert
[:])
204 fw('endloop\nendfacet\n')
206 fw('endsolid %s\n' % header
)
209 def write_stl(filepath
="",
214 Write a stl file from faces,
220 iterable of tuple of 3 vertex, vertex is tuple of 3 coordinates as float
223 save the file in ascii format (very huge)
225 (_ascii_write
if ascii
else _binary_write
)(filepath
, faces
)
228 def read_stl(filepath
):
230 Return the triangles and points of an stl binary file.
232 Please note that this process can take lot of time if the file is
233 huge (~1m30 for a 1 Go stl file on an quad core i7).
235 - returns a tuple(triangles, triangles' normals, points).
238 A list of triangles, each triangle as a tuple of 3 index of
242 A list of vectors3 (tuples, xyz).
245 An indexed list of points, each point is a tuple of 3 float
250 >>> tris, tri_nors, pts = read_stl(filepath)
253 >>> # print the coordinate of the triangle n
254 >>> print(pts[i] for i in tris[n])
257 start_time
= time
.process_time()
259 tris
, tri_nors
, pts
= [], [], ListDict()
261 with
open(filepath
, 'rb') as data
:
262 # check for ascii or binary
263 gen
= _ascii_read
if _is_ascii_file(data
) else _binary_read
265 for nor
, pt
in gen(data
):
266 # Add the triangle and the point.
267 # If the point is allready in the list of points, the
268 # index returned by pts.add() will be the one from the
269 # first equal point inserted.
270 tris
.append([pts
.add(p
) for p
in pt
])
273 print('Import finished in %.4f sec.' % (time
.process_time() - start_time
))
275 return tris
, tri_nors
, pts
.list
278 if __name__
== '__main__':
281 from io_mesh_stl
import blender_utils
283 filepaths
= sys
.argv
[sys
.argv
.index('--') + 1:]
285 for filepath
in filepaths
:
286 objName
= bpy
.path
.display_name(filepath
)
287 tris
, pts
= read_stl(filepath
)
289 blender_utils
.create_and_link_mesh(objName
, tris
, pts
)