1 # ##### BEGIN GPL LICENSE BLOCK #####
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software Foundation,
15 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # ##### END GPL LICENSE BLOCK #####
22 def mesh_linked_faces(mesh):
24 Splits the mesh into connected parts,
25 these parts are returned as lists of faces.
26 used for seperating cubes from other mesh elements in the 1 mesh
29 # Build vert face connectivity
30 vert_faces = [[] for i in range(len(mesh.vertices))]
33 vert_faces[v].append(f)
35 # sort faces into connectivity groups
36 face_groups = [[f] for f in mesh.faces]
37 face_mapping = list(range(len(mesh.faces))) # map old, new face location
39 # Now clump faces iterativly
44 for i, f in enumerate(mesh.faces):
45 mapped_index = face_mapping[f.index]
46 mapped_group = face_groups[mapped_index]
49 for nxt_f in vert_faces[v]:
51 nxt_mapped_index = face_mapping[nxt_f.index]
53 # We are not a part of the same group
54 if mapped_index != nxt_mapped_index:
57 # Assign mapping to this group so they all map to this group
58 for grp_f in face_groups[nxt_mapped_index]:
59 face_mapping[grp_f.index] = mapped_index
61 # Move faces into this group
62 mapped_group.extend(face_groups[nxt_mapped_index])
64 # remove reference to the list
65 face_groups[nxt_mapped_index] = None
67 # return all face groups that are not null
68 # this is all the faces that are connected in their own lists.
69 return [fg for fg in face_groups if fg]
72 def edge_face_count_dict(mesh):
73 face_edge_keys = [face.edge_keys for face in mesh.faces]
75 for face_keys in face_edge_keys:
78 face_edge_count[key] += 1
80 face_edge_count[key] = 1
82 return face_edge_count
85 def edge_face_count(mesh):
86 edge_face_count_dict = edge_face_count_dict(mesh)
87 return [edge_face_count_dict.get(ed.key, 0) for ed in mesh.edges]
90 def edge_loops_from_faces(mesh, faces=None, seams=()):
92 Edge loops defined by faces
94 Takes me.faces or a list of faces and returns the edge loops
95 These edge loops are the edges that sit between quads, so they dont touch
96 1 quad, note: not connected will make 2 edge loops, both only containing 2 edges.
98 return a list of edge key lists
99 [ [(0,1), (4, 8), (3,8)], ...]
101 return a list of edge vertex index lists
104 OTHER_INDEX = 2, 3, 0, 1 # opposite face index
113 if f.vertices_raw[3] != 0:
114 edge_keys = f.edge_keys
115 for i, edkey in enumerate(f.edge_keys):
116 edges.setdefault(edkey, []).append(edge_keys[OTHER_INDEX[i]])
121 # Collect edge loops here
124 for edkey, ed_adj in edges.items():
125 if 0 < len(ed_adj) < 3: # 1 or 2
126 # Seek the first edge
127 context_loop = [edkey, ed_adj[0]]
128 edge_loops.append(context_loop)
130 other_dir = ed_adj[1]
139 # from knowing the last 2, look for th next.
140 ed_adj = edges[context_loop[-1]]
143 if other_dir and flipped == False: # the original edge had 2 other edges
144 flipped = True # only flip the list once
145 context_loop.reverse()
147 context_loop.append(other_dir) # save 1 lookiup
149 ed_adj = edges[context_loop[-1]]
157 i = ed_adj.index(context_loop[-2])
158 context_loop.append(ed_adj[not i])
160 # Dont look at this again
166 def edge_loops_from_edges(mesh, edges=None):
168 Edge loops defined by edges
170 Takes me.edges or a list of edges and returns the edge loops
172 return a list of vertex indices.
175 closed loops have matching start and end values.
179 # Get edges not used by a face
183 if not hasattr(edges, "pop"):
186 edge_dict = {ed.key: ed for ed in mesh.edges if ed.select}
189 current_edge = edges.pop()
190 vert_end, vert_start = current_edge.vertices[:]
191 line_poly = [vert_start, vert_end]
196 #for i, ed in enumerate(edges):
204 vert_end = line_poly[-1]
210 vert_end = line_poly[-1]
214 elif v1 == vert_start:
215 line_poly.insert(0, v2)
216 vert_start = line_poly[0]
220 elif v2 == vert_start:
221 line_poly.insert(0, v1)
222 vert_start = line_poly[0]
226 line_polys.append(line_poly)
231 def ngon_tesselate(from_data, indices, fix_loops=True):
233 Takes a polyline of indices (fgon)
234 and returns a list of face indicie lists.
235 Designed to be used for importers that need indices for an fgon to create from existing verts.
237 from_data: either a mesh, or a list/tuple of vectors.
238 indices: a list of indices to use this list is the ordered closed polyline to fill, and can be a subset of the data given.
239 fix_loops: If this is enabled polylines that use loops to make multiple polylines are delt with correctly.
242 from mathutils import Vector
243 vector_to_tuple = Vector.to_tuple
249 return abs(co[0]) + abs(co[1]) + abs(co[2]) # manhatten length of a vector, faster then length
251 def vert_treplet(v, i):
252 return v, vector_to_tuple(v, 6), i, mlen(v)
254 def ed_key_mlen(v1, v2):
260 if not PREF_FIX_LOOPS:
262 Normal single concave loop filling
264 if type(from_data) in (tuple, list):
265 verts = [Vector(from_data[i]) for ii, i in enumerate(indices)]
267 verts = [from_data.vertices[i].co for ii, i in enumerate(indices)]
269 for i in range(len(verts) - 1, 0, -1): # same as reversed(xrange(1, len(verts))):
270 if verts[i][1] == verts[i - 1][0]:
273 fill = fill_polygon([verts])
277 Seperate this loop into multiple loops be finding edges that are used twice
278 This is used by lightwave LWO files a lot
281 if type(from_data) in (tuple, list):
282 verts = [vert_treplet(Vector(from_data[i]), ii) for ii, i in enumerate(indices)]
284 verts = [vert_treplet(from_data.vertices[i].co, ii) for ii, i in enumerate(indices)]
286 edges = [(i, i - 1) for i in range(len(verts))]
288 edges[0] = (0, len(verts) - 1)
294 edges_doubles = set()
295 # We need to check if any edges are used twice location based.
297 edkey = ed_key_mlen(verts[ed[0]], verts[ed[1]])
298 if edkey in edges_used:
299 edges_doubles.add(edkey)
301 edges_used.add(edkey)
303 # Store a list of unconnected loop segments split by double edges.
308 context_loop = [v_prev]
309 loop_segments = [context_loop]
313 # Are we crossing an edge we removed?
314 if ed_key_mlen(v, v_prev) in edges_doubles:
316 loop_segments.append(context_loop)
318 if context_loop and context_loop[-1][1] == v[1]:
322 context_loop.append(v)
325 # Now join loop segments
327 def join_seg(s1, s2):
328 if s2[-1][1] == s1[0][1]:
330 elif s1[-1][1] == s2[0][1]:
335 # If were stuill here s1 and s2 are 2 segments in the same polyline
336 s1.pop() # remove the last vert from s1
337 s1.extend(s2) # add segment 2 to segment 1
339 if s1[0][1] == s1[-1][1]: # remove endpoints double
342 s2[:] = [] # Empty this segment s2 so we dont use it again.
345 joining_segments = True
346 while joining_segments:
347 joining_segments = False
348 segcount = len(loop_segments)
350 for j in range(segcount - 1, -1, -1): # reversed(range(segcount)):
351 seg_j = loop_segments[j]
353 for k in range(j - 1, -1, -1): # reversed(range(j)):
356 seg_k = loop_segments[k]
358 if seg_k and join_seg(seg_j, seg_k):
359 joining_segments = True
361 loop_list = loop_segments
363 for verts in loop_list:
364 while verts and verts[0][1] == verts[-1][1]:
367 loop_list = [verts for verts in loop_list if len(verts) > 2]
368 # DONE DEALING WITH LOOP FIXING
371 vert_map = [None] * len(indices)
373 for verts in loop_list:
375 for i, vert in enumerate(verts):
376 vert_map[i + ii] = vert[2]
379 fill = tesselate_polygon([[v[0] for v in loop] for loop in loop_list])
380 #draw_loops(loop_list)
382 # map to original indices
383 fill = [[vert_map[i] for i in reversed(f)] for f in fill]
386 print('Warning Cannot scanfill, fallback on a triangle fan.')
387 fill = [[0, i - 1, i] for i in range(2, len(indices))]
390 # See if its flipped the wrong way.
395 for i, vi in enumerate(fi):
396 if vi == 0 and fi[i - 1] == 1:
399 elif vi == 1 and fi[i - 1] == 0:
404 for i, fi in enumerate(fill):
405 fill[i] = tuple([ii for ii in reversed(fi)])