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