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