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
88 def __cmp__(self, other):
91 return cmp(self.index, other.index)
93 def pivot_vertex(self, v):
94 n = self.vertices.index(v)
95 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
97 def get_loop_index(self, v):
98 return self.loop_indices[self.vertices.index(v)]
100 def get_edge(self, v1, v2):
101 key = make_edge_key(v1.index, v2.index)
105 raise KeyError("No edge %s"%(key,))
107 def other_edge(self, e, v):
109 if d!=e and v in d.vertices:
112 def get_neighbors(self):
113 neighbors = [e.other_face(self) for e in self.edges]
114 return list(filter(bool, neighbors))
118 def __init__(self, e):
120 self.vertices = e.vertices[:]
125 def __init__(self, arg):
131 self.uvs = [mathutils.Vector(d.uv) for d in arg.data]
136 dot = self.name.find('.')
138 ext = self.name[dot:]
139 if ext.startswith(".unit") and ext[5:].isdigit():
140 self.unit = int(ext[5:])
146 def __init__(self, mesh):
147 self.name = mesh.name
149 self.winding_test = mesh.winding_test
150 self.smoothing = mesh.smoothing
151 self.use_uv = mesh.use_uv
152 self.tbn_vecs = mesh.tbn_vecs
153 self.tbn_uvtex = mesh.tbn_uvtex
154 self.vertex_groups = mesh.vertex_groups
157 self.vertices = [Vertex(v) for v in mesh.vertices]
158 for v in self.vertices:
159 v.groups = [VertexGroup(g) for g in v.groups]
161 self.faces = [Face(f) for f in mesh.polygons]
162 self.edges = [Edge(e) for e in mesh.edges]
163 self.loops = mesh.loops[:]
164 self.materials = mesh.materials[:]
166 self.use_auto_smooth = mesh.use_auto_smooth
167 self.auto_smooth_angle = mesh.auto_smooth_angle
169 # Clone only the desired UV layers
170 if mesh.use_uv=='NONE' or not mesh.uv_layers:
173 self.uv_layers = [UvLayer(u) for u in mesh.uv_layers]
175 # Assign texture unit numbers to UV layers that lack one
176 missing_unit = [u for u in self.uv_layers if u.unit is None]
178 missing_unit = sorted(missing_unit, key=(lambda u: u.name))
179 used_units = [u.unit for u in self.uv_layers if u.unit is not None]
180 for u, n in zip(missing_unit, (i for i in itertools.count() if i not in used_units)):
183 self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
185 if mesh.use_uv=='UNIT0':
186 self.uv_layers = [self.uv_layers[0]]
187 if self.uv_layers[0].unit!=0:
190 # Rewrite links between elements to point to cloned data, or create links
191 # where they don't exist
192 edge_map = {e.key: e for e in self.edges}
194 if len(f.vertices)>4:
195 raise ValueError("Ngons are not supported")
197 f.vertices = [self.vertices[i] for i in f.vertices]
201 for k in f.edge_keys:
207 e.vertices = [self.vertices[i] for i in e.vertices]
211 # Store loose edges as lines
213 self.lines = [Line(e) for e in self.edges if not e.faces]
217 self.vertex_sequence = []
219 def transform(self, matrix):
220 for v in self.vertices:
223 def splice(self, other):
224 if len(self.uv_layers)!=len(other.uv_layers):
225 raise ValueError("Meshes have incompatible UV layers")
226 for i, u in enumerate(self.uv_layers):
227 if u.name!=other.uv_layers[i].name:
228 raise ValueError("Meshes have incompatible UV layers")
230 # Merge materials and form a lookup from source material indices to the
231 # merged material list
233 for m in other.materials:
234 if m in self.materials:
235 material_map.append(self.materials.index(m))
237 material_map.append(len(self.materials))
238 self.materials.append(m)
240 # Append data and adjust indices where necessary. Since the data is
241 # spliced from the source mesh, rebuilding references is not necessary.
242 for i, u in enumerate(self.uv_layers):
243 u.uvs += other.uv_layers[i].uvs
245 offset = len(self.vertices)
246 self.vertices += other.vertices
247 for v in self.vertices[offset:]:
250 loop_offset = len(self.loops)
251 self.loops += other.loops
253 offset = len(self.faces)
254 self.faces += other.faces
255 for f in self.faces[offset:]:
257 f.loop_indices = range(f.loop_indices.start+offset, f.loop_indices.stop+offset)
259 f.material_index = material_map[f.material_index]
261 offset = len(self.edges)
262 self.edges += other.edges
263 for e in self.edges[offset:]:
265 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
267 self.lines += other.lines
269 def prepare_triangles(self, progress):
270 face_count = len(self.faces)
271 for i in range(face_count):
273 nverts = len(f.vertices)
277 # Calculate normals at each vertex of the face
279 for j in range(nverts):
280 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
283 for j in range(nverts):
284 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
286 # Check which diagonal results in a flatter triangulation
287 flatness1 = normals[0].dot(normals[2])
288 flatness2 = normals[1].dot(normals[3])
289 cut_index = 1 if flatness1>flatness2 else 0
292 nf.index = len(self.faces)
293 self.faces.append(nf)
296 ne.index = len(self.edges)
297 self.edges.append(ne)
299 nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
300 nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
301 for v in nf.vertices:
304 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
305 for v in ne.vertices:
307 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
310 f.vertices[3-cut_index].faces.remove(f)
311 del f.vertices[3-cut_index]
312 f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
316 nf.edges = [ne, f.edges[2], f.edges[3]]
317 f.edges = [f.edges[0], f.edges[1], ne]
319 nf.edges = [f.edges[1], f.edges[2], ne]
320 f.edges = [f.edges[0], ne, f.edges[3]]
326 f.normal = normals[1-cut_index]
327 nf.normal = normals[3-cut_index]
329 progress.set_progress(i/face_count)
331 def prepare_smoothing(self, progress):
333 if self.smoothing=='NONE':
338 elif self.use_auto_smooth:
339 smooth_limit = math.cos(self.auto_smooth_angle)
342 e.check_smooth(smooth_limit)
344 progress.push_task("Sharp edges", 0.0, 0.7)
345 self.split_vertices(self.find_smooth_group, progress)
347 if self.smoothing!='BLENDER':
348 progress.set_task("Updating normals", 0.7, 1.0)
349 self.compute_normals(progress)
353 def prepare_vertex_groups(self, obj):
354 for v in self.vertices:
356 weight_sum = sum(g.weight for g in v.groups)
357 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
358 weight_scale = weight_sum/sum(g.weight for g in v.groups)
360 g.weight *= weight_scale
362 if obj.parent and obj.parent.type=="ARMATURE":
363 armature = obj.parent.data
364 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
365 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
366 for g in first_obj.vertex_groups:
367 if g.name in bone_indices:
368 group_index_map[g.index] = bone_indices[g.name]
370 for v in self.vertices:
372 g.group = group_index_map[g.group]
374 def apply_material_map(self, material_map):
375 for m in self.materials:
376 if m.name not in material_map.material_names:
377 raise Exception("Material map is not compatible with Mesh")
379 if self.use_uv=='NONE':
382 layer = UvLayer("material_map")
383 if self.use_uv=='UNIT0':
384 self.uv_layers = [layer]
387 self.uv_layers.append(layer)
388 used_units = [u.unit for u in self.uv_layers]
389 layer.unit = next(i for i in itertools.count() if i not in used_units)
390 self.uv_layers.sort(key=lambda u: u.unit)
392 layer.uvs = [(0.0, 0.0)]*len(self.loops)
394 uv = material_map.get_material_uv(self.materials[f.material_index])
395 for i in f.loop_indices:
398 def prepare_uv(self, progress):
399 # Form a list of UV layers referenced by materials with the array atlas
401 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']
402 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
407 if f.material_index<len(self.materials):
408 mat = self.materials[f.material_index]
409 if mat and mat.array_atlas:
410 layer = mat.array_layer
412 for l in array_uv_layers:
413 for i in f.loop_indices:
414 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
416 prog_count = len(self.uv_layers)
419 # Split by the UV layer used for TBN vectors first so connectivity
420 # remains intact for TBN vector computation
423 uv_names = [u.name for u in self.uv_layers]
424 if self.tbn_uvtex in uv_names:
426 tbn_layer_index = uv_names.index(self.tbn_uvtex)
427 progress.push_task_slice("Computing TBN", 0, prog_count)
428 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
429 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
430 self.compute_tbn(tbn_layer_index, progress)
434 raise Exception("TBN UV layer not found")
436 # Split by the remaining UV layers
437 for i, u in enumerate(self.uv_layers):
438 if i==tbn_layer_index:
441 progress.push_task_slice(u.name, prog_step, prog_count)
442 self.split_vertices(self.find_uv_group, progress, i)
446 # Copy UVs from layers to vertices
447 for v in self.vertices:
449 # All faces still connected to the vertex have the same UV value
451 i = f.get_loop_index(v)
452 v.uvs = [u.uvs[i] for u in self.uv_layers]
454 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
456 def split_vertices(self, find_group_func, progress, *args):
457 vertex_count = len(self.vertices)
458 for i in range(vertex_count):
463 # Find all groups of faces on this vertex
467 groups.append(find_group_func(v, f, *args))
469 # Give groups after the first separate copies of the vertex
472 nv.index = len(self.vertices)
473 self.vertices.append(nv)
476 e_faces_in_g = [f for f in e.faces if f in g]
480 if len(e_faces_in_g)<len(e.faces):
481 # Create a copy of an edge at the boundary of the group
483 ne.index = len(self.edges)
484 self.edges.append(ne)
486 ne.other_vertex(v).edges.append(ne)
488 for f in e_faces_in_g:
490 f.edges[f.edges.index(e)] = ne
495 e.vertices[e.vertices.index(v)] = nv
498 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
500 # Filter out any edges that were removed from the original vertex
501 v.edges = [e for e in v.edges if v in e.vertices]
505 f.vertices[f.vertices.index(v)] = nv
508 progress.set_progress(i/vertex_count)
510 def find_smooth_group(self, vertex, face):
513 edges = [e for e in face.edges if vertex in e.vertices]
525 e = f.other_edge(e, vertex)
529 def find_uv_group(self, vertex, face, index):
530 layer = self.uv_layers[index]
531 uv = layer.uvs[face.get_loop_index(vertex)]
535 for f in vertex.faces:
536 if not f.flag and layer.uvs[f.get_loop_index(vertex)]==uv:
542 def compute_normals(self, progress):
543 for i, v in enumerate(self.vertices):
544 v.normal = mathutils.Vector()
546 vi = f.pivot_vertex(v)
547 edge1 = f.vertices[vi[1]].co-v.co
548 edge2 = f.vertices[vi[-1]].co-v.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)
558 v.normal = mathutils.Vector((0, 0, 1))
560 progress.set_progress(i/len(self.vertices))
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
567 for i, v in enumerate(self.vertices):
568 v.tan = mathutils.Vector()
569 v.bino = mathutils.Vector()
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]]]
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)
583 mul = edge1.angle(edge2)/div
584 v.tan += (edge1*dv2-edge2*dv1)*mul
585 v.bino += (edge2*du1-edge1*du2)*mul
592 progress.set_progress(i/len(self.vertices))
594 def prepare_sequence(self, progress):
595 progress.push_task("Reordering faces", 0.0, 0.5)
596 self.reorder_faces(progress)
598 progress.set_task("Building sequence", 0.5, 1.0)
600 for i, f in enumerate(self.faces):
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])
607 elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
608 sequence.insert(0, sequence[-1])
611 if sequence[-1] not in f.vertices:
614 to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
616 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
618 sequence.append(sequence[-1])
622 sequence = f.vertices[:]
623 self.vertex_sequence.append(sequence)
625 progress.set_progress(i/len(self.faces))
629 self.reorder_vertices()
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
638 last_triangle_score = 0.75
639 cache_decay_power = 1.5
640 valence_boost_scale = 2.0
641 valence_boost_power = -0.5
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)
657 # Previous iteration gave no candidate for best face (or this is
658 # the first iteration). Scan all faces for the highest score.
664 score = sum(vertex_info[v.index][0] for v in f.vertices)
672 reordered_faces.append(face)
675 for v in face.vertices:
676 vertex_info[v.index][1] -= 1
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)
683 # Update scores for all vertices in the cache
684 for i, v in enumerate(cached_vertices):
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
696 for v in cached_vertices:
699 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
704 del cached_vertices[max_cache_size:]
707 progress.set_progress(n_processed/len(self.faces))
709 self.faces = reordered_faces
710 for i, f in enumerate(self.faces):
713 def reorder_vertices(self):
714 for v in self.vertices:
717 reordered_vertices = []
718 for s in self.vertex_sequence:
721 v.index = len(reordered_vertices)
722 reordered_vertices.append(v)
724 self.vertices = reordered_vertices
727 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
730 def create_mesh_from_object(context, obj, progress, *, material_map=None):
732 raise Exception("Object is not a mesh")
734 progress.push_task("Preparing mesh", 0.0, 0.2)
736 objs = [(obj, mathutils.Matrix())]
742 if c.type=="MESH" and c.compound:
743 objs.append((c, m*c.matrix_local))
745 dg = context.evaluated_depsgraph_get()
749 eval_obj = o.evaluated_get(dg)
750 bmesh = eval_obj.to_mesh()
752 # Object.to_mesh does not copy custom properties
753 bmesh.winding_test = o.data.winding_test
754 bmesh.smoothing = o.data.smoothing
755 bmesh.use_lines = o.data.use_lines
756 bmesh.vertex_groups = o.data.vertex_groups
757 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
758 bmesh.use_uv = o.data.use_uv
759 bmesh.tbn_vecs = o.data.tbn_vecs
760 bmesh.tbn_uvtex = o.data.tbn_uvtex
765 for i, s in enumerate(eval_obj.material_slots):
767 me.materials[i] = s.material
774 mesh.name = obj.data.name
777 mesh.apply_material_map(material_map)
779 progress.set_task("Triangulating", 0.2, 0.3)
780 mesh.prepare_triangles(progress)
781 progress.set_task("Smoothing", 0.3, 0.5)
782 mesh.prepare_smoothing(progress)
783 progress.set_task("Vertex groups", 0.5, 0.6)
784 mesh.prepare_vertex_groups(obj)
785 progress.set_task("Preparing UVs", 0.6, 0.8)
786 mesh.prepare_uv(progress)
787 progress.set_task("Render sequence", 0.8, 1.0)
788 mesh.prepare_sequence(progress)