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