MeshData.py 6.5 KB
Newer Older
1
from pyqtgraph.Qt import QtGui
Luke Campagnola's avatar
Luke Campagnola committed
2
import pyqtgraph.functions as fn
3

Luke Campagnola's avatar
Luke Campagnola committed
4
5
6
7
8
9
10
11
12
13
class MeshData(object):
    """
    Class for storing 3D mesh data. May contain:
        - list of vertex locations
        - list of edges
        - list of triangles
        - colors per vertex, edge, or tri
        - normals per vertex or tri
    """

Luke Campagnola's avatar
Luke Campagnola committed
14
    def __init__(self):
15
16
17
18
19
20
21
22
23
24
        self._vertexes = []
        self._edges = None
        self._faces = []
        self._vertexFaces = None  ## maps vertex ID to a list of face IDs
        self._vertexNormals = None
        self._faceNormals = None
        self._vertexColors = None
        self._edgeColors = None
        self._faceColors = None
        self._meshColor = (1, 1, 1, 0.1)  # default color to use if no face/edge/vertex colors are given
Luke Campagnola's avatar
Luke Campagnola committed
25
26
27
28
29
30
31
32
33
34
35
36
        
    def setFaces(self, faces, vertexes=None):
        """
        Set the faces in this data set.
        Data may be provided either as an Nx3x3 list of floats (9 float coordinate values per face)
            *faces* = [ [(x, y, z), (x, y, z), (x, y, z)], ... ] 
        or as an Nx3 list of ints (vertex integers) AND an Mx3 list of floats (3 float coordinate values per vertex)
            *faces* = [ (p1, p2, p3), ... ]
            *vertexes* = [ (x, y, z), ... ]
        """
        
        if vertexes is None:
37
            self._setUnindexedFaces(faces)
Luke Campagnola's avatar
Luke Campagnola committed
38
        else:
39
40
            self._setIndexedFaces(faces, vertexes)
    
Luke Campagnola's avatar
Luke Campagnola committed
41
42
43
44
45
46
    def setMeshColor(self, color):
        """Set the color of the entire mesh. This removes any per-face or per-vertex colors."""
        color = fn.Color(color)
        self._meshColor = color.glColor()
        self._vertexColors = None
        self._faceColors = None
47
    
Luke Campagnola's avatar
Luke Campagnola committed
48
49
    def _setUnindexedFaces(self, faces):
        verts = {}
50
51
52
53
54
        self._faces = []
        self._vertexes = []
        self._vertexFaces = []
        self._faceNormals = None
        self._vertexNormals = None
Luke Campagnola's avatar
Luke Campagnola committed
55
56
57
        for face in faces:
            inds = []
            for pt in face:
58
                pt2 = tuple([round(x*1e14) for x in pt])  ## quantize to be sure that nearly-identical points will be merged
Luke Campagnola's avatar
Luke Campagnola committed
59
60
                index = verts.get(pt2, None)
                if index is None:
61
62
63
                    self._vertexes.append(QtGui.QVector3D(*pt))
                    self._vertexFaces.append([])
                    index = len(self._vertexes)-1
Luke Campagnola's avatar
Luke Campagnola committed
64
                    verts[pt2] = index
65
                self._vertexFaces[index].append(len(self._faces))
Luke Campagnola's avatar
Luke Campagnola committed
66
                inds.append(index)
67
            self._faces.append(tuple(inds))
Luke Campagnola's avatar
Luke Campagnola committed
68
69
    
    def _setIndexedFaces(self, faces, vertexes):
70
71
72
73
74
75
        self._vertexes = [QtGui.QVector3D(*v) for v in vertexes]
        self._faces = faces
        self._edges = None
        self._vertexFaces = None
        self._faceNormals = None
        self._vertexNormals = None
Luke Campagnola's avatar
Luke Campagnola committed
76

77
    def vertexFaces(self):
Luke Campagnola's avatar
Luke Campagnola committed
78
79
80
        """
        Return list mapping each vertex index to a list of face indexes that use the vertex.
        """
81
82
83
        if self._vertexFaces is None:
            self._vertexFaces = [[]] * len(self._vertexes)
            for i, face in enumerate(self._faces):
