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