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