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._edge = edge._edge
12 self.vertices = edge.vertices[:]
13 self.smooth = edge.smooth
20 def __getattr__(self, attr):
21 return getattr(self._edge, attr)
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._vertex = vertex._vertex
50 self.uvs = vertex.uvs[:]
52 self.bino = vertex.bino
58 self.index = vertex.index
60 self.normal = vertex.normal
64 self.groups = vertex.groups[:]
66 def __getattr__(self, attr):
67 return getattr(self._vertex, attr)
69 def __cmp__(self, other):
72 return cmp(self.index, other.index)
76 def __init__(self, group):
78 self.group = group.group
79 self.weight = group.weight
81 def __getattr__(self, attr):
82 return getattr(self._group, attr)
86 def __init__(self, face):
88 self.index = face.index
90 self.vertices = face.vertices[:]
94 def __getattr__(self, attr):
95 return getattr(self._face, attr)
97 def __cmp__(self, other):
100 return cmp(self.index, other.index)
102 def pivot_vertex(self, v):
103 n = self.vertices.index(v)
104 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
106 def pivot_vertices(self, *vt):
107 flags = [(v in vt) for v in self.vertices]
108 l = len(self.vertices)
110 if flags[i] and not flags[(i+l-1)%l]:
111 return self.vertices[i:]+self.vertices[:i]
113 def get_edge(self, v1, v2):
114 key = make_edge_key(v1.index, v2.index)
118 raise KeyError("No edge %s"%(key,))
120 def other_edge(self, e, v):
122 if d!=e and v in d.vertices:
125 def get_neighbors(self):
126 neighbors = [e.other_face(self) for e in self.edges]
127 return list(filter(bool, neighbors))
131 def __init__(self, e):
133 self.vertices = e.vertices[:]
138 def __init__(self, arg):
145 self.uvs = [d.uv for d in self.data]
150 dot = self.name.find('.')
152 ext = self.name[dot:]
153 if ext.startswith(".unit") and ext[5:].isdigit():
154 self.unit = int(ext[5:])
158 def __getattr__(self, attr):
159 return getattr(self._layer, attr)
163 def __init__(self, mesh):
166 self.winding_test = mesh.winding_test
167 self.tbn_vecs = mesh.tbn_vecs
168 self.vertex_groups = mesh.vertex_groups
171 self.vertices = [Vertex(v) for v in self.vertices]
172 for v in self.vertices:
173 v.groups = [VertexGroup(g) for g in v.groups]
175 self.faces = [Face(f) for f in self.polygons]
176 self.edges = [Edge(e) for e in self.edges]
177 self.loops = self.loops[:]
178 self.materials = self.materials[:]
180 # Clone only the desired UV layers
181 if self.use_uv=='NONE' or not self.uv_layers:
184 self.uv_layers = [UvLayer(u) for u in self.uv_layers]
185 self.uv_layers = sorted([u for u in self.uv_layers if not u.hidden], key=(lambda u: (u.unit or 1000, u.name)))
187 if self.use_uv=='UNIT0':
188 self.uv_layers = [self.uv_layers[0]]
190 # Assign texture unit numbers to UV layers that lack one
191 next_unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
192 for u in self.uv_layers:
197 # Rewrite links between elements to point to cloned data, or create links
198 # where they don't exist
199 edge_map = {e.key: e for e in self.edges}
201 if len(f.vertices)>4:
202 raise ValueError("Ngons are not supported")
204 f.vertices = [self.vertices[i] for i in f.vertices]
208 for k in f.edge_keys:
214 e.vertices = [self.vertices[i] for i in e.vertices]
218 # Store loose edges as lines
220 self.lines = [Line(e) for e in self.edges if not e.faces]
224 def __getattr__(self, attr):
225 return getattr(self._mesh, attr)
227 def transform(self, matrix):
228 for v in self.vertices:
231 def splice(self, other):
232 if len(self.uv_layers)!=len(other.uv_layers):
233 raise ValueError("Meshes have incompatible UV layers")
234 for i, u in enumerate(self.uv_layers):
235 if u.name!=other.uv_layers[i].name:
236 raise ValueError("Meshes have incompatible UV layers")
238 # Merge materials and form a lookup from source material indices to the
239 # merged material list
241 for m in other.materials:
242 if m in self.materials:
243 material_map.append(self.materials.index(m))
245 material_map.append(len(self.materials))
246 self.materials.append(m)
248 # Append data and adjust indices where necessary. Since the data is
249 # spliced from the source mesh, rebuilding references is not necessary.
250 for i, u in enumerate(self.uv_layers):
251 u.uvs += other.uv_layers[i].uvs
253 offset = len(self.vertices)
254 self.vertices += other.vertices
255 for v in self.vertices[offset:]:
258 loop_offset = len(self.loops)
259 self.loops += other.loops
261 offset = len(self.faces)
262 self.faces += other.faces
263 for f in self.faces[offset:]:
265 f.loop_start += loop_offset
266 f.loop_indices = range(f.loop_start, f.loop_start+f.loop_total)
268 f.material_index = material_map[f.material_index]
270 offset = len(self.edges)
271 self.edges += other.edges
272 for e in self.edges[offset:]:
274 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
276 self.lines += other.lines
278 def prepare_smoothing(self, progress):
280 if self.smoothing=='NONE':
285 elif self.use_auto_smooth:
286 smooth_limit = math.cos(self.auto_smooth_angle)
289 e.check_smooth(smooth_limit)
291 progress.push_task("Sharp edges", 0.0, 0.7)
292 self.split_vertices(self.find_smooth_group, progress)
294 if self.smoothing!='BLENDER':
295 progress.set_task("Updating normals", 0.7, 1.0)
296 self.compute_normals(progress)
300 def prepare_vertex_groups(self, obj):
301 for v in self.vertices:
303 weight_sum = sum(g.weight for g in v.groups)
304 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
305 weight_scale = weight_sum/sum(g.weight for g in v.groups)
307 g.weight *= weight_scale
309 if obj.parent and obj.parent.type=="ARMATURE":
310 armature = obj.parent.data
311 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
312 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
313 for g in first_obj.vertex_groups:
314 if g.name in bone_indices:
315 group_index_map[g.index] = bone_indices[g.name]
317 for v in self.vertices:
319 g.group = group_index_map[g.group]
321 def prepare_uv(self, obj, progress):
322 if obj.material_tex and self.use_uv!='NONE':
323 layer = UvLayer("material_tex")
325 if self.use_uv=='UNIT0':
326 self.uv_layers = [layer]
329 self.uv_layers.append(layer)
330 layer.unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
332 layer.uvs = [None]*len(self.loops)
334 uv = mathutils.Vector(((f.material_index+0.5)/len(self.materials), 0.5))
335 for i in f.loop_indices:
338 # Form a list of UV layers referenced by materials with the array atlas
340 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']
341 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
346 if f.material_index<len(self.materials):
347 mat = self.materials[f.material_index]
348 if mat and mat.array_atlas:
349 layer = mat.array_layer
351 for l in array_uv_layers:
352 for i in f.loop_indices:
353 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
355 # Copy UVs from layers to faces
357 for u in self.uv_layers:
358 f.uvs.append([u.uvs[i] for i in f.loop_indices])
360 prog_count = len(self.uv_layers)
363 # Split by the UV layer used for TBN vectors first so connectivity
364 # remains intact for TBN vector computation
367 uv_names = [u.name for u in self.uv_layers]
368 if self.tbn_uvtex in uv_names:
370 tbn_layer_index = uv_names.index(self.tbn_uvtex)
371 progress.push_task_slice("Computing TBN", 0, prog_count)
372 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
373 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
374 self.compute_tbn(tbn_layer_index, progress)
378 # Split by the remaining UV layers
379 for i, u in enumerate(self.uv_layers):
380 if i==tbn_layer_index:
383 progress.push_task_slice(u.name, prog_step, prog_count)
384 self.split_vertices(self.find_uv_group, progress, i)
388 # Copy UVs from faces to vertices
389 for v in self.vertices:
391 # All faces still connected to the vertex have the same UV value
393 i = f.vertices.index(v)
394 v.uvs = [u[i] for u in f.uvs]
396 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
398 def split_vertices(self, find_group_func, progress, *args):
399 vertex_count = len(self.vertices)
400 for i in range(vertex_count):
405 # Find all groups of faces on this vertex
409 groups.append(find_group_func(v, f, *args))
411 # Give groups after the first separate copies of the vertex
414 nv.index = len(self.vertices)
415 self.vertices.append(nv)
418 e_faces_in_g = [f for f in e.faces if f in g]
422 if len(e_faces_in_g)<len(e.faces):
423 # Create a copy of an edge at the boundary of the group
425 ne.index = len(self.edges)
426 self.edges.append(ne)
428 ne.other_vertex(v).edges.append(ne)
430 for f in e_faces_in_g:
432 f.edges[f.edges.index(e)] = ne
437 e.vertices[e.vertices.index(v)] = nv
440 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
442 # Filter out any edges that were removed from the original vertex
443 v.edges = [e for e in v.edges if v in e.vertices]
447 f.vertices[f.vertices.index(v)] = nv
450 progress.set_progress(i/vertex_count)
452 def find_smooth_group(self, vertex, face):
455 edges = [e for e in face.edges if vertex in e.vertices]
467 e = f.other_edge(e, vertex)
471 def find_uv_group(self, vertex, face, index):
472 uv = face.uvs[index][face.vertices.index(vertex)]
476 for f in vertex.faces:
477 if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
483 def compute_normals(self, progress):
484 for i, v in enumerate(self.vertices):
485 v.normal = mathutils.Vector()
487 fv = f.pivot_vertices(v)
488 edge1 = fv[1].co-fv[0].co
489 edge2 = fv[-1].co-fv[0].co
490 if edge1.length and edge2.length:
491 # Use the angle between edges as a weighting factor. This gives
492 # more consistent normals on bends with an inequal number of
493 # faces on each side.
494 v.normal += f.normal*edge1.angle(edge2)
499 v.normal = mathutils.Vector((0, 0, 1))
501 progress.set_progress(i/len(self.vertices))
503 def compute_tbn(self, index, progress):
504 # This function is called at an early stage during UV preparation when
505 # face UVs are not available yet
506 layer_uvs = self.uv_layers[index].uvs
508 for i, v in enumerate(self.vertices):
509 v.tan = mathutils.Vector()
510 v.bino = mathutils.Vector()
512 vi = f.pivot_vertex(v)
513 uv0 = layer_uvs[f.loop_indices[vi[0]]]
514 uv1 = layer_uvs[f.loop_indices[vi[1]]]
515 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
520 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
521 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
522 div = (du1*dv2-du2*dv1)
524 mul = edge1.angle(edge2)/div
525 v.tan += (edge1*dv2-edge2*dv1)*mul
526 v.bino += (edge2*du1-edge1*du2)*mul
533 progress.set_progress(i/len(self.vertices))
535 def drop_references(self):
536 for v in self.vertices:
544 for u in self.uv_layers:
548 def create_strip(self, face, max_len):
549 # Find an edge with another unused face next to it
552 other = e.other_face(face)
553 if other and not other.flag:
560 # Add initial vertices so that we'll complete the edge on the first
562 vertices = face.pivot_vertices(*edge.vertices)
564 result = [vertices[-1], vertices[0]]
566 result = [vertices[-2], vertices[-1]]
571 vertices = face.pivot_vertices(*result[-2:])
574 # Quads need special handling because the winding of every other
575 # triangle in the strip is reversed
576 if len(vertices)==4 and not k:
577 result.append(vertices[3])
578 result.append(vertices[2])
579 if len(vertices)==4 and k:
580 result.append(vertices[3])
582 if len(result)>=max_len:
585 # Hop over the last edge
586 edge = face.get_edge(*result[-2:])
587 face = edge.other_face(face)
588 if not face or face.flag:
593 def create_mesh_from_object(context, obj, progress):
595 raise Exception("Object is not a mesh")
597 progress.push_task("Preparing mesh", 0.0, 0.3)
599 objs = [(obj, mathutils.Matrix())]
605 if c.type=="MESH" and c.compound:
606 objs.append((c, m*c.matrix_local))
611 bmesh = o.to_mesh(context.scene, True, "PREVIEW")
612 bmeshes.append(bmesh)
614 # Object.to_mesh does not copy custom properties
615 bmesh.winding_test = o.data.winding_test
616 bmesh.smoothing = o.data.smoothing
617 bmesh.use_lines = o.data.use_lines
618 bmesh.vertex_groups = o.data.vertex_groups
619 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
620 bmesh.use_uv = o.data.use_uv
621 bmesh.tbn_vecs = o.data.tbn_vecs
622 bmesh.tbn_uvtex = o.data.tbn_uvtex
632 progress.set_task("Smoothing", 0.3, 0.6)
633 mesh.prepare_smoothing(progress)
634 progress.set_task("Vertex groups", 0.6, 0.7)
635 mesh.prepare_vertex_groups(obj)
636 progress.set_task("Preparing UVs", 0.7, 1.0)
637 mesh.prepare_uv(obj, progress)
639 # Discard the temporary Blender meshes after making sure there's no
640 # references to the data
641 mesh.drop_references()
643 bpy.data.meshes.remove(m)