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