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