]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/export_mesh.py
Small optimization for mesh exporter performance
[libs/gl.git] / blender / io_mspgl / export_mesh.py
1 import itertools
2 import bpy
3 import mathutils
4
5 class VertexCache:
6         def __init__(self, size):
7                 self.size = size
8                 self.slots = [-1]*self.size
9
10         def fetch(self, v):
11                 hit = v.index in self.slots
12                 if hit:
13                         self.slots.remove(v.index)
14                 self.slots.append(v.index)
15                 if not hit:
16                         del self.slots[0]
17                 return hit
18
19         def fetch_strip(self, strip):
20                 hits = 0
21                 for v in strip:
22                         if self.fetch(v):
23                                 hits += 1
24                 return hits
25
26         def test_strip(self, strip):
27                 hits = 0
28                 for i in range(len(strip)):
29                         if i>=self.size:
30                                 break
31                         if strip[i].index in self.slots[i:]:
32                                 hits += 1
33                 return hits
34
35
36 class MeshExporter:
37         def __init__(self):
38                 self.show_progress = True
39                 self.use_strips = True
40                 self.use_degen_tris = False
41                 self.max_strip_len = 1024
42                 self.optimize_cache = True
43                 self.cache_size = 64
44                 self.export_lines = False
45                 self.export_uv = "UNIT0"
46                 self.tbn_vecs = False
47                 self.tbn_uvtex = ""
48                 self.compound = False
49                 self.material_tex = False
50                 self.smoothing = "MSPGL"
51                 self.export_groups = False
52                 self.max_groups = 2
53
54         def stripify(self, mesh, progress=None):
55                 for f in mesh.faces:
56                         f.flag = False
57
58                 faces_done = 0
59                 strips = []
60                 loose = []
61
62                 cache = None
63                 if self.optimize_cache:
64                         cache = VertexCache(self.cache_size)
65
66                 island = []
67                 face_neighbors = []
68                 island_strips = []
69                 while 1:
70                         if not island:
71                                 # No current island; find any unused face to start from
72                                 queue = []
73                                 for f in mesh.faces:
74                                         if not f.flag:
75                                                 f.flag = True
76                                                 queue.append(f)
77                                                 break
78
79                                 if not queue:
80                                         break
81
82                                 # Find all faces connected to the first one
83                                 while queue:
84                                         face = queue.pop(0)
85                                         island.append(face)
86
87                                         for n in face.get_neighbors():
88                                                 if not n.flag:
89                                                         n.flag = True
90                                                         queue.append(n)
91
92                                 face_neighbors = [f.get_neighbors() for f in island]
93
94                                 # Unflag the island for the next phase
95                                 for f in island:
96                                         f.flag = False
97
98                         # Find an unused face with as few unused neighbors as possible, but
99                         # at least one.  This heuristic gives a preference to faces in corners
100                         # or along borders of a non-closed island.
101                         best = 5
102                         face = None
103                         for i, f in enumerate(island):
104                                 if f.flag:
105                                         continue
106
107                                 score = sum(not n.flag for n in face_neighbors[i])
108                                 if score>0 and score<best:
109                                         face = f
110                                         best = score
111
112                         if face:
113                                 # Create a strip starting from the face.  This will flag the faces.
114                                 strip = mesh.create_strip(face, self.max_strip_len)
115                                 if strip:
116                                         island_strips.append(strip)
117                                 else:
118                                         face.flag = True
119                         else:
120                                 # Couldn't find a candidate face for starting a strip, so we're
121                                 # done with this island
122                                 while island_strips:
123                                         best = 0
124                                         if cache:
125                                                 # Find the strip that benefits the most from the current
126                                                 # contents of the vertex cache
127                                                 best_hits = 0
128                                                 for i in range(len(island_strips)):
129                                                         hits = cache.test_strip(island_strips[i])
130                                                         if hits>best_hits:
131                                                                 best = i
132                                                                 best_hits = hits
133
134                                         strip = island_strips.pop(best)
135                                         strips.append(strip)
136
137                                         if cache:
138                                                 cache.fetch_strip(strip)
139
140                                 faces_done += len(island)
141                                 if progress:
142                                         progress.set_progress(float(faces_done)/len(mesh.faces))
143
144                                 # Collect any faces that weren't used in strips
145                                 loose += [f for f in island if not f.flag]
146                                 for f in island:
147                                         f.flag = True
148
149                                 island = []
150                                 island_strips = []
151
152                 if cache:
153                         cache = VertexCache(self.cache_size)
154                         total_hits = 0
155
156                 if self.use_degen_tris and strips:
157                         big_strip = []
158
159                         for s in strips:
160                                 if big_strip:
161                                         # Generate glue elements, ensuring that the next strip begins at
162                                         # an even position
163                                         glue = [big_strip[-1], s[0]]
164                                         if len(big_strip)%2:
165                                                 glue += [s[0]]
166
167                                         big_strip += glue
168                                         if cache:
169                                                 total_hits += cache.fetch_strip(glue)
170
171                                 big_strip += s
172                                 if cache:
173                                         total_hits += cache.fetch_strip(s)
174
175                         for f in loose:
176                                 # Add loose faces to the end.  This wastes space, using five
177                                 # elements per triangle and six elements per quad.
178                                 if len(big_strip)%2:
179                                         order = (-1, -2, 0, 1)
180                                 else:
181                                         order = (0, 1, -1, -2)
182                                 vertices = [f.vertices[i] for i in order[:len(f.vertices)]]
183
184                                 if big_strip:
185                                         glue = [big_strip[-1], vertices[0]]
186                                         big_strip += glue
187                                         if cache:
188                                                 total_hits += cache.fetch_strip(glue)
189
190                                 big_strip += vertices
191                                 if cache:
192                                         total_hits += cache.fetch_strip(vertices)
193
194                         strips = [big_strip]
195                         loose = []
196
197                 return strips, loose
198
199         def export(self, context, out_file, objs=None, progress=None):
200                 if objs:
201                         objs = [(o, mathutils.Matrix()) for o in objs]
202
203                 if self.compound:
204                         if objs is None:
205                                 objs = [(o, mathutils.Matrix()) for o in context.selected_objects]
206                         check = objs
207                         while check:
208                                 children = []
209                                 for o, m in check:
210                                         for c in o.children:
211                                                 if c.compound:
212                                                         children.append((c, m*c.matrix_local))
213                                 objs += children
214                                 check = children
215                 elif objs is None:
216                         objs = [(context.active_object, mathutils.Matrix())]
217
218                 if not objs:
219                         raise Exception("Nothing to export")
220                 for o, m in objs:
221                         if o.type!="MESH":
222                                 raise Exception("Can only export Mesh data")
223
224                 from .mesh import Mesh
225                 from .util import Progress
226
227                 if self.show_progress:
228                         if not progress:
229                                 progress = Progress(context)
230                         progress.set_task("Preparing", 0.0, 0.0)
231                 else:
232                         progress = None
233
234                 mesh = None
235                 bmeshes = []
236                 winding_test = False
237                 for o, m in objs:
238                         if o.data.winding_test:
239                                 winding_test = True
240                         bmesh = o.to_mesh(context.scene, True, "PREVIEW")
241                         bmeshes.append(bmesh)
242                         me = Mesh(bmesh)
243                         me.transform(m)
244                         if not mesh:
245                                 mesh = me
246                         else:
247                                 mesh.splice(me)
248
249                 if progress:
250                         progress.set_task("Smoothing", 0.05, 0.35)
251                 if self.smoothing=="NONE":
252                         mesh.flatten_faces()
253                 mesh.split_smooth(progress)
254
255                 if self.smoothing!="BLENDER":
256                         mesh.compute_normals()
257
258                 if self.export_groups:
259                         mesh.sort_vertex_groups(self.max_groups)
260
261                         # Create a mapping from vertex group indices to bone indices
262                         first_obj = objs[0][0]
263                         group_index_map = dict((i, i) for i in range(len(first_obj.vertex_groups)))
264                         if first_obj.parent and first_obj.parent.type=="ARMATURE":
265                                 armature = first_obj.parent.data
266                                 bone_indices = dict((armature.bones[i].name, i) for i in range(len(armature.bones)))
267                                 for g in first_obj.vertex_groups:
268                                         if g.name in bone_indices:
269                                                 group_index_map[g.index] = bone_indices[g.name]
270
271                 if self.material_tex and mesh.materials:
272                         mesh.generate_material_uv()
273
274                 texunits = []
275                 force_unit0 = False
276                 if mesh.uv_layers and (self.export_uv!="NONE" or self.material_tex):
277                         # Figure out which UV layers to export
278                         if self.export_uv=="ALL":
279                                 texunits = range(len(mesh.uv_layers))
280                         elif self.material_tex:
281                                 # The material UV layer is always the last one
282                                 texunits = [len(mesh.uv_layers)-1]
283                                 force_unit0 = True
284                         else:
285                                 for i, u in enumerate(mesh.uv_layers):
286                                         if u.unit==0:
287                                                 texunits = [i]
288                                                 break
289                         texunits = [(i, mesh.uv_layers[i]) for i in texunits]
290                         texunits = [u for u in texunits if not u[1].hidden]
291
292                         if self.tbn_vecs:
293                                 # TBN coordinates must be generated before vertices are split by any other layer
294                                 uv_names = [u.name for i, u in texunits]
295                                 if self.tbn_uvtex in uv_names:
296                                         tbn_index = uv_names.index(self.tbn_uvtex)
297                                         unit = texunits[tbn_index]
298                                         del texunits[tbn_index]
299                                         texunits.insert(0, unit)
300
301                         for i, u in texunits:
302                                 if progress:
303                                         progress.set_task("Splitting UVs", 0.35+0.3*i/len(texunits), 0.35+0.3*(i+1)/len(texunits))
304                                 mesh.split_uv(i, progress)
305                                 if self.tbn_vecs and u.name==self.tbn_uvtex:
306                                         mesh.compute_uv()
307                                         mesh.compute_tbn(i)
308
309                         mesh.compute_uv()
310
311                 strips = []
312                 loose = mesh.faces
313                 if self.use_strips:
314                         if progress:
315                                 progress.set_task("Creating strips", 0.65, 0.95)
316                         strips, loose = self.stripify(mesh, progress)
317
318                 if progress:
319                         progress.set_task("Writing file", 0.95, 1.0)
320
321                 from .outfile import open_output
322                 out_file = open_output(out_file)
323
324                 fmt = ["NORMAL3"]
325                 if texunits:
326                         for i, u in texunits:
327                                 size = str(len(mesh.vertices[0].uvs[i]))
328                                 if u.unit==0 or force_unit0:
329                                         fmt.append("TEXCOORD"+size)
330                                 else:
331                                         fmt.append("TEXCOORD%s_%d"%(size, u.unit))
332                         if self.tbn_vecs:
333                                 fmt += ["TANGENT3", "BINORMAL3"]
334                 if self.export_groups:
335                         fmt.append("ATTRIB%d_5"%(self.max_groups*2))
336                 fmt.append("VERTEX3")
337                 out_file.begin("vertices", *fmt)
338                 normal = None
339                 uvs = {}
340                 tan = None
341                 bino = None
342                 group = None
343                 for v in mesh.vertices:
344                         if v.normal!=normal:
345                                 out_file.write("normal3", *v.normal)
346                                 normal = v.normal
347                         for i, u in texunits:
348                                 if v.uvs[i]!=uvs.get(i):
349                                         size = str(len(v.uvs[i]))
350                                         if u.unit==0 or force_unit0:
351                                                 out_file.write("texcoord"+size, *v.uvs[i])
352                                         else:
353                                                 out_file.write("multitexcoord"+size, u.unit, *v.uvs[i])
354                                         uvs[i] = v.uvs[i]
355                         if self.tbn_vecs:
356                                 if v.tan!=tan:
357                                         out_file.write("tangent3", *v.tan)
358                                         tan = v.tan
359                                 if v.bino!=bino:
360                                         out_file.write("binormal3", *v.bino)
361                                         bino = v.bino
362                         if self.export_groups:
363                                 group_attr = [(group_index_map[g.group], g.weight*v.group_weight_scale) for g in v.groups[:self.max_groups]]
364                                 while len(group_attr)<self.max_groups:
365                                         group_attr.append((0, 0.0))
366                                 group_attr = list(itertools.chain(*group_attr))
367                                 if group_attr!=group:
368                                         out_file.write("attrib%d"%len(group_attr), 5, *group_attr)
369                                         group = group_attr
370                         out_file.write("vertex3", *v.co)
371                 out_file.end()
372                 for s in strips:
373                         out_file.begin("batch", "TRIANGLE_STRIP")
374                         indices = []
375                         n = 0
376                         for v in s:
377                                 indices.append(v.index)
378                                 if len(indices)>=32:
379                                         out_file.write("indices", *indices)
380                                         indices = []
381                         if indices:
382                                 out_file.write("indices", *indices)
383                         out_file.end()
384
385                 if loose:
386                         out_file.begin("batch", "TRIANGLES")
387                         for f in loose:
388                                 for i in range(2, len(f.vertices)):
389                                         out_file.write("indices", f.vertices[0].index, f.vertices[i-1].index, f.vertices[i].index)
390                         out_file.end()
391
392                 if self.export_lines and mesh.lines:
393                         out_file.begin("batch", "LINES")
394                         for l in mesh.lines:
395                                 out_file.write("indices", l.vertices[0].index, l.vertices[1].index)
396                         out_file.end()
397
398                 if winding_test:
399                         out_file.write("winding", "COUNTERCLOCKWISE")
400
401                 if progress:
402                         progress.set_task("Done", 1.0, 1.0)
403
404                 for m in bmeshes:
405                         bpy.data.meshes.remove(m)
406
407                 return mesh