X-Git-Url: http://git.tdb.fi/?p=libs%2Fgl.git;a=blobdiff_plain;f=blender%2Fio_mspgl%2Fmesh.py;h=91648d28e5b28b1ab6db369586b46d974b0c332e;hp=aa8df8d254665d4240b50a34934753515a56e96c;hb=aa1ef522b3b2bdde8f005878fed6668f52b8d949;hpb=fcdc70624618488c514676874006f5eddc4e63df diff --git a/blender/io_mspgl/mesh.py b/blender/io_mspgl/mesh.py index aa8df8d2..91648d28 100644 --- a/blender/io_mspgl/mesh.py +++ b/blender/io_mspgl/mesh.py @@ -1,22 +1,29 @@ +import bpy import math import mathutils +import itertools def make_edge_key(i1, i2): return (min(i1, i2), max(i1, i2)) class Edge: - def __init__(self, me): - if me.__class__==Edge: - self._medge = me._medge - self.vertices = me.vertices[:] - self.smooth = me.smooth + def __init__(self, edge): + if edge.__class__==Edge: + self._edge = edge._edge + self.smooth = edge.smooth else: - self._medge = me + self._edge = edge self.smooth = False + if edge: + self.vertices = edge.vertices[:] + self.key = edge.key + else: + self.vertices = [] + self.key = None self.faces = [] def __getattr__(self, attr): - return getattr(self._medge, attr) + return getattr(self._edge, attr) def check_smooth(self, limit): if len(self.faces)!=2: @@ -34,25 +41,35 @@ class Edge: else: return self.faces[0] + def other_vertex(self, v): + if v.index==self.vertices[0].index: + return self.vertices[1] + else: + return self.vertices[0] + class Vertex: - def __init__(self, mv): - if mv.__class__==Vertex: - self._mvert = mv._mvert - self.normal = mv.normal - self.uvs = mv.uvs[:] - self.tan = mv.tan - self.bino = mv.bino + def __init__(self, vertex): + if vertex.__class__==Vertex: + self._vertex = vertex._vertex + self.uvs = vertex.uvs[:] + self.tan = vertex.tan + self.bino = vertex.bino else: - self._mvert = mv + self._vertex = vertex self.uvs = [] self.tan = None self.bino = None + self.index = vertex.index + self.co = mathutils.Vector(vertex.co) + self.normal = mathutils.Vector(vertex.normal) self.flag = False + self.edges = [] self.faces = [] + self.groups = vertex.groups[:] def __getattr__(self, attr): - return getattr(self._mvert, attr) + return getattr(self._vertex, attr) def __cmp__(self, other): if other is None: @@ -60,22 +77,37 @@ class Vertex: return cmp(self.index, other.index) +class VertexGroup: + def __init__(self, group): + self._group = group + self.group = group.group + self.weight = group.weight + + def __getattr__(self, attr): + return getattr(self._group, attr) + + class Face: - def __init__(self, mf): - self._mface = mf + def __init__(self, face): + self._face = face + self.index = face.index self.edges = [] - self.vertices = mf.vertices[:] + self.vertices = face.vertices[:] self.uvs = [] self.flag = False def __getattr__(self, attr): - return getattr(self._mface, attr) + return getattr(self._face, attr) def __cmp__(self, other): if other is None: return 1 return cmp(self.index, other.index) + def pivot_vertex(self, v): + n = self.vertices.index(v) + return [(n+i)%len(self.vertices) for i in range(len(self.vertices))] + def pivot_vertices(self, *vt): flags = [(v in vt) for v in self.vertices] l = len(self.vertices) @@ -83,13 +115,18 @@ class Face: if flags[i] and not flags[(i+l-1)%l]: return self.vertices[i:]+self.vertices[:i] - def get_edge(self, v1, v2): + def get_edge(self, v1, v2): key = make_edge_key(v1.index, v2.index) for e in self.edges: if e.key==key: return e raise KeyError("No edge %s"%(key,)) + def other_edge(self, e, v): + for d in self.edges: + if d!=e and v in d.vertices: + return d + def get_neighbors(self): neighbors = [e.other_face(self) for e in self.edges] return list(filter(bool, neighbors)) @@ -103,12 +140,19 @@ class Line: class UvLayer: - def __init__(self, l, t): - self._layer = l - self.uvtex = t - self.name = self.uvtex.name + def __init__(self, arg): + if type(arg)==str: + self._layer = None + self.name = arg + self.uvs = [] + else: + self._layer = arg + self.name = arg.name + self.uvs = [mathutils.Vector(d.uv) for d in self.data] + self.unit = None self.hidden = False + dot = self.name.find('.') if dot>=0: ext = self.name[dot:] @@ -120,54 +164,92 @@ class UvLayer: def __getattr__(self, attr): return getattr(self._layer, attr) -class FakeUvLayer: - def __init__(self, n): - self.uvtex = None - self.name = n - self.unit = None - self.hidden = False class Mesh: - def __init__(self, m): - self._mesh = m + def __init__(self, mesh): + self._mesh = mesh + self.name = mesh.name - self.vertices = [Vertex(v) for v in self.vertices] - self.faces = [Face(f) for f in self.polygons] + self.winding_test = mesh.winding_test + self.tbn_vecs = mesh.tbn_vecs + self.vertex_groups = mesh.vertex_groups - self.materials = self.materials[:] + # Clone basic data + self.vertices = [Vertex(v) for v in mesh.vertices] + for v in self.vertices: + v.groups = [VertexGroup(g) for g in v.groups] - self.uv_layers = [UvLayer(self.uv_layers[i], self.uv_textures[i]) for i in range(len(self.uv_layers))] - self.assign_texture_units() + self.faces = [Face(f) for f in mesh.polygons] + self.edges = [Edge(e) for e in mesh.edges] + self.loops = mesh.loops[:] + self.materials = mesh.materials[:] + # Clone only the desired UV layers + if self.use_uv=='NONE' or not mesh.uv_layers: + self.uv_layers = [] + else: + self.uv_layers = [UvLayer(u) for u in mesh.uv_layers] + + # Assign texture unit numbers to UV layers that lack one + missing_unit = [u for u in self.uv_layers if u.unit is None] + if missing_unit: + missing_unit = sorted(missing_unit, key=(lambda u: u.name)) + used_units = [u.unit for u in self.uv_layers if u.unit is not None] + for u, n in zip(missing_unit, (i for i in itertools.count() if i not in used_units)): + u.unit = n + + self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit)) + + if self.use_uv=='UNIT0': + self.uv_layers = [self.uv_layers[0]] + if self.uv_layers[0].unit!=0: + self.uv_layers = [] + + # Rewrite links between elements to point to cloned data, or create links + # where they don't exist + edge_map = {e.key: e for e in self.edges} for f in self.faces: + if len(f.vertices)>4: + raise ValueError("Ngons are not supported") + f.vertices = [self.vertices[i] for i in f.vertices] for v in f.vertices: v.faces.append(f) - for u in self.uv_layers: - f.uvs.append([u.data[f.loop_indices[i]].uv for i in range(len(f.vertices))]) - self.edges = dict([(e.key, Edge(e)) for e in self.edges]) - for f in self.faces: for k in f.edge_keys: - e = self.edges[k] - e.faces.append(self.faces[f.index]) + e = edge_map[k] + e.faces.append(f) f.edges.append(e) - self.lines = [Line(e) for e in self.edges.values() if not e.faces] + for e in self.edges: + e.vertices = [self.vertices[i] for i in e.vertices] + for v in e.vertices: + v.edges.append(e) - if self.use_auto_smooth: - smooth_limit = math.cos(self.auto_smooth_angle*math.pi/180) + # Store loose edges as lines + if self.use_lines: + self.lines = [Line(e) for e in self.edges if not e.faces] else: - smooth_limit = -1 + self.lines = [] - for e in self.edges.values(): - e.vertices = [self.vertices[i] for i in e.vertices] - e.check_smooth(smooth_limit) + self.vertex_sequence = [] def __getattr__(self, attr): return getattr(self._mesh, attr) + def transform(self, matrix): + for v in self.vertices: + v.co = matrix*v.co + def splice(self, other): + if len(self.uv_layers)!=len(other.uv_layers): + raise ValueError("Meshes have incompatible UV layers") + for i, u in enumerate(self.uv_layers): + if u.name!=other.uv_layers[i].name: + raise ValueError("Meshes have incompatible UV layers") + + # Merge materials and form a lookup from source material indices to the + # merged material list material_map = [] for m in other.materials: if m in self.materials: @@ -176,180 +258,350 @@ class Mesh: material_map.append(len(self.materials)) self.materials.append(m) + # Append data and adjust indices where necessary. Since the data is + # spliced from the source mesh, rebuilding references is not necessary. + for i, u in enumerate(self.uv_layers): + u.uvs += other.uv_layers[i].uvs + offset = len(self.vertices) - for v in other.vertices: + self.vertices += other.vertices + for v in self.vertices[offset:]: v.index += offset - self.vertices.append(v) + + loop_offset = len(self.loops) + self.loops += other.loops offset = len(self.faces) - for f in other.faces: + self.faces += other.faces + for f in self.faces[offset:]: f.index += offset + f.loop_start += loop_offset + f.loop_indices = range(f.loop_start, f.loop_start+f.loop_total) if other.materials: f.material_index = material_map[f.material_index] - self.faces.append(f) - for e in other.edges.values(): + offset = len(self.edges) + self.edges += other.edges + for e in self.edges[offset:]: + e.index += offset e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index) - self.edges[e.key] = e self.lines += other.lines - def flatten_faces(self): - for f in self.faces: - f.use_smooth = False + def prepare_triangles(self, progress): + face_count = len(self.faces) + for i in range(face_count): + f = self.faces[i] + nverts = len(f.vertices) + if nverts==3: + continue + + # Calculate normals at each vertex of the face + edge_vecs = [] + for j in range(nverts): + edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co) + + normals = [] + for j in range(nverts): + normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized()) + + # Check which diagonal results in a flatter triangulation + flatness1 = normals[0].dot(normals[2]) + flatness2 = normals[1].dot(normals[3]) + cut_index = 1 if flatness1>flatness2 else 0 + + nf = Face(f) + nf.index = len(self.faces) + self.faces.append(nf) + + ne = Edge(None) + ne.index = len(self.edges) + self.edges.append(ne) + + nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]] + nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]] + for v in nf.vertices: + v.faces.append(nf) + + ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]] + for v in ne.vertices: + v.edges.append(ne) + ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index) + ne.smooth = True + + f.vertices[3-cut_index].faces.remove(f) + del f.vertices[3-cut_index] + f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]] + + ne.faces = [f, nf] + if cut_index==0: + nf.edges = [ne, f.edges[2], f.edges[3]] + f.edges = [f.edges[0], f.edges[1], ne] + else: + nf.edges = [f.edges[1], f.edges[2], ne] + f.edges = [f.edges[0], ne, f.edges[3]] + for e in nf.edges: + if e!=ne: + e.faces.remove(f) + e.faces.append(nf) + + f.normal = normals[1-cut_index] + nf.normal = normals[3-cut_index] - for e in self.edges.values(): - e.check_smooth(1) + progress.set_progress(i/face_count) + + def prepare_smoothing(self, progress): + smooth_limit = -1 + if self.smoothing=='NONE': + for f in self.faces: + f.use_smooth = False + + smooth_limit = 1 + elif self.use_auto_smooth: + smooth_limit = math.cos(self.auto_smooth_angle) + + for e in self.edges: + e.check_smooth(smooth_limit) + + progress.push_task("Sharp edges", 0.0, 0.7) + self.split_vertices(self.find_smooth_group, progress) + + if self.smoothing!='BLENDER': + progress.set_task("Updating normals", 0.7, 1.0) + self.compute_normals(progress) + + progress.pop_task() + + def prepare_vertex_groups(self, obj): + for v in self.vertices: + if v.groups: + weight_sum = sum(g.weight for g in v.groups) + v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex] + weight_scale = weight_sum/sum(g.weight for g in v.groups) + for g in v.groups: + g.weight *= weight_scale + + if obj.parent and obj.parent.type=="ARMATURE": + armature = obj.parent.data + bone_indices = {b.name: i for i, b in enumerate(armature.bones)} + group_index_map = {i: i for i in range(len(obj.vertex_groups))} + for g in first_obj.vertex_groups: + if g.name in bone_indices: + group_index_map[g.index] = bone_indices[g.name] + + for v in self.vertices: + for g in v.groups: + g.group = group_index_map[g.group] + + def apply_material_map(self, material_map): + for m in self.materials: + if m not in material_map.materials: + raise Exception("Material map is not compatible with Mesh") + + if self.use_uv=='NONE': + return - def assign_texture_units(self): - # Assign texture units for any non-hidden UV layers that lack one - units = [u.unit for u in self.uv_layers if u.unit is not None] - if units: - free_unit = max(units)+1 + layer = UvLayer("material_map") + if self.use_uv=='UNIT0': + self.uv_layers = [layer] + layer.unit = 0 else: - free_unit = 0 - for u in self.uv_layers: - if u.unit is None: - if not u.hidden: - u.unit = free_unit - free_unit += 1 - - def generate_material_uv(self): - self.uv_layers.append(FakeUvLayer("material_tex")) - self.assign_texture_units() + self.uv_layers.append(layer) + used_units = [u.unit for u in self.uv_layers] + layer.unit = next(i for i in itertools.count() if i not in used_units) + self.uv_layers.sort(key=lambda u: u.unit) + + layer.uvs = [(0.0, 0.0)]*len(self.loops) + for f in self.faces: + uv = material_map.get_material_uv(self.materials[f.material_index]) + for i in f.loop_indices: + layer.uvs[i] = uv + + def prepare_uv(self, progress): + # Form a list of UV layers referenced by materials with the array atlas + # property set + 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'] + array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers] + + if array_uv_layers: + for f in self.faces: + layer = 0 + if f.material_index=2: + for f in e_faces_in_g: e.faces.remove(f) - e = Edge(e) - f.edges[j] = e - e.faces.append(f) - else: - del self.edges[e.key] + f.edges[f.edges.index(e)] = ne + ne.faces.append(f) - e.vertices[e.vertices.index(self.vertices[i])] = v + e = ne - e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index) - self.edges[e.key] = e + e.vertices[e.vertices.index(v)] = nv + nv.edges.append(e) - self.vertices[i].faces.remove(f) - f.vertices[f.vertices.index(self.vertices[i])] = v - v.faces.append(f) + e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index) - if progress: - progress.set_progress(0.5+i*0.5/len(self.vertices)) + # Filter out any edges that were removed from the original vertex + v.edges = [e for e in v.edges if v in e.vertices] - def split_smooth(self, progress = None): - self.split_vertices(self.find_smooth_group, progress) + for f in g: + v.faces.remove(f) + f.vertices[f.vertices.index(v)] = nv + nv.faces.append(f) - def split_uv(self, index, progress = None): - self.split_vertices(self.find_uv_group, progress, index) + progress.set_progress(i/vertex_count) def find_smooth_group(self, vertex, face): face.flag = True - queue = [face] - for f in queue: - for e in f.edges: - other = e.other_face(f) - if other not in vertex.faces: - continue + edges = [e for e in face.edges if vertex in e.vertices] - if e.smooth: - if not other.flag: - other.flag = True - queue.append(other) + group = [face] + for e in edges: + f = face + while e.smooth: + f = e.other_face(f) + if not f or f.flag: + break - return queue + f.flag = True + group.append(f) + e = f.other_edge(e, vertex) + + return group def find_uv_group(self, vertex, face, index): uv = face.uvs[index][face.vertices.index(vertex)] face.flag = True + group = [face] for f in vertex.faces: if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv: f.flag = True group.append(f) + return group - def compute_normals(self): - for v in self.vertices: - if v.faces: - v.normal = mathutils.Vector() - for f in v.faces: - fv = f.pivot_vertices(v) - edge1 = fv[1].co-fv[0].co - edge2 = fv[-1].co-fv[0].co - weight = 1 - if len(f.get_edge(fv[0], fv[1]).faces)==1: - weight += 1 - if len(f.get_edge(fv[0], fv[-1]).faces)==1: - weight += 1 - v.normal += f.normal*edge1.angle(edge2)*weight + def compute_normals(self, progress): + for i, v in enumerate(self.vertices): + v.normal = mathutils.Vector() + for f in v.faces: + fv = f.pivot_vertices(v) + edge1 = fv[1].co-fv[0].co + edge2 = fv[-1].co-fv[0].co + if edge1.length and edge2.length: + # Use the angle between edges as a weighting factor. This gives + # more consistent normals on bends with an inequal number of + # faces on each side. + v.normal += f.normal*edge1.angle(edge2) + + if v.normal.length: v.normal.normalize() else: - # XXX Should use edges to compute normal - v.normal = mathutils.Vector(0, 0, 1) + v.normal = mathutils.Vector((0, 0, 1)) - def compute_uv(self): - for v in self.vertices: - if v.faces: - f = v.faces[0] - i = f.vertices.index(v) - v.uvs = [u[i] for u in f.uvs] + progress.set_progress(i/len(self.vertices)) - def compute_tbn(self, index): - if not self.uv_layers: - return + def compute_tbn(self, index, progress): + # This function is called at an early stage during UV preparation when + # face UVs are not available yet + layer_uvs = self.uv_layers[index].uvs - for v in self.vertices: + for i, v in enumerate(self.vertices): v.tan = mathutils.Vector() v.bino = mathutils.Vector() for f in v.faces: - fv = f.pivot_vertices(v) - uv0 = fv[0].uvs[index] - uv1 = fv[1].uvs[index] - uv2 = fv[-1].uvs[index] + vi = f.pivot_vertex(v) + uv0 = layer_uvs[f.loop_indices[vi[0]]] + uv1 = layer_uvs[f.loop_indices[vi[1]]] + uv2 = layer_uvs[f.loop_indices[vi[-1]]] du1 = uv1[0]-uv0[0] du2 = uv2[0]-uv0[0] dv1 = uv1[1]-uv0[1] dv2 = uv2[1]-uv0[1] - edge1 = fv[1].co-fv[0].co - edge2 = fv[-1].co-fv[0].co + edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co + edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co div = (du1*dv2-du2*dv1) if div: mul = edge1.angle(edge2)/div @@ -361,47 +613,218 @@ class Mesh: if v.bino.length: v.bino.normalize() - def create_strip(self, face, max_len): - # Find an edge with another unused face next to it - edge = None - for e in face.edges: - other = e.other_face(face) - if other and not other.flag: - edge = e - break + progress.set_progress(i/len(self.vertices)) + + def prepare_sequence(self, progress): + progress.push_task("Reordering faces", 0.0, 0.5) + self.reorder_faces(progress) + + progress.set_task("Building sequence", 0.5, 1.0) + sequence = None + for i, f in enumerate(self.faces): + if sequence: + if len(sequence)==3: + # Rotate the first three vertices so that the new face can be added + if sequence[0] in f.vertices and sequence[1] not in f.vertices: + sequence.append(sequence[0]) + del sequence[0] + elif sequence[2] not in f.vertices and sequence[1] in f.vertices: + sequence.insert(0, sequence[-1]) + del sequence[-1] + + if sequence[-1] not in f.vertices: + sequence = None + else: + to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]] + if len(to_add)==2: + if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1): + to_add.reverse() + sequence.append(sequence[-1]) + sequence += to_add + + if not sequence: + sequence = f.vertices[:] + self.vertex_sequence.append(sequence) + + progress.set_progress(i/len(self.faces)) + + progress.pop_task() + + self.reorder_vertices() + + def reorder_faces(self, progress): + # Tom Forsyth's vertex cache optimization algorithm + # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html + + for f in self.faces: + f.flag = False - if not edge: - return None + last_triangle_score = 0.75 + cache_decay_power = 1.5 + valence_boost_scale = 2.0 + valence_boost_power = -0.5 - # Add initial vertices so that we'll complete the edge on the first - # iteration - vertices = face.pivot_vertices(*edge.vertices) - if len(vertices)==3: - result = [vertices[-1], vertices[0]] - else: - result = [vertices[-2], vertices[-1]] + max_cache_size = 32 + cached_vertices = [] + # Keep track of the score and number of unused faces for each vertex + vertex_info = [[0, len(v.faces)] for v in self.vertices] + for vi in vertex_info: + vi[0] = valence_boost_scale*(vi[1]**valence_boost_power) + + face = None + reordered_faces = [] + + n_processed = 0 while 1: + if not face: + # Previous iteration gave no candidate for best face (or this is + # the first iteration). Scan all faces for the highest score. + best_score = 0 + for f in self.faces: + if f.flag: + continue + + score = sum(vertex_info[v.index][0] for v in f.vertices) + if score>best_score: + best_score = score + face = f + + if not face: + break + + reordered_faces.append(face) face.flag = True - vertices = face.pivot_vertices(*result[-2:]) - k = len(result)%2 + for v in face.vertices: + vertex_info[v.index][1] -= 1 + + # Shuffle the vertex into the front of the cache + if v in cached_vertices: + cached_vertices.remove(v) + cached_vertices.insert(0, v) + + # Update scores for all vertices in the cache + for i, v in enumerate(cached_vertices): + score = 0 + if i<3: + score += last_triangle_score + elif ibest_score: + best_score = score + face = f - # Quads need special handling because the winding of every other - # triangle in the strip is reversed - if len(vertices)==4 and not k: - result.append(vertices[3]) - result.append(vertices[2]) - if len(vertices)==4 and k: - result.append(vertices[3]) + del cached_vertices[max_cache_size:] - if len(result)>=max_len: - break + n_processed += 1 + progress.set_progress(n_processed/len(self.faces)) - # Hop over the last edge - edge = face.get_edge(*result[-2:]) - face = edge.other_face(face) - if not face or face.flag: - break + self.faces = reordered_faces + for i, f in enumerate(self.faces): + f.index = i + + def reorder_vertices(self): + for v in self.vertices: + v.index = -1 + + reordered_vertices = [] + for s in self.vertex_sequence: + for v in s: + if v.index<0: + v.index = len(reordered_vertices) + reordered_vertices.append(v) + + self.vertices = reordered_vertices + + for e in self.edges: + e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index) + + def drop_references(self): + for v in self.vertices: + v._vertex = None + for g in v.groups: + g._group = None + for e in self.edges: + e._edge = None + for f in self.faces: + f._face = None + for u in self.uv_layers: + u._layer = None + self._mesh = None + + +def create_mesh_from_object(context, obj, progress, *, material_map=None): + if obj.type!="MESH": + raise Exception("Object is not a mesh") + + progress.push_task("Preparing mesh", 0.0, 0.2) + + objs = [(obj, mathutils.Matrix())] + i = 0 + while i