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)
62 self.groups = vertex.groups[:]
64 def __cmp__(self, other):
67 return cmp(self.index, other.index)
71 def __init__(self, group):
72 self.group = group.group
73 self.weight = group.weight
77 def __init__(self, face):
78 self.index = face.index
80 self.edge_keys = face.edge_keys
81 self.vertices = face.vertices[:]
82 self.loop_indices = face.loop_indices
83 self.normal = face.normal
84 self.use_smooth = face.use_smooth
85 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_edge(self, v1, v2):
99 key = make_edge_key(v1.index, v2.index)
103 raise KeyError("No edge %s"%(key,))
105 def other_edge(self, e, v):
107 if d!=e and v in d.vertices:
110 def get_neighbors(self):
111 neighbors = [e.other_face(self) for e in self.edges]
112 return list(filter(bool, neighbors))
116 def __init__(self, e):
118 self.vertices = e.vertices[:]
123 def __init__(self, arg):
129 self.uvs = [mathutils.Vector(d.uv) for d in arg.data]
134 dot = self.name.find('.')
136 ext = self.name[dot:]
137 if ext.startswith(".unit") and ext[5:].isdigit():
138 self.unit = int(ext[5:])
144 def __init__(self, mesh):
145 self.name = mesh.name
147 self.winding_test = mesh.winding_test
148 self.smoothing = mesh.smoothing
149 self.use_uv = mesh.use_uv
150 self.tbn_vecs = mesh.tbn_vecs
151 self.tbn_uvtex = mesh.tbn_uvtex
152 self.vertex_groups = mesh.vertex_groups
155 self.vertices = [Vertex(v) for v in mesh.vertices]
156 for v in self.vertices:
157 v.groups = [VertexGroup(g) for g in v.groups]
159 self.faces = [Face(f) for f in mesh.polygons]
160 self.edges = [Edge(e) for e in mesh.edges]
161 self.loops = mesh.loops[:]
162 self.materials = mesh.materials[:]
164 self.use_auto_smooth = mesh.use_auto_smooth
165 self.auto_smooth_angle = mesh.auto_smooth_angle
167 # Clone only the desired UV layers
168 if mesh.use_uv=='NONE' or not mesh.uv_layers:
171 self.uv_layers = [UvLayer(u) for u in mesh.uv_layers]
173 # Assign texture unit numbers to UV layers that lack one
174 missing_unit = [u for u in self.uv_layers if u.unit is None]
176 missing_unit = sorted(missing_unit, key=(lambda u: u.name))
177 used_units = [u.unit for u in self.uv_layers if u.unit is not None]
178 for u, n in zip(missing_unit, (i for i in itertools.count() if i not in used_units)):
181 self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
183 if mesh.use_uv=='UNIT0':
184 self.uv_layers = [self.uv_layers[0]]
185 if self.uv_layers[0].unit!=0:
188 # Rewrite links between elements to point to cloned data, or create links
189 # where they don't exist
190 edge_map = {e.key: e for e in self.edges}
192 if len(f.vertices)>4:
193 raise ValueError("Ngons are not supported")
195 f.vertices = [self.vertices[i] for i in f.vertices]
199 for k in f.edge_keys:
205 e.vertices = [self.vertices[i] for i in e.vertices]
209 # Store loose edges as lines
211 self.lines = [Line(e) for e in self.edges if not e.faces]
215 self.vertex_sequence = []
217 def transform(self, matrix):
218 for v in self.vertices:
221 def splice(self, other):
222 if len(self.uv_layers)!=len(other.uv_layers):
223 raise ValueError("Meshes have incompatible UV layers")
224 for i, u in enumerate(self.uv_layers):
225 if u.name!=other.uv_layers[i].name:
226 raise ValueError("Meshes have incompatible UV layers")
228 # Merge materials and form a lookup from source material indices to the
229 # merged material list
231 for m in other.materials:
232 if m in self.materials:
233 material_map.append(self.materials.index(m))
235 material_map.append(len(self.materials))
236 self.materials.append(m)
238 # Append data and adjust indices where necessary. Since the data is
239 # spliced from the source mesh, rebuilding references is not necessary.
240 for i, u in enumerate(self.uv_layers):
241 u.uvs += other.uv_layers[i].uvs
243 offset = len(self.vertices)
244 self.vertices += other.vertices
245 for v in self.vertices[offset:]:
248 loop_offset = len(self.loops)
249 self.loops += other.loops
251 offset = len(self.faces)
252 self.faces += other.faces
253 for f in self.faces[offset:]:
255 f.loop_indices = range(f.loop_indices.start+offset, f.loop_indices.stop+offset)
257 f.material_index = material_map[f.material_index]
259 offset = len(self.edges)
260 self.edges += other.edges
261 for e in self.edges[offset:]:
263 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
265 self.lines += other.lines
267 def prepare_triangles(self, progress):
268 face_count = len(self.faces)
269 for i in range(face_count):
271 nverts = len(f.vertices)
275 # Calculate normals at each vertex of the face
277 for j in range(nverts):
278 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
281 for j in range(nverts):
282 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
284 # Check which diagonal results in a flatter triangulation
285 flatness1 = normals[0].dot(normals[2])
286 flatness2 = normals[1].dot(normals[3])
287 cut_index = 1 if flatness1>flatness2 else 0
290 nf.index = len(self.faces)
291 self.faces.append(nf)
294 ne.index = len(self.edges)
295 self.edges.append(ne)
297 nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
298 nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
299 for v in nf.vertices:
302 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
303 for v in ne.vertices:
305 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
308 f.vertices[3-cut_index].faces.remove(f)
309 del f.vertices[3-cut_index]
310 f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
314 nf.edges = [ne, f.edges[2], f.edges[3]]
315 f.edges = [f.edges[0], f.edges[1], ne]
317 nf.edges = [f.edges[1], f.edges[2], ne]
318 f.edges = [f.edges[0], ne, f.edges[3]]
324 f.normal = normals[1-cut_index]
325 nf.normal = normals[3-cut_index]
327 progress.set_progress(i/face_count)
329 def prepare_smoothing(self, progress):
331 if self.smoothing=='NONE':
336 elif self.use_auto_smooth:
337 smooth_limit = math.cos(self.auto_smooth_angle)
340 e.check_smooth(smooth_limit)
342 progress.push_task("Sharp edges", 0.0, 0.7)
343 self.split_vertices(self.find_smooth_group, progress)
345 if self.smoothing!='BLENDER':
346 progress.set_task("Updating normals", 0.7, 1.0)
347 self.compute_normals(progress)
351 def prepare_vertex_groups(self, obj):
352 for v in self.vertices:
354 weight_sum = sum(g.weight for g in v.groups)
355 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
356 weight_scale = weight_sum/sum(g.weight for g in v.groups)
358 g.weight *= weight_scale
360 if obj.parent and obj.parent.type=="ARMATURE":
361 armature = obj.parent.data
362 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
363 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
364 for g in first_obj.vertex_groups:
365 if g.name in bone_indices:
366 group_index_map[g.index] = bone_indices[g.name]
368 for v in self.vertices:
370 g.group = group_index_map[g.group]
372 def apply_material_map(self, material_map):
373 for m in self.materials:
374 if m.name not in material_map.material_names:
375 raise Exception("Material map is not compatible with Mesh")
377 if self.use_uv=='NONE':
380 layer = UvLayer("material_map")
381 if self.use_uv=='UNIT0':
382 self.uv_layers = [layer]
385 self.uv_layers.append(layer)
386 used_units = [u.unit for u in self.uv_layers]
387 layer.unit = next(i for i in itertools.count() if i not in used_units)
388 self.uv_layers.sort(key=lambda u: u.unit)
390 layer.uvs = [(0.0, 0.0)]*len(self.loops)
392 uv = material_map.get_material_uv(self.materials[f.material_index])
393 for i in f.loop_indices:
396 def prepare_uv(self, progress):
397 # Form a list of UV layers referenced by materials with the array atlas
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]
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
410 for l in array_uv_layers:
411 for i in f.loop_indices:
412 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
414 # Copy UVs from layers to faces
416 for u in self.uv_layers:
417 f.uvs.append([u.uvs[i] for i in f.loop_indices])
419 prog_count = len(self.uv_layers)
422 # Split by the UV layer used for TBN vectors first so connectivity
423 # remains intact for TBN vector computation
426 uv_names = [u.name for u in self.uv_layers]
427 if self.tbn_uvtex in uv_names:
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)
437 raise Exception("TBN UV layer not found")
439 # Split by the remaining UV layers
440 for i, u in enumerate(self.uv_layers):
441 if i==tbn_layer_index:
444 progress.push_task_slice(u.name, prog_step, prog_count)
445 self.split_vertices(self.find_uv_group, progress, i)
449 # Copy UVs from faces to vertices
450 for v in self.vertices:
452 # All faces still connected to the vertex have the same UV value
454 i = f.vertices.index(v)
455 v.uvs = [u[i] for u in f.uvs]
457 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
459 def split_vertices(self, find_group_func, progress, *args):
460 vertex_count = len(self.vertices)
461 for i in range(vertex_count):
466 # Find all groups of faces on this vertex
470 groups.append(find_group_func(v, f, *args))
472 # Give groups after the first separate copies of the vertex
475 nv.index = len(self.vertices)
476 self.vertices.append(nv)
479 e_faces_in_g = [f for f in e.faces if f in g]
483 if len(e_faces_in_g)<len(e.faces):
484 # Create a copy of an edge at the boundary of the group
486 ne.index = len(self.edges)
487 self.edges.append(ne)
489 ne.other_vertex(v).edges.append(ne)
491 for f in e_faces_in_g:
493 f.edges[f.edges.index(e)] = ne
498 e.vertices[e.vertices.index(v)] = nv
501 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
503 # Filter out any edges that were removed from the original vertex
504 v.edges = [e for e in v.edges if v in e.vertices]
508 f.vertices[f.vertices.index(v)] = nv
511 progress.set_progress(i/vertex_count)
513 def find_smooth_group(self, vertex, face):
516 edges = [e for e in face.edges if vertex in e.vertices]
528 e = f.other_edge(e, vertex)
532 def find_uv_group(self, vertex, face, index):
533 uv = face.uvs[index][face.vertices.index(vertex)]
537 for f in vertex.faces:
538 if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
544 def compute_normals(self, progress):
545 for i, v in enumerate(self.vertices):
546 v.normal = mathutils.Vector()
548 vi = f.pivot_vertex(v)
549 edge1 = f.vertices[vi[1]].co-v.co
550 edge2 = f.vertices[vi[-1]].co-v.co
551 if edge1.length and edge2.length:
552 # Use the angle between edges as a weighting factor. This gives
553 # more consistent normals on bends with an inequal number of
554 # faces on each side.
555 v.normal += f.normal*edge1.angle(edge2)
560 v.normal = mathutils.Vector((0, 0, 1))
562 progress.set_progress(i/len(self.vertices))
564 def compute_tbn(self, index, progress):
565 # This function is called at an early stage during UV preparation when
566 # face UVs are not available yet
567 layer_uvs = self.uv_layers[index].uvs
569 for i, v in enumerate(self.vertices):
570 v.tan = mathutils.Vector()
571 v.bino = mathutils.Vector()
573 vi = f.pivot_vertex(v)
574 uv0 = layer_uvs[f.loop_indices[vi[0]]]
575 uv1 = layer_uvs[f.loop_indices[vi[1]]]
576 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
581 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
582 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
583 div = (du1*dv2-du2*dv1)
585 mul = edge1.angle(edge2)/div
586 v.tan += (edge1*dv2-edge2*dv1)*mul
587 v.bino += (edge2*du1-edge1*du2)*mul
594 progress.set_progress(i/len(self.vertices))
596 def prepare_sequence(self, progress):
597 progress.push_task("Reordering faces", 0.0, 0.5)
598 self.reorder_faces(progress)
600 progress.set_task("Building sequence", 0.5, 1.0)
602 for i, f in enumerate(self.faces):
605 # Rotate the first three vertices so that the new face can be added
606 if sequence[0] in f.vertices and sequence[1] not in f.vertices:
607 sequence.append(sequence[0])
609 elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
610 sequence.insert(0, sequence[-1])
613 if sequence[-1] not in f.vertices:
616 to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
618 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
620 sequence.append(sequence[-1])
624 sequence = f.vertices[:]
625 self.vertex_sequence.append(sequence)
627 progress.set_progress(i/len(self.faces))
631 self.reorder_vertices()
633 def reorder_faces(self, progress):
634 # Tom Forsyth's vertex cache optimization algorithm
635 # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
640 last_triangle_score = 0.75
641 cache_decay_power = 1.5
642 valence_boost_scale = 2.0
643 valence_boost_power = -0.5
648 # Keep track of the score and number of unused faces for each vertex
649 vertex_info = [[0, len(v.faces)] for v in self.vertices]
650 for vi in vertex_info:
651 vi[0] = valence_boost_scale*(vi[1]**valence_boost_power)
659 # Previous iteration gave no candidate for best face (or this is
660 # the first iteration). Scan all faces for the highest score.
666 score = sum(vertex_info[v.index][0] for v in f.vertices)
674 reordered_faces.append(face)
677 for v in face.vertices:
678 vertex_info[v.index][1] -= 1
680 # Shuffle the vertex into the front of the cache
681 if v in cached_vertices:
682 cached_vertices.remove(v)
683 cached_vertices.insert(0, v)
685 # Update scores for all vertices in the cache
686 for i, v in enumerate(cached_vertices):
689 score += last_triangle_score
690 elif i<max_cache_size:
691 score += (1-(i-3)/(max_cache_size-3))**cache_decay_power
692 if vertex_info[v.index][1]:
693 score += valence_boost_scale*(vertex_info[v.index][1]**valence_boost_power)
694 vertex_info[v.index][0] = score
698 for v in cached_vertices:
701 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
706 del cached_vertices[max_cache_size:]
709 progress.set_progress(n_processed/len(self.faces))
711 self.faces = reordered_faces
712 for i, f in enumerate(self.faces):
715 def reorder_vertices(self):
716 for v in self.vertices:
719 reordered_vertices = []
720 for s in self.vertex_sequence:
723 v.index = len(reordered_vertices)
724 reordered_vertices.append(v)
726 self.vertices = reordered_vertices
729 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
732 def create_mesh_from_object(context, obj, progress, *, material_map=None):
734 raise Exception("Object is not a mesh")
736 progress.push_task("Preparing mesh", 0.0, 0.2)
738 objs = [(obj, mathutils.Matrix())]
744 if c.type=="MESH" and c.compound:
745 objs.append((c, m*c.matrix_local))
747 dg = context.evaluated_depsgraph_get()
751 eval_obj = o.evaluated_get(dg)
752 bmesh = eval_obj.to_mesh()
754 # Object.to_mesh does not copy custom properties
755 bmesh.winding_test = o.data.winding_test
756 bmesh.smoothing = o.data.smoothing
757 bmesh.use_lines = o.data.use_lines
758 bmesh.vertex_groups = o.data.vertex_groups
759 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
760 bmesh.use_uv = o.data.use_uv
761 bmesh.tbn_vecs = o.data.tbn_vecs
762 bmesh.tbn_uvtex = o.data.tbn_uvtex
767 for i, s in enumerate(eval_obj.material_slots):
769 me.materials[i] = s.material
776 mesh.name = obj.data.name
779 mesh.apply_material_map(material_map)
781 progress.set_task("Triangulating", 0.2, 0.3)
782 mesh.prepare_triangles(progress)
783 progress.set_task("Smoothing", 0.3, 0.5)
784 mesh.prepare_smoothing(progress)
785 progress.set_task("Vertex groups", 0.5, 0.6)
786 mesh.prepare_vertex_groups(obj)
787 progress.set_task("Preparing UVs", 0.6, 0.8)
788 mesh.prepare_uv(progress)
789 progress.set_task("Render sequence", 0.8, 1.0)
790 mesh.prepare_sequence(progress)