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