]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/mesh.py
Some cleanups to exporter code
[libs/gl.git] / blender / io_mspgl / mesh.py
1 import bpy
2 import math
3 import mathutils
4
5 def make_edge_key(i1, i2):
6         return (min(i1, i2), max(i1, i2))
7
8 class Edge:
9         def __init__(self, edge):
10                 if edge.__class__==Edge:
11                         self._edge = edge._edge
12                         self.smooth = edge.smooth
13                 else:
14                         self._edge = edge
15                         self.smooth = False
16                 if edge:
17                         self.vertices = edge.vertices[:]
18                         self.key = edge.key
19                 else:
20                         self.vertices = []
21                         self.key = None
22                 self.faces = []
23
24         def __getattr__(self, attr):
25                 return getattr(self._edge, attr)
26
27         def check_smooth(self, limit):
28                 if len(self.faces)!=2:
29                         return
30
31                 d = self.faces[0].normal.dot(self.faces[1].normal)
32                 self.smooth = ((d>limit and self.faces[0].use_smooth and self.faces[1].use_smooth) or d>0.99995)
33
34         def other_face(self, f):
35                 if f.index==self.faces[0].index:
36                         if len(self.faces)>=2:
37                                 return self.faces[1]
38                         else:
39                                 return None
40                 else:
41                         return self.faces[0]
42
43         def other_vertex(self, v):
44                 if v.index==self.vertices[0].index:
45                         return self.vertices[1]
46                 else:
47                         return self.vertices[0]
48
49
50 class Vertex:
51         def __init__(self, vertex):
52                 if vertex.__class__==Vertex:
53                         self._vertex = vertex._vertex
54                         self.uvs = vertex.uvs[:]
55                         self.tan = vertex.tan
56                         self.bino = vertex.bino
57                 else:
58                         self._vertex = vertex
59                         self.uvs = []
60                         self.tan = None
61                         self.bino = None
62                 self.index = vertex.index
63                 self.co = vertex.co
64                 self.normal = vertex.normal
65                 self.flag = False
66                 self.edges = []
67                 self.faces = []
68                 self.groups = vertex.groups[:]
69
70         def __getattr__(self, attr):
71                 return getattr(self._vertex, attr)
72
73         def __cmp__(self, other):
74                 if other is None:
75                         return 1
76                 return cmp(self.index, other.index)
77
78
79 class VertexGroup:
80         def __init__(self, group):
81                 self._group = group
82                 self.group = group.group
83                 self.weight = group.weight
84
85         def __getattr__(self, attr):
86                 return getattr(self._group, attr)
87
88
89 class Face:
90         def __init__(self, face):
91                 self._face = face
92                 self.index = face.index
93                 self.edges = []
94                 self.vertices = face.vertices[:]
95                 self.uvs = []
96                 self.flag = False
97
98         def __getattr__(self, attr):
99                 return getattr(self._face, attr)
100
101         def __cmp__(self, other):
102                 if other is None:
103                         return 1
104                 return cmp(self.index, other.index)
105
106         def pivot_vertex(self, v):
107                 n = self.vertices.index(v)
108                 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
109
110         def pivot_vertices(self, *vt):
111                 flags = [(v in vt) for v in self.vertices]
112                 l = len(self.vertices)
113                 for i in range(l):
114                         if flags[i] and not flags[(i+l-1)%l]:
115                                 return self.vertices[i:]+self.vertices[:i]
116
117         def get_edge(self, v1, v2):
118                 key = make_edge_key(v1.index, v2.index)
119                 for e in self.edges:
120                         if e.key==key:
121                                 return e
122                 raise KeyError("No edge %s"%(key,))
123
124         def other_edge(self, e, v):
125                 for d in self.edges:
126                         if d!=e and v in d.vertices:
127                                 return d
128
129         def get_neighbors(self):
130                 neighbors = [e.other_face(self) for e in self.edges]
131                 return list(filter(bool, neighbors))
132
133
134 class Line:
135         def __init__(self, e):
136                 self.edge = e
137                 self.vertices = e.vertices[:]
138                 self.flag = False
139
140
141 class UvLayer:
142         def __init__(self, arg):
143                 if type(arg)==str:
144                         self._layer = None
145                         self.name = arg
146                         self.uvs = []
147                 else:
148                         self._layer = arg
149                         self.name = arg.name
150                         self.uvs = [d.uv for d in self.data]
151
152                 self.unit = None
153                 self.hidden = False
154
155                 dot = self.name.find('.')
156                 if dot>=0:
157                         ext = self.name[dot:]
158                         if ext.startswith(".unit") and ext[5:].isdigit():
159                                 self.unit = int(ext[5:])
160                         elif ext==".hidden":
161                                 self.hidden = True
162
163         def __getattr__(self, attr):
164                 return getattr(self._layer, attr)
165
166
167 class Mesh:
168         def __init__(self, mesh):
169                 self._mesh = mesh
170
171                 self.winding_test = mesh.winding_test
172                 self.tbn_vecs = mesh.tbn_vecs
173                 self.vertex_groups = mesh.vertex_groups
174
175                 # Clone basic data
176                 self.vertices = [Vertex(v) for v in mesh.vertices]
177                 for v in self.vertices:
178                         v.groups = [VertexGroup(g) for g in v.groups]
179
180                 self.faces = [Face(f) for f in mesh.polygons]
181                 self.edges = [Edge(e) for e in mesh.edges]
182                 self.loops = mesh.loops[:]
183                 self.materials = mesh.materials[:]
184
185                 # Clone only the desired UV layers
186                 if self.use_uv=='NONE' or not mesh.uv_layers:
187                         self.uv_layers = []
188                 else:
189                         self.uv_layers = [UvLayer(u) for u in mesh.uv_layers]
190                         self.uv_layers = sorted([u for u in self.uv_layers if not u.hidden], key=(lambda u: (u.unit or 1000, u.name)))
191
192                         if self.use_uv=='UNIT0':
193                                 self.uv_layers = [self.uv_layers[0]]
194
195                         # Assign texture unit numbers to UV layers that lack one
196                         next_unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
197                         for u in self.uv_layers:
198                                 if not u.unit:
199                                         u.unit = next_unit
200                                         next_unit += 1
201
202                 # Rewrite links between elements to point to cloned data, or create links
203                 # where they don't exist
204                 edge_map = {e.key: e for e in self.edges}
205                 for f in self.faces:
206                         if len(f.vertices)>4:
207                                 raise ValueError("Ngons are not supported")
208
209                         f.vertices = [self.vertices[i] for i in f.vertices]
210                         for v in f.vertices:
211                                 v.faces.append(f)
212
213                         for k in f.edge_keys:
214                                 e = edge_map[k]
215                                 e.faces.append(f)
216                                 f.edges.append(e)
217
218                 for e in self.edges:
219                         e.vertices = [self.vertices[i] for i in e.vertices]
220                         for v in e.vertices:
221                                 v.edges.append(e)
222
223                 # Store loose edges as lines
224                 if self.use_lines:
225                         self.lines = [Line(e) for e in self.edges if not e.faces]
226                 else:
227                         self.lines = []
228
229                 self.vertex_sequence = []
230
231         def __getattr__(self, attr):
232                 return getattr(self._mesh, attr)
233
234         def transform(self, matrix):
235                 for v in self.vertices:
236                         v.co = matrix*v.co
237
238         def splice(self, other):
239                 if len(self.uv_layers)!=len(other.uv_layers):
240                         raise ValueError("Meshes have incompatible UV layers")
241                 for i, u in enumerate(self.uv_layers):
242                         if u.name!=other.uv_layers[i].name:
243                                 raise ValueError("Meshes have incompatible UV layers")
244
245                 # Merge materials and form a lookup from source material indices to the
246                 # merged material list
247                 material_map = []
248                 for m in other.materials:
249                         if m in self.materials:
250                                 material_map.append(self.materials.index(m))
251                         else:
252                                 material_map.append(len(self.materials))
253                                 self.materials.append(m)
254
255                 # Append data and adjust indices where necessary.  Since the data is
256                 # spliced from the source mesh, rebuilding references is not necessary.
257                 for i, u in enumerate(self.uv_layers):
258                         u.uvs += other.uv_layers[i].uvs
259
260                 offset = len(self.vertices)
261                 self.vertices += other.vertices
262                 for v in self.vertices[offset:]:
263                         v.index += offset
264
265                 loop_offset = len(self.loops)
266                 self.loops += other.loops
267
268                 offset = len(self.faces)
269                 self.faces += other.faces
270                 for f in self.faces[offset:]:
271                         f.index += offset
272                         f.loop_start += loop_offset
273                         f.loop_indices = range(f.loop_start, f.loop_start+f.loop_total)
274                         if other.materials:
275                                 f.material_index = material_map[f.material_index]
276
277                 offset = len(self.edges)
278                 self.edges += other.edges
279                 for e in self.edges[offset:]:
280                         e.index += offset
281                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
282
283                 self.lines += other.lines
284
285         def prepare_triangles(self, progress):
286                 face_count = len(self.faces)
287                 for i in range(face_count):
288                         f = self.faces[i]
289                         nverts = len(f.vertices)
290                         if nverts==3:
291                                 continue
292
293                         # Calculate normals at each vertex of the face
294                         edge_vecs = []
295                         for j in range(nverts):
296                                 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
297
298                         normals = []
299                         for j in range(nverts):
300                                 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
301
302                         # Check which diagonal results in a flatter triangulation
303                         flatness1 = normals[0].dot(normals[2])
304                         flatness2 = normals[1].dot(normals[3])
305                         cut_index = 1 if flatness1>flatness2 else 0
306
307                         nf = Face(f)
308                         nf.index = len(self.faces)
309                         self.faces.append(nf)
310
311                         ne = Edge(None)
312                         ne.index = len(self.edges)
313                         self.edges.append(ne)
314
315                         nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
316                         nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
317                         for v in nf.vertices:
318                                 v.faces.append(nf)
319
320                         ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
321                         for v in ne.vertices:
322                                 v.edges.append(ne)
323                         ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
324                         ne.smooth = True
325
326                         f.vertices[3-cut_index].faces.remove(f)
327                         del f.vertices[3-cut_index]
328                         f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
329
330                         ne.faces = [f, nf]
331                         if cut_index==0:
332                                 nf.edges = [ne, f.edges[2], f.edges[3]]
333                                 f.edges = [f.edges[0], f.edges[1], ne]
334                         else:
335                                 nf.edges = [f.edges[1], f.edges[2], ne]
336                                 f.edges = [f.edges[0], ne, f.edges[3]]
337                         for e in nf.edges:
338                                 if e!=ne:
339                                         e.faces.remove(f)
340                                         e.faces.append(nf)
341
342                         f.normal = normals[1-cut_index]
343                         nf.normal = normals[3-cut_index]
344
345                         progress.set_progress(i/face_count)
346
347         def prepare_smoothing(self, progress):
348                 smooth_limit = -1
349                 if self.smoothing=='NONE':
350                         for f in self.faces:
351                                 f.use_smooth = False
352
353                         smooth_limit = 1
354                 elif self.use_auto_smooth:
355                         smooth_limit = math.cos(self.auto_smooth_angle)
356
357                 for e in self.edges:
358                         e.check_smooth(smooth_limit)
359
360                 progress.push_task("Sharp edges", 0.0, 0.7)
361                 self.split_vertices(self.find_smooth_group, progress)
362
363                 if self.smoothing!='BLENDER':
364                         progress.set_task("Updating normals", 0.7, 1.0)
365                         self.compute_normals(progress)
366
367                 progress.pop_task()
368
369         def prepare_vertex_groups(self, obj):
370                 for v in self.vertices:
371                         if v.groups:
372                                 weight_sum = sum(g.weight for g in v.groups)
373                                 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
374                                 weight_scale = weight_sum/sum(g.weight for g in v.groups)
375                                 for g in v.groups:
376                                         g.weight *= weight_scale
377
378                 if obj.parent and obj.parent.type=="ARMATURE":
379                         armature = obj.parent.data
380                         bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
381                         group_index_map = {i: i for i in range(len(obj.vertex_groups))}
382                         for g in first_obj.vertex_groups:
383                                 if g.name in bone_indices:
384                                         group_index_map[g.index] = bone_indices[g.name]
385
386                         for v in self.vertices:
387                                 for g in v.groups:
388                                         g.group = group_index_map[g.group]
389
390         def prepare_uv(self, obj, progress):
391                 if obj.material_tex and self.use_uv!='NONE':
392                         layer = UvLayer("material_tex")
393
394                         if self.use_uv=='UNIT0':
395                                 self.uv_layers = [layer]
396                                 layer.unit = 0
397                         else:
398                                 self.uv_layers.append(layer)
399                                 layer.unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
400
401                         layer.uvs = [None]*len(self.loops)
402                         for f in self.faces:
403                                 uv = mathutils.Vector(((f.material_index+0.5)/len(self.materials), 0.5))
404                                 for i in f.loop_indices:
405                                         layer.uvs[i] = uv
406
407                 # Form a list of UV layers referenced by materials with the array atlas
408                 # property set
409                 array_uv_layers = [t.uv_layer for m in self.materials if m.array_atlas for t in m.texture_slots if t and t.texture_coords=='UV']
410                 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
411
412                 if array_uv_layers:
413                         for f in self.faces:
414                                 layer = 0
415                                 if f.material_index<len(self.materials):
416                                         mat = self.materials[f.material_index]
417                                         if mat and mat.array_atlas:
418                                                 layer = mat.array_layer
419
420                                 for l in array_uv_layers:
421                                         for i in f.loop_indices:
422                                                 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
423
424                 # Copy UVs from layers to faces
425                 for f in self.faces:
426                         for u in self.uv_layers:
427                                 f.uvs.append([u.uvs[i] for i in f.loop_indices])
428
429                 prog_count = len(self.uv_layers)
430                 prog_step = 0
431
432                 # Split by the UV layer used for TBN vectors first so connectivity
433                 # remains intact for TBN vector computation
434                 tbn_layer_index = -1
435                 if self.tbn_vecs:
436                         uv_names = [u.name for u in self.uv_layers]
437                         if self.tbn_uvtex in uv_names:
438                                 prog_count += 1
439                                 tbn_layer_index = uv_names.index(self.tbn_uvtex)
440                                 progress.push_task_slice("Computing TBN", 0, prog_count)
441                                 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
442                                 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
443                                 self.compute_tbn(tbn_layer_index, progress)
444                                 progress.pop_task()
445                                 prog_step = 2
446
447                 # Split by the remaining UV layers
448                 for i, u in enumerate(self.uv_layers):
449                         if i==tbn_layer_index:
450                                 continue
451
452                         progress.push_task_slice(u.name, prog_step, prog_count)
453                         self.split_vertices(self.find_uv_group, progress, i)
454                         progress.pop_task()
455                         prog_step += 1
456
457                 # Copy UVs from faces to vertices
458                 for v in self.vertices:
459                         if v.faces:
460                                 # All faces still connected to the vertex have the same UV value
461                                 f = v.faces[0]
462                                 i = f.vertices.index(v)
463                                 v.uvs = [u[i] for u in f.uvs]
464                         else:
465                                 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
466
467         def split_vertices(self, find_group_func, progress, *args):
468                 vertex_count = len(self.vertices)
469                 for i in range(vertex_count):
470                         v = self.vertices[i]
471                         for f in v.faces:
472                                 f.flag = False
473
474                         # Find all groups of faces on this vertex
475                         groups = []
476                         for f in v.faces:
477                                 if not f.flag:
478                                         groups.append(find_group_func(v, f, *args))
479
480                         # Give groups after the first separate copies of the vertex
481                         for g in groups[1:]:
482                                 nv = Vertex(v)
483                                 nv.index = len(self.vertices)
484                                 self.vertices.append(nv)
485
486                                 for e in v.edges:
487                                         e_faces_in_g = [f for f in e.faces if f in g]
488                                         if not e_faces_in_g:
489                                                 continue
490
491                                         if len(e_faces_in_g)<len(e.faces):
492                                                 # Create a copy of an edge at the boundary of the group
493                                                 ne = Edge(e)
494                                                 ne.index = len(self.edges)
495                                                 self.edges.append(ne)
496
497                                                 ne.other_vertex(v).edges.append(ne)
498
499                                                 for f in e_faces_in_g:
500                                                         e.faces.remove(f)
501                                                         f.edges[f.edges.index(e)] = ne
502                                                         ne.faces.append(f)
503
504                                                 e = ne
505
506                                         e.vertices[e.vertices.index(v)] = nv
507                                         nv.edges.append(e)
508
509                                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
510
511                                 # Filter out any edges that were removed from the original vertex
512                                 v.edges = [e for e in v.edges if v in e.vertices]
513
514                                 for f in g:
515                                         v.faces.remove(f)
516                                         f.vertices[f.vertices.index(v)] = nv
517                                         nv.faces.append(f)
518
519                         progress.set_progress(i/vertex_count)
520
521         def find_smooth_group(self, vertex, face):
522                 face.flag = True
523
524                 edges = [e for e in face.edges if vertex in e.vertices]
525
526                 group = [face]
527                 for e in edges:
528                         f = face
529                         while e.smooth:
530                                 f = e.other_face(f)
531                                 if not f or f.flag:
532                                         break
533
534                                 f.flag = True
535                                 group.append(f)
536                                 e = f.other_edge(e, vertex)
537
538                 return group
539
540         def find_uv_group(self, vertex, face, index):
541                 uv = face.uvs[index][face.vertices.index(vertex)]
542                 face.flag = True
543
544                 group = [face]
545                 for f in vertex.faces:
546                         if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
547                                 f.flag = True
548                                 group.append(f)
549
550                 return group
551
552         def compute_normals(self, progress):
553                 for i, v in enumerate(self.vertices):
554                         v.normal = mathutils.Vector()
555                         for f in v.faces:
556                                 fv = f.pivot_vertices(v)
557                                 edge1 = fv[1].co-fv[0].co
558                                 edge2 = fv[-1].co-fv[0].co
559                                 if edge1.length and edge2.length:
560                                         # Use the angle between edges as a weighting factor.  This gives
561                                         # more consistent normals on bends with an inequal number of
562                                         # faces on each side.
563                                         v.normal += f.normal*edge1.angle(edge2)
564
565                         if v.normal.length:
566                                 v.normal.normalize()
567                         else:
568                                 v.normal = mathutils.Vector((0, 0, 1))
569
570                         progress.set_progress(i/len(self.vertices))
571
572         def compute_tbn(self, index, progress):
573                 # This function is called at an early stage during UV preparation when
574                 # face UVs are not available yet
575                 layer_uvs = self.uv_layers[index].uvs
576
577                 for i, v in enumerate(self.vertices):
578                         v.tan = mathutils.Vector()
579                         v.bino = mathutils.Vector()
580                         for f in v.faces:
581                                 vi = f.pivot_vertex(v)
582                                 uv0 = layer_uvs[f.loop_indices[vi[0]]]
583                                 uv1 = layer_uvs[f.loop_indices[vi[1]]]
584                                 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
585                                 du1 = uv1[0]-uv0[0]
586                                 du2 = uv2[0]-uv0[0]
587                                 dv1 = uv1[1]-uv0[1]
588                                 dv2 = uv2[1]-uv0[1]
589                                 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
590                                 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
591                                 div = (du1*dv2-du2*dv1)
592                                 if div:
593                                         mul = edge1.angle(edge2)/div
594                                         v.tan += (edge1*dv2-edge2*dv1)*mul
595                                         v.bino += (edge2*du1-edge1*du2)*mul
596
597                         if v.tan.length:
598                                 v.tan.normalize()
599                         if v.bino.length:
600                                 v.bino.normalize()
601
602                         progress.set_progress(i/len(self.vertices))
603
604         def prepare_sequence(self, progress):
605                 progress.push_task("Reordering faces", 0.0, 0.5)
606                 self.reorder_faces(progress)
607
608                 progress.set_task("Building sequence", 0.5, 1.0)
609                 sequence = None
610                 for i, f in enumerate(self.faces):
611                         if sequence:
612                                 if len(sequence)==3:
613                                         # Rotate the first three vertices so that the new face can be added
614                                         if sequence[0] in f.vertices and sequence[1] not in f.vertices:
615                                                 sequence.append(sequence[0])
616                                                 del sequence[0]
617                                         elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
618                                                 sequence.insert(0, sequence[-1])
619                                                 del sequence[-1]
620
621                                 if sequence[-1] not in f.vertices:
622                                         sequence = None
623                                 else:
624                                         to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
625                                         if len(to_add)==2:
626                                                 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
627                                                         to_add.reverse()
628                                                 sequence.append(sequence[-1])
629                                         sequence += to_add
630
631                         if not sequence:
632                                 sequence = f.vertices[:]
633                                 self.vertex_sequence.append(sequence)
634
635                         progress.set_progress(i/len(self.faces))
636
637                 progress.pop_task()
638
639                 self.reorder_vertices()
640
641         def reorder_faces(self, progress):
642                 # Tom Forsyth's vertex cache optimization algorithm
643                 # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
644
645                 for f in self.faces:
646                         f.flag = False
647
648                 last_triangle_score = 0.75
649                 cache_decay_power = 1.5
650                 valence_boost_scale = 2.0
651                 valence_boost_power = -0.5
652
653                 max_cache_size = 32
654                 cached_vertices = []
655
656                 # Keep track of the score and number of unused faces for each vertex
657                 vertex_info = [[0, len(v.faces)] for v in self.vertices]
658                 for vi in vertex_info:
659                         vi[0] = valence_boost_scale*(vi[1]**valence_boost_power)
660
661                 face = None
662                 reordered_faces = []
663
664                 n_processed = 0
665                 while 1:
666                         if not face:
667                                 # Previous iteration gave no candidate for best face (or this is
668                                 # the first iteration).  Scan all faces for the highest score.
669                                 best_score = 0
670                                 for f in self.faces:
671                                         if f.flag:
672                                                 continue
673
674                                         score = sum(vertex_info[v.index][0] for v in f.vertices)
675                                         if score>best_score:
676                                                 best_score = score
677                                                 face = f
678
679                         if not face:
680                                 break
681
682                         reordered_faces.append(face)
683                         face.flag = True
684
685                         for v in face.vertices:
686                                 vertex_info[v.index][1] -= 1
687
688                                 # Shuffle the vertex into the front of the cache
689                                 if v in cached_vertices:
690                                         cached_vertices.remove(v)
691                                 cached_vertices.insert(0, v)
692
693                         # Update scores for all vertices in the cache
694                         for i, v in enumerate(cached_vertices):
695                                 score = 0
696                                 if i<3:
697                                         score += last_triangle_score
698                                 elif i<max_cache_size:
699                                         score += (1-(i-3)/(max_cache_size-3))**cache_decay_power
700                                 if vertex_info[v.index][1]:
701                                         score += valence_boost_scale*(vertex_info[v.index][1]**valence_boost_power)
702                                 vertex_info[v.index][0] = score
703
704                         face = None
705                         best_score = 0
706                         for v in cached_vertices:
707                                 for f in v.faces:
708                                         if not f.flag:
709                                                 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
710                                                 if score>best_score:
711                                                         best_score = score
712                                                         face = f
713
714                         del cached_vertices[max_cache_size:]
715
716                         n_processed += 1
717                         progress.set_progress(n_processed/len(self.faces))
718
719                 self.faces = reordered_faces
720                 for i, f in enumerate(self.faces):
721                         f.index = i
722
723         def reorder_vertices(self):
724                 for v in self.vertices:
725                         v.index = -1
726
727                 reordered_vertices = []
728                 for s in self.vertex_sequence:
729                         for v in s:
730                                 if v.index<0:
731                                         v.index = len(reordered_vertices)
732                                         reordered_vertices.append(v)
733
734                 self.vertices = reordered_vertices
735
736                 for e in self.edges:
737                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
738
739         def drop_references(self):
740                 for v in self.vertices:
741                         v._vertex = None
742                         for g in v.groups:
743                                 g._group = None
744                 for e in self.edges:
745                         e._edge = None
746                 for f in self.faces:
747                         f._face = None
748                 for u in self.uv_layers:
749                         u._layer = None
750                 self._mesh = None
751
752
753 def create_mesh_from_object(context, obj, progress):
754         if obj.type!="MESH":
755                 raise Exception("Object is not a mesh")
756
757         progress.push_task("Preparing mesh", 0.0, 0.2)
758
759         objs = [(obj, mathutils.Matrix())]
760         i = 0
761         while i<len(objs):
762                 o, m = objs[i]
763                 i += 1
764                 for c in o.children:
765                         if c.type=="MESH" and c.compound:
766                                 objs.append((c, m*c.matrix_local))
767
768         mesh = None
769         bmeshes = []
770         for o, m in objs:
771                 bmesh = o.to_mesh(context.scene, True, "PREVIEW")
772                 bmeshes.append(bmesh)
773
774                 # Object.to_mesh does not copy custom properties
775                 bmesh.winding_test = o.data.winding_test
776                 bmesh.smoothing = o.data.smoothing
777                 bmesh.use_lines = o.data.use_lines
778                 bmesh.vertex_groups = o.data.vertex_groups
779                 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
780                 bmesh.use_uv = o.data.use_uv
781                 bmesh.tbn_vecs = o.data.tbn_vecs
782                 bmesh.tbn_uvtex = o.data.tbn_uvtex
783
784                 me = Mesh(bmesh)
785                 me.transform(m)
786
787                 if mesh:
788                         mesh.splice(me)
789                 else:
790                         mesh = me
791
792         progress.set_task("Triangulating", 0.2, 0.3)
793         mesh.prepare_triangles(progress)
794         progress.set_task("Smoothing", 0.3, 0.5)
795         mesh.prepare_smoothing(progress)
796         progress.set_task("Vertex groups", 0.5, 0.6)
797         mesh.prepare_vertex_groups(obj)
798         progress.set_task("Preparing UVs", 0.6, 0.8)
799         mesh.prepare_uv(obj, progress)
800         progress.set_task("Render sequence", 0.8, 1.0)
801         mesh.prepare_sequence(progress)
802
803         # Discard the temporary Blender meshes after making sure there's no
804         # references to the data
805         mesh.drop_references()
806         for m in bmeshes:
807                 bpy.data.meshes.remove(m)
808
809         progress.pop_task()
810
811         return mesh