facegeometry.cpp 10.3 KB
Newer Older
1
2
// ================================================================================================
// 
schultezub's avatar
schultezub committed
3
// This file is part of the CAMPVis Software Framework.
4
// 
5
// If not explicitly stated otherwise: Copyright (C) 2012-2013, all rights reserved,
schultezub's avatar
schultezub committed
6
//      Christian Schulte zu Berge <christian.szb@in.tum.de>
7
//      Chair for Computer Aided Medical Procedures
8
9
//      Technische Universität München
//      Boltzmannstr. 3, 85748 Garching b. München, Germany
10
// 
schultezub's avatar
schultezub committed
11
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
12
// 
13
14
15
16
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 
// except in compliance with the License. You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
17
// 
18
19
20
21
// Unless required by applicable law or agreed to in writing, software distributed under the 
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
// either express or implied. See the License for the specific language governing permissions 
// and limitations under the License.
22
23
24
25
26
27
28
29
30
// 
// ================================================================================================

#include "facegeometry.h"

#include "tgt/assert.h"
#include "tgt/logmanager.h"
#include "tgt/buffer.h"
#include "tgt/vertexarrayobject.h"
31
#include "tgt/vector.h"
32

schultezub's avatar
schultezub committed
33
namespace campvis {
34

schultezub's avatar
schultezub committed
35
    const std::string FaceGeometry::loggerCat_ = "CAMPVis.core.datastructures.FaceGeometry";
36

37
38
39
40
41
42
43
    FaceGeometry::FaceGeometry()
        : GeometryData()
        , _faceNormal(0.f)
    {

    }

44
    FaceGeometry::FaceGeometry(const std::vector<tgt::vec3>& vertices, const std::vector<tgt::vec3>& textureCoordinates /*= std::vector<tgt::vec3>()*/, const std::vector<tgt::vec4>& colors /*= std::vector<tgt::vec4>()*/, const std::vector<tgt::vec3>& normals /*= std::vector<tgt::vec3>() */)
45
        : GeometryData()
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
        , _vertices(vertices)
        , _textureCoordinates(textureCoordinates)
        , _colors(colors)
        , _normals(normals)
        , _faceNormal(0.f)
    {
        tgtAssert(textureCoordinates.empty() || textureCoordinates.size() == vertices.size(), "Texture coordinates vector must be either empty or of the same size as the vertex vector.");
        tgtAssert(colors.empty() || colors.size() == vertices.size(), "Colors vector must be either empty or of the same size as the vertex vector.");
        tgtAssert(normals.empty() || normals.size() == vertices.size(), "Normals vector must be either empty or of the same size as the vertex vector.");

        // compute normal (class invariant states, that all vertices lie in the same plane):
        if (_vertices.size() > 2) {
            _faceNormal = tgt::normalize(tgt::cross(vertices[1] - vertices[0], vertices[2] - vertices[0]));
        }
    }

    FaceGeometry::~FaceGeometry() {
63

64
65
66
67
68
69
    }

    FaceGeometry* FaceGeometry::clone() const {
        return new FaceGeometry(_vertices, _textureCoordinates, _colors, _normals);
    }

70
71
72
73
74
75
76
77
78
79
80
81
82
83
    size_t FaceGeometry::getLocalMemoryFootprint() const {
        size_t sum = 0;
        if (_verticesBuffer != 0)
            sum += sizeof(tgt::BufferObject);
        if (_texCoordsBuffer != 0)
            sum += sizeof(tgt::BufferObject);
        if (_colorsBuffer != 0)
            sum += sizeof(tgt::BufferObject);
        if (_normalsBuffer != 0)
            sum += sizeof(tgt::BufferObject);

        return sizeof(*this) + sum + (sizeof(tgt::vec3) * (_vertices.size() + _textureCoordinates.size() + _normals.size())) + (sizeof(tgt::vec4) * _colors.size());
    }

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    size_t FaceGeometry::size() const {
        return _vertices.size();
    }

    const std::vector<tgt::vec3>& FaceGeometry::getVertices() const {
        return _vertices;
    }

    const std::vector<tgt::vec4>& FaceGeometry::getColors() const {
        return _colors;
    }

    const std::vector<tgt::vec3>& FaceGeometry::getNormals() const {
        return _normals;
    }

    const std::vector<tgt::vec3>& FaceGeometry::getTextureCoordinates() const {
        return _textureCoordinates;
    }

