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[:]
54 self.index = vertex.index
55 self.co = mathutils.Vector(vertex.co)
56 self.normal = mathutils.Vector(vertex.normal)
61 self.groups = vertex.groups[:]
63 def __cmp__(self, other):
66 return cmp(self.index, other.index)
70 def __init__(self, group):
72 self.group = group.group
73 self.weight = group.weight
80 def __init__(self, face):
81 self.index = face.index
83 self.edge_keys = face.edge_keys
84 self.vertices = face.vertices[:]
85 self.loop_indices = face.loop_indices
86 self.normal = face.normal
87 self.use_smooth = face.use_smooth
88 self.material_index = face.material_index
91 def __cmp__(self, other):
94 return cmp(self.index, other.index)
96 def pivot_vertex(self, v):
97 n = self.vertices.index(v)
98 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
100 def get_loop_index(self, v):
101 return self.loop_indices[self.vertices.index(v)]
103 def get_edge(self, v1, v2):
104 key = make_edge_key(v1.index, v2.index)
108 raise KeyError("No edge %s"%(key,))
110 def other_edge(self, e, v):
112 if d!=e and v in d.vertices:
115 def get_neighbors(self):
116 neighbors = [e.other_face(self) for e in self.edges]
117 return list(filter(bool, neighbors))
121 def __init__(self, e):
123 self.vertices = e.vertices[:]
128 def __init__(self, arg):
134 self.uvs = [mathutils.Vector(d.uv) for d in arg.data]
139 dot = self.name.find('.')
141 ext = self.name[dot:]
142 if ext.startswith(".unit") and ext[5:].isdigit():
143 self.unit = int(ext[5:])
149 def __init__(self, l):
151 self.colors = [c.color[:] for c in l.data]
155 def __init__(self, mesh):
156 self.name = mesh.name
158 self.winding_test = mesh.winding_test
159 self.smoothing = mesh.smoothing
160 self.use_uv = mesh.use_uv
161 self.tangent_uvtex = mesh.tangent_uvtex
162 self.use_strips = mesh.use_strips
163 self.vertex_groups = mesh.vertex_groups
166 self.vertices = [Vertex(v) for v in mesh.vertices]
167 if self.vertex_groups:
168 for v in self.vertices:
169 v.groups = [VertexGroup(g) for g in v.groups]
171 self.faces = [Face(f) for f in mesh.polygons]
172 self.edges = [Edge(e) for e in mesh.edges]
173 self.loops = mesh.loops[:]
174 self.materials = mesh.materials[:]
176 self.use_auto_smooth = mesh.use_auto_smooth
177 self.auto_smooth_angle = mesh.auto_smooth_angle
178 self.max_groups_per_vertex = mesh.max_groups_per_vertex
180 # Clone only the desired UV layers
181 if mesh.use_uv=='NONE' or not mesh.uv_layers:
184 self.uv_layers = [UvLayer(u) for u in mesh.uv_layers if u.data]
186 # Assign texture unit numbers to UV layers that lack one
187 missing_unit = [u for u in self.uv_layers if u.unit is None]
189 missing_unit = sorted(missing_unit, key=(lambda u: u.name))
190 used_units = [u.unit for u in self.uv_layers if u.unit is not None]
191 for u, n in zip(missing_unit, (i for i in itertools.count() if i not in used_units)):
194 self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
196 if mesh.use_uv=='UNIT0' and self.uv_layers:
197 self.uv_layers = [self.uv_layers[0]]
198 if self.uv_layers[0].unit!=0:
202 if mesh.vertex_colors:
203 self.colors = ColorLayer(mesh.vertex_colors[0])
205 # Rewrite links between elements to point to cloned data, or create links
206 # where they don't exist
207 edge_map = {e.key: e for e in self.edges}
209 if len(f.vertices)>4:
210 raise ValueError("Unsupported face on mesh {}: N-gon".format(self.name))
212 f.vertices = [self.vertices[i] for i in f.vertices]
216 for k in f.edge_keys:
222 e.vertices = [self.vertices[i] for i in e.vertices]
226 # Store loose edges as lines
228 self.lines = [Line(e) for e in self.edges if not e.faces]
232 # Check if tangent vectors are needed
233 if mesh.tangent_vecs=='NO':
234 self.tangent_vecs = False
235 elif mesh.tangent_vecs=='YES':
236 self.tangent_vecs = True
237 elif mesh.tangent_vecs=='AUTO':
238 from .material import Material
239 self.tangent_vecs = False
240 for m in self.materials:
243 normal_prop = next((p for p in mat.properties if p.tex_keyword=="normal_map"), None)
244 if normal_prop and normal_prop.texture:
245 self.tangent_vecs = True
247 self.vertex_sequence = []
249 def transform(self, matrix):
250 for v in self.vertices:
253 def splice(self, other):
254 if len(self.uv_layers)!=len(other.uv_layers):
255 raise ValueError("Meshes {} and {} have incompatible UV layers".format(self.name, other.name))
256 for i, u in enumerate(self.uv_layers):
257 if u.name!=other.uv_layers[i].name:
258 raise ValueError("Meshes {} and {} have incompatible UV layers".format(self.name, other.name))
260 # Merge materials and form a lookup from source material indices to the
261 # merged material list
263 for m in other.materials:
264 if m in self.materials:
265 material_atlas.append(self.materials.index(m))
267 material_atlas.append(len(self.materials))
268 self.materials.append(m)
270 # Append data and adjust indices where necessary. Since the data is
271 # spliced from the source mesh, rebuilding references is not necessary.
272 for i, u in enumerate(self.uv_layers):
273 u.uvs += other.uv_layers[i].uvs
277 self.colors.colors += other.colors.colors
279 self.colors.colors += [(1.0, 1.0, 1.0, 1.0)]*len(other.loops)
281 self.colors = ColorLayer(other.colors.name)
282 self.colors.colors = [(1.0, 1.0, 1.0, 1.0)]*len(self.loops)+other.colors.colors
284 offset = len(self.vertices)
285 self.vertices += other.vertices
286 for v in self.vertices[offset:]:
289 loop_offset = len(self.loops)
290 self.loops += other.loops
292 offset = len(self.faces)
293 self.faces += other.faces
294 for f in self.faces[offset:]:
296 f.loop_indices = range(f.loop_indices.start+offset, f.loop_indices.stop+offset)
298 f.material_index = material_atlas[f.material_index]
300 offset = len(self.edges)
301 self.edges += other.edges
302 for e in self.edges[offset:]:
304 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
306 self.lines += other.lines
308 def prepare_triangles(self, task):
309 face_count = len(self.faces)
310 for i in range(face_count):
312 nverts = len(f.vertices)
316 # Calculate normals at each vertex of the face
318 for j in range(nverts):
319 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
322 for j in range(nverts):
323 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
325 # Check which diagonal results in a flatter triangulation
326 flatness1 = normals[0].dot(normals[2])
327 flatness2 = normals[1].dot(normals[3])
328 cut_index = 1 if flatness1>flatness2 else 0
331 nf.index = len(self.faces)
332 self.faces.append(nf)
335 ne.index = len(self.edges)
336 self.edges.append(ne)
338 nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
339 nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
340 for v in nf.vertices:
343 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
344 for v in ne.vertices:
346 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
349 f.vertices[3-cut_index].faces.remove(f)
350 del f.vertices[3-cut_index]
351 f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
355 nf.edges = [ne, f.edges[2], f.edges[3]]
356 f.edges = [f.edges[0], f.edges[1], ne]
358 nf.edges = [f.edges[1], f.edges[2], ne]
359 f.edges = [f.edges[0], ne, f.edges[3]]
365 f.normal = normals[1-cut_index]
366 nf.normal = normals[3-cut_index]
368 task.set_progress(i/face_count)
370 def prepare_smoothing(self, task):
372 if self.smoothing=='NONE':
377 elif self.use_auto_smooth:
378 smooth_limit = math.cos(self.auto_smooth_angle)
381 e.check_smooth(smooth_limit)
383 subtask = task.task("Sharp edges", 0.7)
384 self.split_vertices(self.find_smooth_group, subtask)
386 if self.smoothing!='BLENDER':
387 subtask = task.task("Updating normals", 1.0)
388 self.compute_normals(subtask)
390 def prepare_vertex_groups(self, obj):
391 if not self.vertex_groups:
394 for v in self.vertices:
396 weight_sum = sum(g.weight for g in v.groups)
397 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
398 weight_scale = weight_sum/sum(g.weight for g in v.groups)
400 g.weight *= weight_scale
401 while len(v.groups)<self.max_groups_per_vertex:
402 v.groups.append(VertexGroup(None))
404 if obj.parent and obj.parent.type=="ARMATURE":
405 armature = obj.parent.data
406 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
407 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
408 for g in first_obj.vertex_groups:
409 if g.name in bone_indices:
410 group_index_map[g.index] = bone_indices[g.name]
412 for v in self.vertices:
414 g.group = group_index_map[g.group]
416 def apply_material_atlas(self, material_atlas):
417 for m in self.materials:
418 if m.name not in material_atlas.material_names:
419 raise Exception("Material atlas {} is not compatible with Mesh {}".format(material_atlas.name, self.name))
421 if self.use_uv=='NONE':
424 layer = UvLayer("material_atlas")
425 if self.use_uv=='UNIT0':
426 self.uv_layers = [layer]
429 self.uv_layers.append(layer)
430 used_units = [u.unit for u in self.uv_layers]
431 layer.unit = next(i for i in itertools.count() if i not in used_units)
432 self.uv_layers.sort(key=lambda u: u.unit)
434 layer.uvs = [(0.0, 0.0)]*len(self.loops)
436 uv = material_atlas.get_material_uv(self.materials[f.material_index])
437 for i in f.loop_indices:
440 def prepare_uv(self, task):
441 # Form a list of UV layers referenced by materials with the array atlas
443 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']
444 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
449 if f.material_index<len(self.materials):
450 mat = self.materials[f.material_index]
451 if mat and mat.array_atlas:
452 layer = mat.array_layer
454 for l in array_uv_layers:
455 for i in f.loop_indices:
456 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
458 # Split by the UV layer used for tangent vectors first so connectivity
459 # remains intact for tangent vector computation
460 tangent_layer_index = -1
461 if self.tangent_vecs:
462 if self.tangent_uvtex:
463 uv_names = [u.name for u in self.uv_layers]
464 if self.tangent_uvtex in uv_names:
465 tangent_layer_index = uv_names.index(self.tangent_uvtex)
466 elif self.uv_layers[0].unit==0:
467 tangent_layer_index = 0
469 if tangent_layer_index<0:
470 raise Exception("Invalid configuration on mesh {}: No tangent UV layer".format(self.name))
472 prog_count = len(self.uv_layers)
473 if tangent_layer_index>=0:
475 task.set_slices(prog_count)
477 if tangent_layer_index>=0:
478 subtask = task.next_slice("Computing tangents")
479 self.split_vertices(self.find_uv_group, subtask, tangent_layer_index)
480 subtask = task.next_slice(self.tangent_uvtex)
481 self.compute_tangents(tangent_layer_index, subtask)
483 # Split by the remaining UV layers
484 for i, u in enumerate(self.uv_layers):
485 if i==tangent_layer_index:
488 subtask = task.next_slice(u.name)
489 self.split_vertices(self.find_uv_group, subtask, i)
491 # Copy UVs from layers to vertices
492 for v in self.vertices:
494 # All faces still connected to the vertex have the same UV value
496 i = f.get_loop_index(v)
497 v.uvs = [u.uvs[i] for u in self.uv_layers]
499 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
501 def prepare_colors(self, task):
505 self.split_vertices(self.find_color_group, task)
507 for v in self.vertices:
510 v.color = self.colors.colors[f.get_loop_index(v)]
512 v.color = (1.0, 1.0, 1.0, 1.0)
514 def split_vertices(self, find_group_func, task, *args):
515 vertex_count = len(self.vertices)
516 for i in range(vertex_count):
521 # Find all groups of faces on this vertex
525 groups.append(find_group_func(v, f, *args))
527 # Give groups after the first separate copies of the vertex
530 nv.index = len(self.vertices)
531 self.vertices.append(nv)
534 e_faces_in_g = [f for f in e.faces if f in g]
538 if len(e_faces_in_g)<len(e.faces):
539 # Create a copy of an edge at the boundary of the group
541 ne.index = len(self.edges)
542 self.edges.append(ne)
544 ne.other_vertex(v).edges.append(ne)
546 for f in e_faces_in_g:
548 f.edges[f.edges.index(e)] = ne
553 e.vertices[e.vertices.index(v)] = nv
556 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
558 # Filter out any edges that were removed from the original vertex
559 v.edges = [e for e in v.edges if v in e.vertices]
563 f.vertices[f.vertices.index(v)] = nv
566 task.set_progress(i/vertex_count)
568 def find_smooth_group(self, vertex, face):
571 edges = [e for e in face.edges if vertex in e.vertices]
583 e = f.other_edge(e, vertex)
587 def find_uv_group(self, vertex, face, index):
588 layer = self.uv_layers[index]
589 uv = layer.uvs[face.get_loop_index(vertex)]
593 for f in vertex.faces:
594 if not f.flag and layer.uvs[f.get_loop_index(vertex)]==uv:
600 def find_color_group(self, vertex, face):
601 color = self.colors.colors[face.get_loop_index(vertex)]
605 for f in vertex.faces:
606 if not f.flag and self.colors.colors[f.get_loop_index(vertex)]==color:
612 def compute_normals(self, task):
613 for i, v in enumerate(self.vertices):
614 v.normal = mathutils.Vector()
616 vi = f.pivot_vertex(v)
617 edge1 = f.vertices[vi[1]].co-v.co
618 edge2 = f.vertices[vi[-1]].co-v.co
619 if edge1.length and edge2.length:
620 # Use the angle between edges as a weighting factor. This gives
621 # more consistent normals on bends with an inequal number of
622 # faces on each side.
623 v.normal += f.normal*edge1.angle(edge2)
628 v.normal = mathutils.Vector((0, 0, 1))
630 task.set_progress(i/len(self.vertices))
632 def compute_tangents(self, index, task):
633 layer_uvs = self.uv_layers[index].uvs
635 for i, v in enumerate(self.vertices):
636 v.tan = mathutils.Vector()
638 vi = f.pivot_vertex(v)
639 uv0 = layer_uvs[f.loop_indices[vi[0]]]
640 uv1 = layer_uvs[f.loop_indices[vi[1]]]
641 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
646 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
647 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
648 div = (du1*dv2-du2*dv1)
650 mul = edge1.angle(edge2)/div
651 v.tan += (edge1*dv2-edge2*dv1)*mul
656 task.set_progress(i/len(self.vertices))
658 def prepare_sequence(self, task):
659 subtask = task.task("Reordering faces", 0.5)
660 self.reorder_faces(subtask)
662 subtask = task.task("Building sequence", 1.0)
664 for i, f in enumerate(self.faces):
667 # Rotate the first three vertices so that the new face can be added
668 if sequence[0] in f.vertices and sequence[1] not in f.vertices:
669 sequence.append(sequence[0])
671 elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
672 sequence.insert(0, sequence[-1])
675 if sequence[-1] not in f.vertices:
678 to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
680 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
682 sequence.append(sequence[-1])
686 sequence = f.vertices[:]
687 self.vertex_sequence.append(sequence)
689 subtask.set_progress(i/len(self.faces))
691 self.reorder_vertices()
693 def reorder_faces(self, task):
694 # Tom Forsyth's vertex cache optimization algorithm
695 # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
700 last_triangle_score = 0.75
701 cache_decay_power = 1.5
702 valence_boost_scale = 2.0
703 valence_boost_power = -0.5
708 # Keep track of the score and number of unused faces for each vertex
709 vertex_info = [[0, len(v.faces)] for v in self.vertices]
710 for vi in vertex_info:
712 vi[0] = valence_boost_scale*(vi[1]**valence_boost_power)
720 # Previous iteration gave no candidate for best face (or this is
721 # the first iteration). Scan all faces for the highest score.
727 score = sum(vertex_info[v.index][0] for v in f.vertices)
735 reordered_faces.append(face)
738 for v in face.vertices:
739 vertex_info[v.index][1] -= 1
741 # Shuffle the vertex into the front of the cache
742 if v in cached_vertices:
743 cached_vertices.remove(v)
744 cached_vertices.insert(0, v)
746 # Update scores for all vertices in the cache
747 for i, v in enumerate(cached_vertices):
750 score += last_triangle_score
751 elif i<max_cache_size:
752 score += (1-(i-3)/(max_cache_size-3))**cache_decay_power
753 if vertex_info[v.index][1]:
754 score += valence_boost_scale*(vertex_info[v.index][1]**valence_boost_power)
755 vertex_info[v.index][0] = score
759 for v in cached_vertices:
762 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
767 del cached_vertices[max_cache_size:]
770 task.set_progress(n_processed/len(self.faces))
772 self.faces = reordered_faces
773 for i, f in enumerate(self.faces):
776 def reorder_vertices(self):
777 for v in self.vertices:
780 reordered_vertices = []
781 for s in self.vertex_sequence:
784 v.index = len(reordered_vertices)
785 reordered_vertices.append(v)
787 for v in self.vertices:
789 v.index = len(reordered_vertices)
790 reordered_vertices.append(v)
792 self.vertices = reordered_vertices
795 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
798 def create_mesh_from_object(ctx, obj, material_atlas):
800 raise Exception("Object {} is not a mesh".format(obj.name))
802 task = ctx.task("Collecting mesh data", 0.2)
804 objs = [(obj, mathutils.Matrix())]
810 if c.type=="MESH" and c.compound:
811 objs.append((c, m*c.matrix_local))
813 dg = ctx.context.evaluated_depsgraph_get()
817 eval_obj = o.evaluated_get(dg)
818 bmesh = eval_obj.to_mesh()
820 # Object.to_mesh does not copy custom properties
821 bmesh.winding_test = o.data.winding_test
822 bmesh.smoothing = o.data.smoothing
823 bmesh.use_lines = o.data.use_lines
824 bmesh.vertex_groups = o.data.vertex_groups
825 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
826 bmesh.use_uv = o.data.use_uv
827 bmesh.tangent_vecs = o.data.tangent_vecs
828 bmesh.tangent_uvtex = o.data.tangent_uvtex
833 for i, s in enumerate(eval_obj.material_slots):
835 me.materials[i] = s.material
842 mesh.name = obj.data.name
845 mesh.apply_material_atlas(material_atlas)
847 task = ctx.task("Triangulating", 0.3)
848 mesh.prepare_triangles(task)
849 task = ctx.task("Smoothing", 0.5)
850 mesh.prepare_smoothing(task)
851 task = ctx.task("Vertex groups", 0.6)
852 mesh.prepare_vertex_groups(obj)
853 task = ctx.task("Preparing UVs", 0.75)
854 mesh.prepare_uv(task)
855 task = ctx.task("Preparing vertex colors", 0.85)
856 mesh.prepare_colors(task)
857 task = ctx.task("Render sequence", 1.0)
858 mesh.prepare_sequence(task)