Luke Campagnola's avatar
Luke Campagnola committed
84
                for ind in face:
85
86
87
88
                    if len(self._vertexFaces[ind]) == 0:
                        self._vertexFaces[ind] = []  ## need a unique/empty list to fill
                    self._vertexFaces[ind].append(i)
        return self._vertexFaces
Luke Campagnola's avatar
Luke Campagnola committed
89
        
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    def __iter__(self):
        """Iterate over all faces, yielding a list of three tuples [(position, normal, color), ...] for each face."""
        vnorms = self.vertexNormals()
        vcolors = self.vertexColors()
        for i in range(len(self._faces)):
            face = []
            for j in [0,1,2]:
                vind = self._faces[i][j]
                pos = self._vertexes[vind]
                norm = vnorms[vind]
                if vcolors is None:
                    color = self._meshColor
                else:
                    color = vcolors[vind]
                face.append((pos, norm, color))
            yield face
    
    
    def faceNormals(self):
Luke Campagnola's avatar
Luke Campagnola committed
109
110
111
        """
        Computes and stores normal of each face.
        """
112
113
114
        if self._faceNormals is None:
            self._faceNormals = []
            for i, face in enumerate(self._faces):
Luke Campagnola's avatar
Luke Campagnola committed
115
                ## compute face normal
116
                pts = [self._vertexes[vind] for vind in face]
Luke Campagnola's avatar
Luke Campagnola committed
117
118
                norm = QtGui.QVector3D.crossProduct(pts[1]-pts[0], pts[2]-pts[0])
                norm = norm / norm.length()  ## don't use .normalized(); doesn't work for small values.
119
120
                self._faceNormals.append(norm)
        return self._faceNormals
Luke Campagnola's avatar
Luke Campagnola committed
121
    
122
    def vertexNormals(self):
Luke Campagnola's avatar
Luke Campagnola committed
123
124
125
126
        """
        Assigns each vertex the average of its connected face normals.
        If face normals have not been computed yet, then generateFaceNormals will be called.
        """
127
128
129
130
131
132
        if self._vertexNormals is None:
            faceNorms = self.faceNormals()
            vertFaces = self.vertexFaces()
            self._vertexNormals = []
            for vindex in xrange(len(self._vertexes)):
                #print vertFaces[vindex]
Luke Campagnola's avatar
Luke Campagnola committed
133
                norms = [faceNorms[findex] for findex in vertFaces[vindex]]
134
135
136
                norm = QtGui.QVector3D()
                for fn in norms:
                    norm += fn
Luke Campagnola's avatar
Luke Campagnola committed
137
                norm = norm / norm.length()  ## don't use .normalize(); doesn't work for small values.
138
139
140
141
142
143
144
145
                self._vertexNormals.append(norm)
        return self._vertexNormals
        
    def vertexColors(self):
        return self._vertexColors
        
    def faceColors(self):
        return self._faceColors
Luke Campagnola's avatar
Luke Campagnola committed
146
        
147
148
    def edgeColors(self):
        return self._edgeColors
Luke Campagnola's avatar
Luke Campagnola committed
149
150
        
    def reverseNormals(self):
Luke Campagnola's avatar
Luke Campagnola committed
151
152
153
154
155
156
157
158
159
160
161
162
        """
        Reverses the direction of all normal vectors.
        """
        pass
        
    def generateEdgesFromFaces(self):
        """
        Generate a set of edges by listing all the edges of faces and removing any duplicates.
        Useful for displaying wireframe meshes.
        """
        pass
        
Luke Campagnola's avatar
Luke Campagnola committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    def save(self):
        """Serialize this mesh to a string appropriate for disk storage"""
        import pickle
        names = ['_vertexes', '_edges', '_faces', '_vertexFaces', '_vertexNormals', '_faceNormals', '_vertexColors', '_edgeColors', '_faceColors', '_meshColor']
        state = {n:getattr(self, n) for n in names}
        return pickle.dumps(state)
        
    def restore(self, state):
        """Restore the state of a mesh previously saved using save()"""
        import pickle
        state = pickle.loads(state)
        for k in state:
            setattr(self, k, state[k])