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