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