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.smooth = edge.smooth
16 self.vertices = edge.vertices[:]
23 def check_smooth(self, limit):
24 if len(self.faces)!=2:
27 d = self.faces[0].normal.dot(self.faces[1].normal)
28 self.smooth = ((d>limit and self.faces[0].use_smooth and self.faces[1].use_smooth) or d>0.99995)
30 def other_face(self, f):
31 if f.index==self.faces[0].index:
32 if len(self.faces)>=2:
39 def other_vertex(self, v):
40 if v.index==self.vertices[0].index:
41 return self.vertices[1]
43 return self.vertices[0]
47 def __init__(self, vertex):
48 if vertex.__class__==Vertex:
49 self.uvs = vertex.uvs[:]
51 self.bino = vertex.bino
56 self.index = vertex.index
57 self.co = mathutils.Vector(vertex.co)
58 self.normal = mathutils.Vector(vertex.normal)
63 self.groups = vertex.groups[:]
65 def __cmp__(self, other):
68 return cmp(self.index, other.index)
72 def __init__(self, group):
73 self.group = group.group
74 self.weight = group.weight
78 def __init__(self, face):
79 self.index = face.index
81 self.edge_keys = face.edge_keys
82 self.vertices = face.vertices[:]
83 self.loop_indices = face.loop_indices
84 self.normal = face.normal
85 self.use_smooth = face.use_smooth
86 self.material_index = face.material_index
89 def __cmp__(self, other):
92 return cmp(self.index, other.index)
94 def pivot_vertex(self, v):
95 n = self.vertices.index(v)
96 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
98 def get_loop_index(self, v):
99 return self.loop_indices[self.vertices.index(v)]
101 def get_edge(self, v1, v2):
102 key = make_edge_key(v1.index, v2.index)
106 raise KeyError("No edge %s"%(key,))
108 def other_edge(self, e, v):
110 if d!=e and v in d.vertices:
113 def get_neighbors(self):
114 neighbors = [e.other_face(self) for e in self.edges]
115 return list(filter(bool, neighbors))
119 def __init__(self, e):
121 self.vertices = e.vertices[:]
126 def __init__(self, arg):
132 self.uvs = [mathutils.Vector(d.uv) for d in arg.data]
137 dot = self.name.find('.')
139 ext = self.name[dot:]
140 if ext.startswith(".unit") and ext[5:].isdigit():
141 self.unit = int(ext[5:])
147 def __init__(self, l):
149 self.colors = [c.color[:] for c in l.data]
153 def __init__(self, mesh):
154 self.name = mesh.name
156 self.winding_test = mesh.winding_test
157 self.smoothing = mesh.smoothing
158 self.use_uv = mesh.use_uv
159 self.tbn_vecs = mesh.tbn_vecs
160 self.tbn_uvtex = mesh.tbn_uvtex
161 self.vertex_groups = mesh.vertex_groups
164 self.vertices = [Vertex(v) for v in mesh.vertices]
165 for v in self.vertices:
166 v.groups = [VertexGroup(g) for g in v.groups]
168 self.faces = [Face(f) for f in mesh.polygons]
169 self.edges = [Edge(e) for e in mesh.edges]
170 self.loops = mesh.loops[:]
171 self.materials = mesh.materials[:]
173 self.use_auto_smooth = mesh.use_auto_smooth
174 self.auto_smooth_angle = mesh.auto_smooth_angle
176 # Clone only the desired UV layers
177 if mesh.use_uv=='NONE' or not mesh.uv_layers:
180 self.uv_layers = [UvLayer(u) for u in mesh.uv_layers]
182 # Assign texture unit numbers to UV layers that lack one
183 missing_unit = [u for u in self.uv_layers if u.unit is None]
185 missing_unit = sorted(missing_unit, key=(lambda u: u.name))
186 used_units = [u.unit for u in self.uv_layers if u.unit is not None]
187 for u, n in zip(missing_unit, (i for i in itertools.count() if i not in used_units)):
190 self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
192 if mesh.use_uv=='UNIT0':
193 self.uv_layers = [self.uv_layers[0]]
194 if self.uv_layers[0].unit!=0:
198 if mesh.vertex_colors:
199 self.colors = ColorLayer(mesh.vertex_colors[0])
201 # Rewrite links between elements to point to cloned data, or create links
202 # where they don't exist
203 edge_map = {e.key: e for e in self.edges}
205 if len(f.vertices)>4:
206 raise ValueError("Ngons are not supported")
208 f.vertices = [self.vertices[i] for i in f.vertices]
212 for k in f.edge_keys:
218 e.vertices = [self.vertices[i] for i in e.vertices]
222 # Store loose edges as lines
224 self.lines = [Line(e) for e in self.edges if not e.faces]
228 self.vertex_sequence = []
230 def transform(self, matrix):
231 for v in self.vertices:
234 def splice(self, other):
235 if len(self.uv_layers)!=len(other.uv_layers):
236 raise ValueError("Meshes have incompatible UV layers")
237 for i, u in enumerate(self.uv_layers):
238 if u.name!=other.uv_layers[i].name:
239 raise ValueError("Meshes have incompatible UV layers")
241 # Merge materials and form a lookup from source material indices to the
242 # merged material list
244 for m in other.materials:
245 if m in self.materials:
246 material_map.append(self.materials.index(m))
248 material_map.append(len(self.materials))
249 self.materials.append(m)
251 # Append data and adjust indices where necessary. Since the data is
252 # spliced from the source mesh, rebuilding references is not necessary.
253 for i, u in enumerate(self.uv_layers):
254 u.uvs += other.uv_layers[i].uvs
258 self.colors.colors += other.colors.colors
260 self.colors.colors += [(1.0, 1.0, 1.0, 1.0)]*len(other.loops)
262 self.colors = ColorLayer(other.colors.name)
263 self.colors.colors = [(1.0, 1.0, 1.0, 1.0)]*len(self.loops)+other.colors.colors
265 offset = len(self.vertices)
266 self.vertices += other.vertices
267 for v in self.vertices[offset:]:
270 loop_offset = len(self.loops)
271 self.loops += other.loops
273 offset = len(self.faces)
274 self.faces += other.faces
275 for f in self.faces[offset:]:
277 f.loop_indices = range(f.loop_indices.start+offset, f.loop_indices.stop+offset)
279 f.material_index = material_map[f.material_index]
281 offset = len(self.edges)
282 self.edges += other.edges
283 for e in self.edges[offset:]:
285 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
287 self.lines += other.lines
289 def prepare_triangles(self, progress):
290 face_count = len(self.faces)
291 for i in range(face_count):
293 nverts = len(f.vertices)
297 # Calculate normals at each vertex of the face
299 for j in range(nverts):
300 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
303 for j in range(nverts):
304 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
306 # Check which diagonal results in a flatter triangulation
307 flatness1 = normals[0].dot(normals[2])
308 flatness2 = normals[1].dot(normals[3])
309 cut_index = 1 if flatness1>flatness2 else 0
312 nf.index = len(self.faces)
313 self.faces.append(nf)
316 ne.index = len(self.edges)
317 self.edges.append(ne)
319 nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
320 nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
321 for v in nf.vertices:
324 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
325 for v in ne.vertices:
327 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
330 f.vertices[3-cut_index].faces.remove(f)
331 del f.vertices[3-cut_index]
332 f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
336 nf.edges = [ne, f.edges[2], f.edges[3]]
337 f.edges = [f.edges[0], f.edges[1], ne]
339 nf.edges = [f.edges[1], f.edges[2], ne]
340 f.edges = [f.edges[0], ne, f.edges[3]]
346 f.normal = normals[1-cut_index]
347 nf.normal = normals[3-cut_index]
349 progress.set_progress(i/face_count)
351 def prepare_smoothing(self, progress):
353 if self.smoothing=='NONE':
358 elif self.use_auto_smooth:
359 smooth_limit = math.cos(self.auto_smooth_angle)
362 e.check_smooth(smooth_limit)
364 progress.push_task("Sharp edges", 0.0, 0.7)
365 self.split_vertices(self.find_smooth_group, progress)
367 if self.smoothing!='BLENDER':
368 progress.set_task("Updating normals", 0.7, 1.0)
369 self.compute_normals(progress)
373 def prepare_vertex_groups(self, obj):
374 for v in self.vertices:
376 weight_sum = sum(g.weight for g in v.groups)
377 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
378 weight_scale = weight_sum/sum(g.weight for g in v.groups)
380 g.weight *= weight_scale
382 if obj.parent and obj.parent.type=="ARMATURE":
383 armature = obj.parent.data
384 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
385 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
386 for g in first_obj.vertex_groups:
387 if g.name in bone_indices:
388 group_index_map[g.index] = bone_indices[g.name]
390 for v in self.vertices:
392 g.group = group_index_map[g.group]
394 def apply_material_map(self, material_map):
395 for m in self.materials:
396 if m.name not in material_map.material_names:
397 raise Exception("Material map is not compatible with Mesh")
399 if self.use_uv=='NONE':
402 layer = UvLayer("material_map")
403 if self.use_uv=='UNIT0':
404 self.uv_layers = [layer]
407 self.uv_layers.append(layer)
408 used_units = [u.unit for u in self.uv_layers]
409 layer.unit = next(i for i in itertools.count() if i not in used_units)
410 self.uv_layers.sort(key=lambda u: u.unit)
412 layer.uvs = [(0.0, 0.0)]*len(self.loops)
414 uv = material_map.get_material_uv(self.materials[f.material_index])
415 for i in f.loop_indices:
418 def prepare_uv(self, progress):
419 # Form a list of UV layers referenced by materials with the array atlas
421 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']
422 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
427 if f.material_index<len(self.materials):
428 mat = self.materials[f.material_index]
429 if mat and mat.array_atlas:
430 layer = mat.array_layer
432 for l in array_uv_layers:
433 for i in f.loop_indices:
434 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
436 prog_count = len(self.uv_layers)
439 # Split by the UV layer used for TBN vectors first so connectivity
440 # remains intact for TBN vector computation
443 uv_names = [u.name for u in self.uv_layers]
444 if self.tbn_uvtex in uv_names:
446 tbn_layer_index = uv_names.index(self.tbn_uvtex)
447 progress.push_task_slice("Computing TBN", 0, prog_count)
448 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
449 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
450 self.compute_tbn(tbn_layer_index, progress)
454 raise Exception("TBN UV layer not found")
456 # Split by the remaining UV layers
457 for i, u in enumerate(self.uv_layers):
458 if i==tbn_layer_index:
461 progress.push_task_slice(u.name, prog_step, prog_count)
462 self.split_vertices(self.find_uv_group, progress, i)
466 # Copy UVs from layers to vertices
467 for v in self.vertices:
469 # All faces still connected to the vertex have the same UV value
471 i = f.get_loop_index(v)
472 v.uvs = [u.uvs[i] for u in self.uv_layers]
474 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
476 def prepare_colors(self, progress):
480 self.split_vertices(self.find_color_group, progress)
482 for v in self.vertices:
485 v.color = self.colors.colors[f.get_loop_index(v)]
487 v.color = (1.0, 1.0, 1.0, 1.0)
489 def split_vertices(self, find_group_func, progress, *args):
490 vertex_count = len(self.vertices)
491 for i in range(vertex_count):
496 # Find all groups of faces on this vertex
500 groups.append(find_group_func(v, f, *args))
502 # Give groups after the first separate copies of the vertex
505 nv.index = len(self.vertices)
506 self.vertices.append(nv)
509 e_faces_in_g = [f for f in e.faces if f in g]
513 if len(e_faces_in_g)<len(e.faces):
514 # Create a copy of an edge at the boundary of the group
516 ne.index = len(self.edges)
517 self.edges.append(ne)
519 ne.other_vertex(v).edges.append(ne)
521 for f in e_faces_in_g:
523 f.edges[f.edges.index(e)] = ne
528 e.vertices[e.vertices.index(v)] = nv
531 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
533 # Filter out any edges that were removed from the original vertex
534 v.edges = [e for e in v.edges if v in e.vertices]
538 f.vertices[f.vertices.index(v)] = nv
541 progress.set_progress(i/vertex_count)
543 def find_smooth_group(self, vertex, face):
546 edges = [e for e in face.edges if vertex in e.vertices]
558 e = f.other_edge(e, vertex)
562 def find_uv_group(self, vertex, face, index):
563 layer = self.uv_layers[index]
564 uv = layer.uvs[face.get_loop_index(vertex)]
568 for f in vertex.faces:
569 if not f.flag and layer.uvs[f.get_loop_index(vertex)]==uv:
575 def find_color_group(self, vertex, face):
576 color = self.colors.colors[face.get_loop_index(vertex)]
580 for f in vertex.faces:
581 if not f.flag and self.colors.colors[f.get_loop_index(vertex)]==color:
587 def compute_normals(self, progress):
588 for i, v in enumerate(self.vertices):
589 v.normal = mathutils.Vector()
591 vi = f.pivot_vertex(v)
592 edge1 = f.vertices[vi[1]].co-v.co
593 edge2 = f.vertices[vi[-1]].co-v.co
594 if edge1.length and edge2.length:
595 # Use the angle between edges as a weighting factor. This gives
596 # more consistent normals on bends with an inequal number of
597 # faces on each side.
598 v.normal += f.normal*edge1.angle(edge2)
603 v.normal = mathutils.Vector((0, 0, 1))
605 progress.set_progress(i/len(self.vertices))
607 def compute_tbn(self, index, progress):
608 # This function is called at an early stage during UV preparation when
609 # face UVs are not available yet
610 layer_uvs = self.uv_layers[index].uvs
612 for i, v in enumerate(self.vertices):
613 v.tan = mathutils.Vector()
614 v.bino = mathutils.Vector()
616 vi = f.pivot_vertex(v)
617 uv0 = layer_uvs[f.loop_indices[vi[0]]]
618 uv1 = layer_uvs[f.loop_indices[vi[1]]]
619 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
624 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
625 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
626 div = (du1*dv2-du2*dv1)
628 mul = edge1.angle(edge2)/div
629 v.tan += (edge1*dv2-edge2*dv1)*mul
630 v.bino += (edge2*du1-edge1*du2)*mul
637 progress.set_progress(i/len(self.vertices))
639 def prepare_sequence(self, progress):
640 progress.push_task("Reordering faces", 0.0, 0.5)
641 self.reorder_faces(progress)
643 progress.set_task("Building sequence", 0.5, 1.0)
645 for i, f in enumerate(self.faces):
648 # Rotate the first three vertices so that the new face can be added
649 if sequence[0] in f.vertices and sequence[1] not in f.vertices:
650 sequence.append(sequence[0])
652 elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
653 sequence.insert(0, sequence[-1])
656 if sequence[-1] not in f.vertices:
659 to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
661 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
663 sequence.append(sequence[-1])
667 sequence = f.vertices[:]
668 self.vertex_sequence.append(sequence)
670 progress.set_progress(i/len(self.faces))
674 self.reorder_vertices()
676 def reorder_faces(self, progress):
677 # Tom Forsyth's vertex cache optimization algorithm
678 # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
683 last_triangle_score = 0.75
684 cache_decay_power = 1.5
685 valence_boost_scale = 2.0
686 valence_boost_power = -0.5
691 # Keep track of the score and number of unused faces for each vertex
692 vertex_info = [[0, len(v.faces)] for v in self.vertices]
693 for vi in vertex_info:
694 vi[0] = valence_boost_scale*(vi[1]**valence_boost_power)
702 # Previous iteration gave no candidate for best face (or this is
703 # the first iteration). Scan all faces for the highest score.
709 score = sum(vertex_info[v.index][0] for v in f.vertices)
717 reordered_faces.append(face)
720 for v in face.vertices:
721 vertex_info[v.index][1] -= 1
723 # Shuffle the vertex into the front of the cache
724 if v in cached_vertices:
725 cached_vertices.remove(v)
726 cached_vertices.insert(0, v)
728 # Update scores for all vertices in the cache
729 for i, v in enumerate(cached_vertices):
732 score += last_triangle_score
733 elif i<max_cache_size:
734 score += (1-(i-3)/(max_cache_size-3))**cache_decay_power
735 if vertex_info[v.index][1]:
736 score += valence_boost_scale*(vertex_info[v.index][1]**valence_boost_power)
737 vertex_info[v.index][0] = score
741 for v in cached_vertices:
744 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
749 del cached_vertices[max_cache_size:]
752 progress.set_progress(n_processed/len(self.faces))
754 self.faces = reordered_faces
755 for i, f in enumerate(self.faces):
758 def reorder_vertices(self):
759 for v in self.vertices:
762 reordered_vertices = []
763 for s in self.vertex_sequence:
766 v.index = len(reordered_vertices)
767 reordered_vertices.append(v)
769 self.vertices = reordered_vertices
772 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
775 def create_mesh_from_object(context, obj, progress, *, material_map=None):
777 raise Exception("Object is not a mesh")
779 progress.push_task("Preparing mesh", 0.0, 0.2)
781 objs = [(obj, mathutils.Matrix())]
787 if c.type=="MESH" and c.compound:
788 objs.append((c, m*c.matrix_local))
790 dg = context.evaluated_depsgraph_get()
794 eval_obj = o.evaluated_get(dg)
795 bmesh = eval_obj.to_mesh()
797 # Object.to_mesh does not copy custom properties
798 bmesh.winding_test = o.data.winding_test
799 bmesh.smoothing = o.data.smoothing
800 bmesh.use_lines = o.data.use_lines
801 bmesh.vertex_groups = o.data.vertex_groups
802 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
803 bmesh.use_uv = o.data.use_uv
804 bmesh.tbn_vecs = o.data.tbn_vecs
805 bmesh.tbn_uvtex = o.data.tbn_uvtex
810 for i, s in enumerate(eval_obj.material_slots):
812 me.materials[i] = s.material
819 mesh.name = obj.data.name
822 mesh.apply_material_map(material_map)
824 progress.set_task("Triangulating", 0.2, 0.3)
825 mesh.prepare_triangles(progress)
826 progress.set_task("Smoothing", 0.3, 0.5)
827 mesh.prepare_smoothing(progress)
828 progress.set_task("Vertex groups", 0.5, 0.6)
829 mesh.prepare_vertex_groups(obj)
830 progress.set_task("Preparing UVs", 0.6, 0.75)
831 mesh.prepare_uv(progress)
832 progress.set_task("Preparing vertex colors", 0.75, 0.85)
833 mesh.prepare_colors(progress)
834 progress.set_task("Render sequence", 0.85, 1.0)
835 mesh.prepare_sequence(progress)