5 def make_edge_key(i1, i2):
6 return (min(i1, i2), max(i1, i2))
9 def __init__(self, edge):
10 if edge.__class__==Edge:
11 self.smooth = edge.smooth
15 self.vertices = edge.vertices[:]
22 def check_smooth(self, limit):
23 if len(self.faces)!=2:
26 d = self.faces[0].normal.dot(self.faces[1].normal)
27 self.smooth = ((d>limit and self.faces[0].use_smooth and self.faces[1].use_smooth) or d>0.99995)
29 def other_face(self, f):
30 if f.index==self.faces[0].index:
31 if len(self.faces)>=2:
38 def other_vertex(self, v):
39 if v.index==self.vertices[0].index:
40 return self.vertices[1]
42 return self.vertices[0]
46 def __init__(self, vertex):
47 if vertex.__class__==Vertex:
48 self.uvs = vertex.uvs[:]
53 self.index = vertex.index
54 self.co = mathutils.Vector(vertex.co)
55 self.normal = mathutils.Vector(vertex.normal)
60 self.groups = vertex.groups[:]
62 def __cmp__(self, other):
65 return cmp(self.index, other.index)
69 def __init__(self, group):
71 self.group = group.group
72 self.weight = group.weight
79 def __init__(self, pt):
80 self.primitive_type = pt
85 def __init__(self, face):
86 self.index = face.index
88 self.edge_keys = face.edge_keys
89 self.vertices = face.vertices[:]
90 self.loop_indices = face.loop_indices
91 self.normal = face.normal
92 self.use_smooth = face.use_smooth
93 self.material_index = face.material_index
96 def __cmp__(self, other):
99 return cmp(self.index, other.index)
101 def pivot_vertex(self, v):
102 n = self.vertices.index(v)
103 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
105 def get_loop_index(self, v):
106 return self.loop_indices[self.vertices.index(v)]
108 def get_edge(self, v1, v2):
109 key = make_edge_key(v1.index, v2.index)
113 raise KeyError("No edge %s"%(key,))
115 def other_edge(self, e, v):
117 if d!=e and v in d.vertices:
120 def get_neighbors(self):
121 neighbors = [e.other_face(self) for e in self.edges]
122 return list(filter(bool, neighbors))
126 def __init__(self, e):
128 self.vertices = e.vertices[:]
133 def __init__(self, arg):
139 self.uvs = [mathutils.Vector(d.uv) for d in arg.data]
144 dot = self.name.find('.')
146 ext = self.name[dot:]
147 if ext.startswith(".unit") and ext[5:].isdigit():
148 self.unit = int(ext[5:])
154 def __init__(self, l):
156 self.colors = [c.color[:] for c in l.data]
160 def __init__(self, mesh):
161 self.name = mesh.name
163 self.smoothing = mesh.smoothing
164 self.use_uv = mesh.use_uv
165 self.tangent_uvtex = mesh.tangent_uvtex
166 self.use_strips = mesh.use_strips
167 self.use_lines = mesh.use_lines
168 self.vertex_groups = mesh.vertex_groups
171 self.vertices = [Vertex(v) for v in mesh.vertices]
172 if self.vertex_groups:
173 for v in self.vertices:
174 v.groups = [VertexGroup(g) for g in v.groups]
176 self.faces = [Face(f) for f in mesh.polygons]
177 self.edges = [Edge(e) for e in mesh.edges]
178 self.loops = mesh.loops[:]
179 self.materials = mesh.materials[:]
181 self.use_auto_smooth = mesh.use_auto_smooth
182 self.auto_smooth_angle = mesh.auto_smooth_angle
183 self.max_groups_per_vertex = mesh.max_groups_per_vertex
185 # Clone only the desired UV layers
186 if mesh.use_uv=='NONE' or not mesh.uv_layers:
189 self.uv_layers = [UvLayer(u) for u in mesh.uv_layers if u.data]
191 # Assign texture unit numbers to UV layers that lack one
192 missing_unit = [u for u in self.uv_layers if u.unit is None]
194 missing_unit = sorted(missing_unit, key=(lambda u: u.name))
195 used_units = [u.unit for u in self.uv_layers if u.unit is not None]
196 for u, n in zip(missing_unit, (i for i in itertools.count() if i not in used_units)):
199 self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
201 if mesh.use_uv=='UNIT0' and self.uv_layers:
202 self.uv_layers = [self.uv_layers[0]]
203 if self.uv_layers[0].unit!=0:
207 if mesh.vertex_colors:
208 self.colors = ColorLayer(mesh.vertex_colors[0])
210 # Rewrite links between elements to point to cloned data, or create links
211 # where they don't exist
212 edge_map = {e.key: e for e in self.edges}
214 if len(f.vertices)>4:
215 raise ValueError("Unsupported face on mesh {}: N-gon".format(self.name))
217 f.vertices = [self.vertices[i] for i in f.vertices]
221 for k in f.edge_keys:
227 e.vertices = [self.vertices[i] for i in e.vertices]
231 # Store loose edges as lines
233 self.lines = [Line(e) for e in self.edges if not e.faces]
237 # Check if tangent vectors are needed
238 if mesh.tangent_vecs=='NO':
239 self.tangent_vecs = False
240 elif mesh.tangent_vecs=='YES':
241 self.tangent_vecs = True
242 elif mesh.tangent_vecs=='AUTO':
243 from .material import Material
244 self.tangent_vecs = False
245 for m in self.materials:
248 normal_prop = next((p for p in mat.properties if p.tex_keyword=="normal_map"), None)
249 if normal_prop and normal_prop.texture:
250 self.tangent_vecs = True
254 def transform(self, matrix):
255 for v in self.vertices:
258 def splice(self, other):
259 if len(self.uv_layers)!=len(other.uv_layers):
260 raise ValueError("Meshes {} and {} have incompatible UV layers".format(self.name, other.name))
261 for i, u in enumerate(self.uv_layers):
262 if u.name!=other.uv_layers[i].name:
263 raise ValueError("Meshes {} and {} have incompatible UV layers".format(self.name, other.name))
265 # Merge materials and form a lookup from source material indices to the
266 # merged material list
268 for m in other.materials:
269 if m in self.materials:
270 material_lookup.append(self.materials.index(m))
272 material_lookup.append(len(self.materials))
273 self.materials.append(m)
275 # Append data and adjust indices where necessary. Since the data is
276 # spliced from the source mesh, rebuilding references is not necessary.
277 for i, u in enumerate(self.uv_layers):
278 u.uvs += other.uv_layers[i].uvs
282 self.colors.colors += other.colors.colors
284 self.colors.colors += [(1.0, 1.0, 1.0, 1.0)]*len(other.loops)
286 self.colors = ColorLayer(other.colors.name)
287 self.colors.colors = [(1.0, 1.0, 1.0, 1.0)]*len(self.loops)+other.colors.colors
289 offset = len(self.vertices)
290 self.vertices += other.vertices
291 for v in self.vertices[offset:]:
294 loop_offset = len(self.loops)
295 self.loops += other.loops
297 offset = len(self.faces)
298 self.faces += other.faces
299 for f in self.faces[offset:]:
301 f.loop_indices = range(f.loop_indices.start+offset, f.loop_indices.stop+offset)
303 f.material_index = material_lookup[f.material_index]
305 offset = len(self.edges)
306 self.edges += other.edges
307 for e in self.edges[offset:]:
309 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
311 self.lines += other.lines
313 def prepare_triangles(self, task):
314 face_count = len(self.faces)
315 for i in range(face_count):
317 nverts = len(f.vertices)
321 # Calculate normals at each vertex of the face
323 for j in range(nverts):
324 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
327 for j in range(nverts):
328 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
330 # Check which diagonal results in a flatter triangulation
331 flatness1 = normals[0].dot(normals[2])
332 flatness2 = normals[1].dot(normals[3])
333 cut_index = 1 if flatness1>flatness2 else 0
336 nf.index = len(self.faces)
337 self.faces.append(nf)
340 ne.index = len(self.edges)
341 self.edges.append(ne)
343 nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
344 nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
345 for v in nf.vertices:
348 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
349 for v in ne.vertices:
351 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
354 f.vertices[3-cut_index].faces.remove(f)
355 del f.vertices[3-cut_index]
356 f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
360 nf.edges = [ne, f.edges[2], f.edges[3]]
361 f.edges = [f.edges[0], f.edges[1], ne]
363 nf.edges = [f.edges[1], f.edges[2], ne]
364 f.edges = [f.edges[0], ne, f.edges[3]]
370 f.normal = normals[1-cut_index]
371 nf.normal = normals[3-cut_index]
373 task.set_progress(i/face_count)
375 def prepare_smoothing(self, task):
377 if self.smoothing=='NONE':
382 elif self.use_auto_smooth:
383 smooth_limit = math.cos(self.auto_smooth_angle)
386 e.check_smooth(smooth_limit)
388 subtask = task.task("Sharp edges", 0.7)
389 self.split_vertices(self.find_smooth_group, subtask)
391 if self.smoothing!='BLENDER':
392 subtask = task.task("Updating normals", 1.0)
393 self.compute_normals(subtask)
395 def prepare_vertex_groups(self, obj):
396 if not self.vertex_groups:
399 for v in self.vertices:
401 weight_sum = sum(g.weight for g in v.groups)
402 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
403 weight_scale = weight_sum/sum(g.weight for g in v.groups)
405 g.weight *= weight_scale
406 while len(v.groups)<self.max_groups_per_vertex:
407 v.groups.append(VertexGroup(None))
409 if obj.parent and obj.parent.type=="ARMATURE":
410 armature = obj.parent.data
411 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
412 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
413 for g in first_obj.vertex_groups:
414 if g.name in bone_indices:
415 group_index_map[g.index] = bone_indices[g.name]
417 for v in self.vertices:
419 g.group = group_index_map[g.group]
421 def prepare_uv(self, task):
422 # Form a list of UV layers referenced by materials with the array atlas
424 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']
425 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
430 if f.material_index<len(self.materials):
431 mat = self.materials[f.material_index]
432 if mat and mat.array_atlas:
433 layer = mat.array_layer
435 for l in array_uv_layers:
436 for i in f.loop_indices:
437 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
439 # Split by the UV layer used for tangent vectors first so connectivity
440 # remains intact for tangent vector computation
441 tangent_layer_index = -1
442 if self.tangent_vecs:
443 if self.tangent_uvtex:
444 uv_names = [u.name for u in self.uv_layers]
445 if self.tangent_uvtex in uv_names:
446 tangent_layer_index = uv_names.index(self.tangent_uvtex)
447 elif self.uv_layers[0].unit==0:
448 tangent_layer_index = 0
450 if tangent_layer_index<0:
451 raise Exception("Invalid configuration on mesh {}: No tangent UV layer".format(self.name))
453 prog_count = len(self.uv_layers)
454 if tangent_layer_index>=0:
456 task.set_slices(prog_count)
458 if tangent_layer_index>=0:
459 subtask = task.next_slice("Computing tangents")
460 self.split_vertices(self.find_uv_group, subtask, tangent_layer_index)
461 subtask = task.next_slice(self.tangent_uvtex)
462 self.compute_tangents(tangent_layer_index, subtask)
464 # Split by the remaining UV layers
465 for i, u in enumerate(self.uv_layers):
466 if i==tangent_layer_index:
469 subtask = task.next_slice(u.name)
470 self.split_vertices(self.find_uv_group, subtask, i)
472 # Copy UVs from layers to vertices
473 for v in self.vertices:
475 # All faces still connected to the vertex have the same UV value
477 i = f.get_loop_index(v)
478 v.uvs = [u.uvs[i] for u in self.uv_layers]
480 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
482 def prepare_colors(self, task):
486 self.split_vertices(self.find_color_group, task)
488 for v in self.vertices:
491 v.color = self.colors.colors[f.get_loop_index(v)]
493 v.color = (1.0, 1.0, 1.0, 1.0)
495 def split_vertices(self, find_group_func, task, *args):
496 vertex_count = len(self.vertices)
497 for i in range(vertex_count):
502 # Find all groups of faces on this vertex
506 groups.append(find_group_func(v, f, *args))
508 # Give groups after the first separate copies of the vertex
511 nv.index = len(self.vertices)
512 self.vertices.append(nv)
515 e_faces_in_g = [f for f in e.faces if f in g]
519 if len(e_faces_in_g)<len(e.faces):
520 # Create a copy of an edge at the boundary of the group
522 ne.index = len(self.edges)
523 self.edges.append(ne)
525 ne.other_vertex(v).edges.append(ne)
527 for f in e_faces_in_g:
529 f.edges[f.edges.index(e)] = ne
534 e.vertices[e.vertices.index(v)] = nv
537 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
539 # Filter out any edges that were removed from the original vertex
540 v.edges = [e for e in v.edges if v in e.vertices]
544 f.vertices[f.vertices.index(v)] = nv
547 task.set_progress(i/vertex_count)
549 def find_smooth_group(self, vertex, face):
552 edges = [e for e in face.edges if vertex in e.vertices]
564 e = f.other_edge(e, vertex)
568 def find_uv_group(self, vertex, face, index):
569 layer = self.uv_layers[index]
570 uv = layer.uvs[face.get_loop_index(vertex)]
574 for f in vertex.faces:
575 if not f.flag and layer.uvs[f.get_loop_index(vertex)]==uv:
581 def find_color_group(self, vertex, face):
582 color = self.colors.colors[face.get_loop_index(vertex)]
586 for f in vertex.faces:
587 if not f.flag and self.colors.colors[f.get_loop_index(vertex)]==color:
593 def compute_normals(self, task):
594 for i, v in enumerate(self.vertices):
595 v.normal = mathutils.Vector()
597 vi = f.pivot_vertex(v)
598 edge1 = f.vertices[vi[1]].co-v.co
599 edge2 = f.vertices[vi[-1]].co-v.co
600 if edge1.length and edge2.length:
601 # Use the angle between edges as a weighting factor. This gives
602 # more consistent normals on bends with an inequal number of
603 # faces on each side.
604 v.normal += f.normal*edge1.angle(edge2)
609 v.normal = mathutils.Vector((0, 0, 1))
611 task.set_progress(i/len(self.vertices))
613 def compute_tangents(self, index, task):
614 layer_uvs = self.uv_layers[index].uvs
616 for i, v in enumerate(self.vertices):
617 v.tan = mathutils.Vector()
619 vi = f.pivot_vertex(v)
620 uv0 = layer_uvs[f.loop_indices[vi[0]]]
621 uv1 = layer_uvs[f.loop_indices[vi[1]]]
622 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
627 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
628 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
629 div = (du1*dv2-du2*dv1)
631 mul = edge1.angle(edge2)/div
632 v.tan += (edge1*dv2-edge2*dv1)*mul
637 task.set_progress(i/len(self.vertices))
639 def prepare_sequence(self, task):
640 subtask = task.task("Reordering faces", 0.5)
641 self.reorder_faces(subtask)
643 subtask = task.task("Building sequence", 1.0)
645 self.build_tristrip_sequence(subtask)
647 self.build_triangle_sequence(subtask)
650 self.build_line_sequence()
652 self.reorder_vertices()
654 def build_tristrip_sequence(self, task):
656 for i, f in enumerate(self.faces):
659 # Rotate the first three vertices so that the new face can be added
660 if sequence[0] in f.vertices and sequence[1] not in f.vertices:
661 sequence.append(sequence[0])
663 elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
664 sequence.insert(0, sequence[-1])
667 if sequence[-1] not in f.vertices:
670 to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
672 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
674 sequence.append(sequence[-1])
678 self.batches.append(Batch("TRIANGLE_STRIP"))
679 sequence = self.batches[-1].vertices
680 sequence += f.vertices
682 task.set_progress(i/len(self.faces))
684 def build_triangle_sequence(self, task):
685 batch = Batch("TRIANGLES")
687 batch.vertices += f.vertices
688 self.batches.append(batch)
690 def build_line_sequence(self):
691 batch = Batch("LINES")
693 batch.vertices += l.vertices
694 self.batches.append(batch)
696 self.reorder_vertices()
698 def reorder_faces(self, task):
699 # Tom Forsyth's vertex cache optimization algorithm
700 # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
705 last_triangle_score = 0.75
706 cache_decay_power = 1.5
707 valence_boost_scale = 2.0
708 valence_boost_power = -0.5
713 # Keep track of the score and number of unused faces for each vertex
714 vertex_info = [[0, len(v.faces)] for v in self.vertices]
715 for vi in vertex_info:
717 vi[0] = valence_boost_scale*(vi[1]**valence_boost_power)
725 # Previous iteration gave no candidate for best face (or this is
726 # the first iteration). Scan all faces for the highest score.
732 score = sum(vertex_info[v.index][0] for v in f.vertices)
740 reordered_faces.append(face)
743 for v in face.vertices:
744 vertex_info[v.index][1] -= 1
746 # Shuffle the vertex into the front of the cache
747 if v in cached_vertices:
748 cached_vertices.remove(v)
749 cached_vertices.insert(0, v)
751 # Update scores for all vertices in the cache
752 for i, v in enumerate(cached_vertices):
755 score += last_triangle_score
756 elif i<max_cache_size:
757 score += (1-(i-3)/(max_cache_size-3))**cache_decay_power
758 if vertex_info[v.index][1]:
759 score += valence_boost_scale*(vertex_info[v.index][1]**valence_boost_power)
760 vertex_info[v.index][0] = score
764 for v in cached_vertices:
767 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
772 del cached_vertices[max_cache_size:]
775 task.set_progress(n_processed/len(self.faces))
777 self.faces = reordered_faces
778 for i, f in enumerate(self.faces):
781 def reorder_vertices(self):
782 for v in self.vertices:
785 reordered_vertices = []
786 for b in self.batches:
789 v.index = len(reordered_vertices)
790 reordered_vertices.append(v)
792 for v in self.vertices:
794 v.index = len(reordered_vertices)
795 reordered_vertices.append(v)
797 self.vertices = reordered_vertices
800 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
803 def create_mesh_from_object(ctx, obj):
805 raise Exception("Object {} is not a mesh".format(obj.name))
807 task = ctx.task("Collecting mesh data", 0.2)
809 objs = [(obj, mathutils.Matrix())]
815 if c.type=="MESH" and c.compound:
816 objs.append((c, m*c.matrix_local))
818 dg = ctx.context.evaluated_depsgraph_get()
822 eval_obj = o.evaluated_get(dg)
823 bmesh = eval_obj.to_mesh()
825 # Object.to_mesh does not copy custom properties
826 bmesh.smoothing = o.data.smoothing
827 bmesh.use_lines = o.data.use_lines
828 bmesh.vertex_groups = o.data.vertex_groups
829 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
830 bmesh.use_uv = o.data.use_uv
831 bmesh.tangent_vecs = o.data.tangent_vecs
832 bmesh.tangent_uvtex = o.data.tangent_uvtex
837 for i, s in enumerate(eval_obj.material_slots):
839 me.materials[i] = s.material
846 mesh.name = obj.data.name
848 task = ctx.task("Triangulating", 0.3)
849 mesh.prepare_triangles(task)
850 task = ctx.task("Smoothing", 0.5)
851 mesh.prepare_smoothing(task)
852 task = ctx.task("Vertex groups", 0.6)
853 mesh.prepare_vertex_groups(obj)
854 task = ctx.task("Preparing UVs", 0.75)
855 mesh.prepare_uv(task)
856 task = ctx.task("Preparing vertex colors", 0.85)
857 mesh.prepare_colors(task)
858 task = ctx.task("Render sequence", 1.0)
859 mesh.prepare_sequence(task)