    const tgt::vec3& FaceGeometry::getFaceNormal() const {
        return _faceNormal;
    }

108
    void FaceGeometry::render(GLenum mode) const {
109
110
111
        if (_vertices.empty())
            return;

112
        createGLBuffers();
113
        if (_buffersDirty) {
114
115
116
117
118
119
            LERROR("Cannot render without initialized OpenGL buffers.");
            return;
        }

        tgt::VertexArrayObject vao;
        if (_verticesBuffer)
120
            vao.setVertexAttributePointer(0, _verticesBuffer);
121
        if (_texCoordsBuffer)
122
            vao.setVertexAttributePointer(1, _texCoordsBuffer);
123
        if (_colorsBuffer)
124
            vao.setVertexAttributePointer(2, _colorsBuffer);
125
        if (_normalsBuffer)
126
            vao.setVertexAttributePointer(3, _normalsBuffer);
127
        LGL_ERROR;
128

129
        glDrawArrays(mode, 0, static_cast<GLsizei>(_vertices.size()));
130
        LGL_ERROR;
131
132
    }

133
    void FaceGeometry::createGLBuffers() const {
134
135
        if (_buffersDirty) {
            deleteBuffers();
136

137
            try {
138
139
                _verticesBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                _verticesBuffer->data(&_vertices.front(), _vertices.size() * sizeof(tgt::vec3), tgt::BufferObject::FLOAT, 3);
140
141

                if (! _textureCoordinates.empty()) {
142
143
                    _texCoordsBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                    _texCoordsBuffer->data(&_textureCoordinates.front(), _textureCoordinates.size() * sizeof(tgt::vec3), tgt::BufferObject::FLOAT, 3);
144
145
                }
                if (! _colors.empty()) {
146
147
                    _colorsBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                    _colorsBuffer->data(&_colors.front(), _colors.size() * sizeof(tgt::vec4), tgt::BufferObject::FLOAT, 4);
148
149
                }
                if (! _normals.empty()) {
150
151
                    _normalsBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                    _normalsBuffer->data(&_normals.front(), _normals.size() * sizeof(tgt::vec3), tgt::BufferObject::FLOAT, 3);
152
153
154
155
                }
            }
            catch (tgt::Exception& e) {
                LERROR("Error creating OpenGL Buffer objects: " << e.what());
156
                _buffersDirty = true;
157
158
159
                return;
            }

160
            LGL_ERROR;
161
            _buffersDirty = false;
162
163
164
        }
    }

165
166
167
168
169
170
171
172
173
174
    namespace {
        float distanceToPlane(const tgt::vec3& vertex, float p, const tgt::vec3& pNormal, float epsilon) {
            float distance = tgt::dot(pNormal, vertex) - p;
            if (std::abs(distance) <= epsilon)
                return 0;
            else
                return distance;
        }
    }

175
    campvis::FaceGeometry FaceGeometry::clipAgainstPlane(float p, const tgt::vec3& pNormal, float epsilon /*= 1e-4f*/) const {
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
        tgtAssert(epsilon >= 0, "Epsilon must be positive.");

        std::vector<tgt::vec3> verts, texCoords, norms;
        std::vector<tgt::vec4> cols;
        size_t lastIndex = _vertices.size() - 1;
        float lastDistance = distanceToPlane(_vertices.back(), p, pNormal, epsilon);

        // Implementation of Sutherland-Hodgman polygon clipping:
        for (size_t i = 0; i < _vertices.size(); ++i) {
            float currrentDistance = distanceToPlane(_vertices[i], p, pNormal, epsilon);

            // case 1: last vertex outside, this vertex inside clip region => clip
            if (lastDistance > 0 && currrentDistance <= 0) {
                float t = lastDistance / (lastDistance - currrentDistance);
                
                verts.push_back(tgt::mix(_vertices[lastIndex], _vertices[i], t));
                if (!_textureCoordinates.empty())
                    texCoords.push_back(tgt::mix(_textureCoordinates[lastIndex], _textureCoordinates[i], t));
                if (!_colors.empty())
                    cols.push_back(tgt::mix(_colors[lastIndex], _colors[i], t));
                if (!_normals.empty())
                    norms.push_back(tgt::mix(_normals[lastIndex], _normals[i], t));
            }
            // case 2: last vertex inside, this vertex outside clip region => clip
            else if (lastDistance <= 0 && currrentDistance > 0) {
                float t = lastDistance / (lastDistance - currrentDistance);

                verts.push_back(tgt::mix(_vertices[lastIndex], _vertices[i], t));
                if (!_textureCoordinates.empty())
                    texCoords.push_back(tgt::mix(_textureCoordinates[lastIndex], _textureCoordinates[i], t));
                if (!_colors.empty())
                    cols.push_back(tgt::mix(_colors[lastIndex], _colors[i], t));
                if (!_normals.empty())
                    norms.push_back(tgt::mix(_normals[lastIndex], _normals[i], t));
            }

            // case 1.2 + case 3: current vertix in front of plane => keep
            if (currrentDistance <= 0) {
                verts.push_back(_vertices[i]);
                if (!_textureCoordinates.empty())
                    texCoords.push_back(_textureCoordinates[i]);
                if (!_colors.empty())
                    cols.push_back(_colors[i]);
                if (!_normals.empty())
                    norms.push_back(_normals[i]);
            }

            lastIndex = i;
            lastDistance = currrentDistance;
        }

        return FaceGeometry(verts, texCoords, cols, norms);
    }

230
231
232
233
234
235
236
    tgt::Bounds FaceGeometry::getWorldBounds() const {
        tgt::Bounds toReturn;
        for (std::vector<tgt::vec3>::const_iterator it = _vertices.begin(); it != _vertices.end(); ++it)
            toReturn.addPoint(*it);
        return toReturn;
    }

237
238
239
240
241
242
243
244
245
246
247
248
249
    bool FaceGeometry::hasTextureCoordinates() const {
        return ! _textureCoordinates.empty();
    }

    void FaceGeometry::applyTransformationToVertices(const tgt::mat4& t) {
        for (size_t i = 0; i < _vertices.size(); ++i) {
            tgt::vec4 tmp = t * tgt::vec4(_vertices[i], 1.f);
            _vertices[i] = tmp.xyz() / tmp.w;
        }

        _buffersDirty = true;
    }

250
}