6 def make_edge_key(i1, i2):
7 return (min(i1, i2), max(i1, i2))
10 def __init__(self, edge):
11 if edge.__class__==Edge:
12 self._edge = edge._edge
13 self.smooth = edge.smooth
18 self.vertices = edge.vertices[:]
25 def __getattr__(self, attr):
26 return getattr(self._edge, attr)
28 def check_smooth(self, limit):
29 if len(self.faces)!=2:
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)
35 def other_face(self, f):
36 if f.index==self.faces[0].index:
37 if len(self.faces)>=2:
44 def other_vertex(self, v):
45 if v.index==self.vertices[0].index:
46 return self.vertices[1]
48 return self.vertices[0]
52 def __init__(self, vertex):
53 if vertex.__class__==Vertex:
54 self._vertex = vertex._vertex
55 self.uvs = vertex.uvs[:]
57 self.bino = vertex.bino
63 self.index = vertex.index
64 self.co = mathutils.Vector(vertex.co)
65 self.normal = mathutils.Vector(vertex.normal)
69 self.groups = vertex.groups[:]
71 def __getattr__(self, attr):
72 return getattr(self._vertex, attr)
74 def __cmp__(self, other):
77 return cmp(self.index, other.index)
81 def __init__(self, group):
83 self.group = group.group
84 self.weight = group.weight
86 def __getattr__(self, attr):
87 return getattr(self._group, attr)
91 def __init__(self, face):
93 self.index = face.index
95 self.vertices = face.vertices[:]
99 def __getattr__(self, attr):
100 return getattr(self._face, attr)
102 def __cmp__(self, other):
105 return cmp(self.index, other.index)
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))]
111 def pivot_vertices(self, *vt):
112 flags = [(v in vt) for v in self.vertices]
113 l = len(self.vertices)
115 if flags[i] and not flags[(i+l-1)%l]:
116 return self.vertices[i:]+self.vertices[:i]
118 def get_edge(self, v1, v2):
119 key = make_edge_key(v1.index, v2.index)
123 raise KeyError("No edge %s"%(key,))
125 def other_edge(self, e, v):
127 if d!=e and v in d.vertices:
130 def get_neighbors(self):
131 neighbors = [e.other_face(self) for e in self.edges]
132 return list(filter(bool, neighbors))
136 def __init__(self, e):
138 self.vertices = e.vertices[:]
143 def __init__(self, arg):
151 self.uvs = [mathutils.Vector(d.uv) for d in self.data]
156 dot = self.name.find('.')
158 ext = self.name[dot:]
159 if ext.startswith(".unit") and ext[5:].isdigit():
160 self.unit = int(ext[5:])
164 def __getattr__(self, attr):
165 return getattr(self._layer, attr)
169 def __init__(self, mesh):
171 self.name = mesh.name
173 self.winding_test = mesh.winding_test
174 self.tbn_vecs = mesh.tbn_vecs
175 self.vertex_groups = mesh.vertex_groups
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]
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[:]
187 # Clone only the desired UV layers
188 if self.use_uv=='NONE' or not mesh.uv_layers:
191 self.uv_layers = [UvLayer(u) for u in mesh.uv_layers]
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]
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)):
201 self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
203 if self.use_uv=='UNIT0':
204 self.uv_layers = [self.uv_layers[0]]
205 if self.uv_layers[0].unit!=0:
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}
212 if len(f.vertices)>4:
213 raise ValueError("Ngons are not supported")
215 f.vertices = [self.vertices[i] for i in f.vertices]
219 for k in f.edge_keys:
225 e.vertices = [self.vertices[i] for i in e.vertices]
229 # Store loose edges as lines
231 self.lines = [Line(e) for e in self.edges if not e.faces]
235 self.vertex_sequence = []
237 def __getattr__(self, attr):
238 return getattr(self._mesh, attr)
240 def transform(self, matrix):
241 for v in self.vertices:
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")
251 # Merge materials and form a lookup from source material indices to the
252 # merged material list
254 for m in other.materials:
255 if m in self.materials:
256 material_map.append(self.materials.index(m))
258 material_map.append(len(self.materials))
259 self.materials.append(m)
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
266 offset = len(self.vertices)
267 self.vertices += other.vertices
268 for v in self.vertices[offset:]:
271 loop_offset = len(self.loops)
272 self.loops += other.loops
274 offset = len(self.faces)
275 self.faces += other.faces
276 for f in self.faces[offset:]:
278 f.loop_indices = range(f.loop_indices.start+offset, f.loop_indices.stop+offset)
280 f.material_index = material_map[f.material_index]
282 offset = len(self.edges)
283 self.edges += other.edges
284 for e in self.edges[offset:]:
286 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
288 self.lines += other.lines
290 def prepare_triangles(self, progress):
291 face_count = len(self.faces)
292 for i in range(face_count):
294 nverts = len(f.vertices)
298 # Calculate normals at each vertex of the face
300 for j in range(nverts):
301 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
304 for j in range(nverts):
305 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
307 # Check which diagonal results in a flatter triangulation
308 flatness1 = normals[0].dot(normals[2])
309 flatness2 = normals[1].dot(normals[3])
310 cut_index = 1 if flatness1>flatness2 else 0
313 nf.index = len(self.faces)
314 self.faces.append(nf)
317 ne.index = len(self.edges)
318 self.edges.append(ne)
320 nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
321 nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
322 for v in nf.vertices:
325 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
326 for v in ne.vertices:
328 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
331 f.vertices[3-cut_index].faces.remove(f)
332 del f.vertices[3-cut_index]
333 f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
337 nf.edges = [ne, f.edges[2], f.edges[3]]
338 f.edges = [f.edges[0], f.edges[1], ne]
340 nf.edges = [f.edges[1], f.edges[2], ne]
341 f.edges = [f.edges[0], ne, f.edges[3]]
347 f.normal = normals[1-cut_index]
348 nf.normal = normals[3-cut_index]
350 progress.set_progress(i/face_count)
352 def prepare_smoothing(self, progress):
354 if self.smoothing=='NONE':
359 elif self.use_auto_smooth:
360 smooth_limit = math.cos(self.auto_smooth_angle)
363 e.check_smooth(smooth_limit)
365 progress.push_task("Sharp edges", 0.0, 0.7)
366 self.split_vertices(self.find_smooth_group, progress)
368 if self.smoothing!='BLENDER':
369 progress.set_task("Updating normals", 0.7, 1.0)
370 self.compute_normals(progress)
374 def prepare_vertex_groups(self, obj):
375 for v in self.vertices:
377 weight_sum = sum(g.weight for g in v.groups)
378 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
379 weight_scale = weight_sum/sum(g.weight for g in v.groups)
381 g.weight *= weight_scale
383 if obj.parent and obj.parent.type=="ARMATURE":
384 armature = obj.parent.data
385 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
386 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
387 for g in first_obj.vertex_groups:
388 if g.name in bone_indices:
389 group_index_map[g.index] = bone_indices[g.name]
391 for v in self.vertices:
393 g.group = group_index_map[g.group]
395 def apply_material_map(self, material_map):
396 for m in self.materials:
397 if m.name not in material_map.material_names:
398 raise Exception("Material map is not compatible with Mesh")
400 if self.use_uv=='NONE':
403 layer = UvLayer("material_map")
404 if self.use_uv=='UNIT0':
405 self.uv_layers = [layer]
408 self.uv_layers.append(layer)
409 used_units = [u.unit for u in self.uv_layers]
410 layer.unit = next(i for i in itertools.count() if i not in used_units)
411 self.uv_layers.sort(key=lambda u: u.unit)
413 layer.uvs = [(0.0, 0.0)]*len(self.loops)
415 uv = material_map.get_material_uv(self.materials[f.material_index])
416 for i in f.loop_indices:
419 def prepare_uv(self, progress):
420 # Form a list of UV layers referenced by materials with the array atlas
422 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']
423 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
428 if f.material_index<len(self.materials):
429 mat = self.materials[f.material_index]
430 if mat and mat.array_atlas:
431 layer = mat.array_layer
433 for l in array_uv_layers:
434 for i in f.loop_indices:
435 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
437 # Copy UVs from layers to faces
439 for u in self.uv_layers:
440 f.uvs.append([u.uvs[i] for i in f.loop_indices])
442 prog_count = len(self.uv_layers)
445 # Split by the UV layer used for TBN vectors first so connectivity
446 # remains intact for TBN vector computation
449 uv_names = [u.name for u in self.uv_layers]
450 if self.tbn_uvtex in uv_names:
452 tbn_layer_index = uv_names.index(self.tbn_uvtex)
453 progress.push_task_slice("Computing TBN", 0, prog_count)
454 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
455 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
456 self.compute_tbn(tbn_layer_index, progress)
460 # Split by the remaining UV layers
461 for i, u in enumerate(self.uv_layers):
462 if i==tbn_layer_index:
465 progress.push_task_slice(u.name, prog_step, prog_count)
466 self.split_vertices(self.find_uv_group, progress, i)
470 # Copy UVs from faces to vertices
471 for v in self.vertices:
473 # All faces still connected to the vertex have the same UV value
475 i = f.vertices.index(v)
476 v.uvs = [u[i] for u in f.uvs]
478 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
480 def split_vertices(self, find_group_func, progress, *args):
481 vertex_count = len(self.vertices)
482 for i in range(vertex_count):
487 # Find all groups of faces on this vertex
491 groups.append(find_group_func(v, f, *args))
493 # Give groups after the first separate copies of the vertex
496 nv.index = len(self.vertices)
497 self.vertices.append(nv)
500 e_faces_in_g = [f for f in e.faces if f in g]
504 if len(e_faces_in_g)<len(e.faces):
505 # Create a copy of an edge at the boundary of the group
507 ne.index = len(self.edges)
508 self.edges.append(ne)
510 ne.other_vertex(v).edges.append(ne)
512 for f in e_faces_in_g:
514 f.edges[f.edges.index(e)] = ne
519 e.vertices[e.vertices.index(v)] = nv
522 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
524 # Filter out any edges that were removed from the original vertex
525 v.edges = [e for e in v.edges if v in e.vertices]
529 f.vertices[f.vertices.index(v)] = nv
532 progress.set_progress(i/vertex_count)
534 def find_smooth_group(self, vertex, face):
537 edges = [e for e in face.edges if vertex in e.vertices]
549 e = f.other_edge(e, vertex)
553 def find_uv_group(self, vertex, face, index):
554 uv = face.uvs[index][face.vertices.index(vertex)]
558 for f in vertex.faces:
559 if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
565 def compute_normals(self, progress):
566 for i, v in enumerate(self.vertices):
567 v.normal = mathutils.Vector()
569 fv = f.pivot_vertices(v)
570 edge1 = fv[1].co-fv[0].co
571 edge2 = fv[-1].co-fv[0].co
572 if edge1.length and edge2.length:
573 # Use the angle between edges as a weighting factor. This gives
574 # more consistent normals on bends with an inequal number of
575 # faces on each side.
576 v.normal += f.normal*edge1.angle(edge2)
581 v.normal = mathutils.Vector((0, 0, 1))
583 progress.set_progress(i/len(self.vertices))
585 def compute_tbn(self, index, progress):
586 # This function is called at an early stage during UV preparation when
587 # face UVs are not available yet
588 layer_uvs = self.uv_layers[index].uvs
590 for i, v in enumerate(self.vertices):
591 v.tan = mathutils.Vector()
592 v.bino = mathutils.Vector()
594 vi = f.pivot_vertex(v)
595 uv0 = layer_uvs[f.loop_indices[vi[0]]]
596 uv1 = layer_uvs[f.loop_indices[vi[1]]]
597 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
602 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
603 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
604 div = (du1*dv2-du2*dv1)
606 mul = edge1.angle(edge2)/div
607 v.tan += (edge1*dv2-edge2*dv1)*mul
608 v.bino += (edge2*du1-edge1*du2)*mul
615 progress.set_progress(i/len(self.vertices))
617 def prepare_sequence(self, progress):
618 progress.push_task("Reordering faces", 0.0, 0.5)
619 self.reorder_faces(progress)
621 progress.set_task("Building sequence", 0.5, 1.0)
623 for i, f in enumerate(self.faces):
626 # Rotate the first three vertices so that the new face can be added
627 if sequence[0] in f.vertices and sequence[1] not in f.vertices:
628 sequence.append(sequence[0])
630 elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
631 sequence.insert(0, sequence[-1])
634 if sequence[-1] not in f.vertices:
637 to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
639 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
641 sequence.append(sequence[-1])
645 sequence = f.vertices[:]
646 self.vertex_sequence.append(sequence)
648 progress.set_progress(i/len(self.faces))
652 self.reorder_vertices()
654 def reorder_faces(self, progress):
655 # Tom Forsyth's vertex cache optimization algorithm
656 # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
661 last_triangle_score = 0.75
662 cache_decay_power = 1.5
663 valence_boost_scale = 2.0
664 valence_boost_power = -0.5
669 # Keep track of the score and number of unused faces for each vertex
670 vertex_info = [[0, len(v.faces)] for v in self.vertices]
671 for vi in vertex_info:
672 vi[0] = valence_boost_scale*(vi[1]**valence_boost_power)
680 # Previous iteration gave no candidate for best face (or this is
681 # the first iteration). Scan all faces for the highest score.
687 score = sum(vertex_info[v.index][0] for v in f.vertices)
695 reordered_faces.append(face)
698 for v in face.vertices:
699 vertex_info[v.index][1] -= 1
701 # Shuffle the vertex into the front of the cache
702 if v in cached_vertices:
703 cached_vertices.remove(v)
704 cached_vertices.insert(0, v)
706 # Update scores for all vertices in the cache
707 for i, v in enumerate(cached_vertices):
710 score += last_triangle_score
711 elif i<max_cache_size:
712 score += (1-(i-3)/(max_cache_size-3))**cache_decay_power
713 if vertex_info[v.index][1]:
714 score += valence_boost_scale*(vertex_info[v.index][1]**valence_boost_power)
715 vertex_info[v.index][0] = score
719 for v in cached_vertices:
722 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
727 del cached_vertices[max_cache_size:]
730 progress.set_progress(n_processed/len(self.faces))
732 self.faces = reordered_faces
733 for i, f in enumerate(self.faces):
736 def reorder_vertices(self):
737 for v in self.vertices:
740 reordered_vertices = []
741 for s in self.vertex_sequence:
744 v.index = len(reordered_vertices)
745 reordered_vertices.append(v)
747 self.vertices = reordered_vertices
750 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
752 def drop_references(self):
753 for v in self.vertices:
761 for u in self.uv_layers:
766 def create_mesh_from_object(context, obj, progress, *, material_map=None):
768 raise Exception("Object is not a mesh")
770 progress.push_task("Preparing mesh", 0.0, 0.2)
772 objs = [(obj, mathutils.Matrix())]
778 if c.type=="MESH" and c.compound:
779 objs.append((c, m*c.matrix_local))
781 dg = context.evaluated_depsgraph_get()
785 eval_obj = o.evaluated_get(dg)
786 bmesh = eval_obj.to_mesh()
788 # Object.to_mesh does not copy custom properties
789 bmesh.winding_test = o.data.winding_test
790 bmesh.smoothing = o.data.smoothing
791 bmesh.use_lines = o.data.use_lines
792 bmesh.vertex_groups = o.data.vertex_groups
793 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
794 bmesh.use_uv = o.data.use_uv
795 bmesh.tbn_vecs = o.data.tbn_vecs
796 bmesh.tbn_uvtex = o.data.tbn_uvtex
801 for i, s in enumerate(eval_obj.material_slots):
803 me.materials[i] = s.material
810 mesh.name = obj.data.name
813 mesh.apply_material_map(material_map)
815 progress.set_task("Triangulating", 0.2, 0.3)
816 mesh.prepare_triangles(progress)
817 progress.set_task("Smoothing", 0.3, 0.5)
818 mesh.prepare_smoothing(progress)
819 progress.set_task("Vertex groups", 0.5, 0.6)
820 mesh.prepare_vertex_groups(obj)
821 progress.set_task("Preparing UVs", 0.6, 0.8)
822 mesh.prepare_uv(progress)
823 progress.set_task("Render sequence", 0.8, 1.0)
824 mesh.prepare_sequence(progress)
826 # Discard the temporary Blender meshes after making sure there's no
827 # references to the data
828 mesh.drop_references()