File: Canvas.cpp

package info (click to toggle)
bornagain 23.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 103,948 kB
  • sloc: cpp: 423,131; python: 40,997; javascript: 11,167; awk: 630; sh: 318; ruby: 173; xml: 130; makefile: 51; ansic: 24
file content (355 lines) | stat: -rw-r--r-- 9,003 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Img3D/View/Canvas.cpp
//! @brief     Implements class Canvas.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Img3D/View/Canvas.h"
#include "Base/Util/Assert.h"
#include "Img3D/Model/Geometry.h"
#include "Img3D/Model/GeometryStore.h"
#include "Img3D/Model/Model.h"
#include "Img3D/Plot/AxesPlotter.h"
#include "Img3D/Plot/BodyPlotter.h"
#include "Img3D/View/Camera.h"
#include "Img3D/View/Shader.h"
#include <QMouseEvent>
#include <QVBoxLayout>

namespace {

float ZoomInScale()
{
    if (QSysInfo::productType() == "osx")
        return 1.02f;
    return 1.25f;
}
float ZoomOutScale()
{
    if (QSysInfo::productType() == "osx")
        return 0.98f;
    return 0.8f;
}

// Default camera position in accordance with RealspaceBuilder.h
const float cameraDefaultPosY = -200.0f; // default camera position on Y axis
const float cameraDefaultPosZ = 120.0f;  // default camera position on Z axis

} // namespace


namespace Img3D {

Canvas::Canvas()
    : aspectRatio(1)
    , currentZoomLevel(0)
    , m_model(nullptr)
    , m_is_initializedGL(false)
{
    connect(&geometryStore(), &GeometryStore::deletingGeometry, this, &Canvas::releaseBuffer);

    // layout for caution messages
    setLayout(new QVBoxLayout);
    layout()->setAlignment(Qt::AlignCenter);
}

Canvas::~Canvas()
{
    releaseBuffers();
}

void Canvas::setCamera(Camera* c)
{
    m_camera.reset(c);
    switchCamera(true);
}

void Canvas::setShader(Shader* p)
{
    m_shader.reset(p);
    if (m_shader)
        m_shader->needsInit();
    update();
}

void Canvas::setModel(Model* m)
{
    releaseBuffers();
    m_model = m;
    switchCamera(true);
    if (!m || !m_camera)
        return;
    m_camera->set();
}

void Canvas::switchCamera(bool full)
{
    if (m_camera) {
        m_camera->setAspectRatio(aspectRatio);
        if (full && m_model)
            m_camera->lookAt(m_model->defaultCameraPosition);
    }
    update();
}

void Canvas::initializeGL()
{
    setCamera(new Camera);
    setShader(new Shader);

    initializeOpenGLFunctions();
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    m_is_initializedGL = true;
}

void Canvas::resizeGL(int w, int h)
{
    int w1 = qMax(1, w), h1 = qMax(1, h);
    viewport.setRect(0, 0, w1, h1);
    aspectRatio = float(w1) / float(h1);
    switchCamera(false);
}

void Canvas::paintGL()
{
    glClearColor(1, 1, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (!m_camera || !m_shader || !m_model || m_model->modelIsEmpty())
        return;

    m_shader->init();
    m_shader->bind();
    m_shader->setCamera(*m_camera);
    m_shader->setAxis(false);

    // opaque objects
    for (const PlottableBody* o : m_model->objects())
        drawBody(*o);

    // transparent objects
    glEnable(GL_BLEND);
    glDepthMask(false);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    for (const PlottableBody* o : m_model->transparentObjects())
        drawBody(*o);
    glDisable(GL_BLEND);
    glDepthMask(true);

    // Draw 3D coordinate axes in lower left corner
    glViewport(0, 0, viewport.width() / 9, viewport.height() / 5);
    QMatrix4x4 matObject3DAxes;
    matObject3DAxes.setToIdentity(); // 3D axes transformation matrix is Identity
    m_shader->setMatObject(matObject3DAxes);
    m_shader->setMatModel(m_camera->matAxes());
    m_shader->setAxis(true);
    std::unique_ptr<AxesPlotter> buf3DAxes(new AxesPlotter());
    buf3DAxes->draw3DAxes();

    m_shader->release();
}

void Canvas::mousePressEvent(QMouseEvent* e)
{
    switch (e->button()) {
    case Qt::LeftButton:
        mouseButton = btnTURN;
        break;
    case Qt::RightButton:
        mouseButton = btnZOOM;
        break;
    default:
        mouseButton = btnNONE;
        break;
    }

    if (!m_camera)
        return;

    matModel = m_camera->matModel();
    matProj = m_camera->matProj();
    m_last_mouse_coords = e->pos();
}

void Canvas::mouseMoveEvent(QMouseEvent* e)
{
    if (!m_camera)
        return;

    const float delta_x = e->pos().x() - m_last_mouse_coords.x();
    const float delta_y = e->pos().y() - m_last_mouse_coords.y();

    switch (mouseButton) {
    case btnTURN: {
        if (!isInitialized())
            break;

        // minus sign for consistency with Blender; arbitrary prefactor for decent rotation speed
        if (delta_x != 0)
            m_camera->horizontalTurn(-0.007f * delta_x);
        if (delta_y != 0)
            m_camera->verticalTurn(-0.007f * delta_y);

        m_last_mouse_coords = e->pos();
        break;
    }
    case btnZOOM: {
        const float d = (e->y() - m_last_mouse_coords.y()) / float(viewport.height());
        m_camera->zoomBy(1 + d);
        break;
    }
    default:
        break;
    }

    update();
}

void Canvas::mouseReleaseEvent(QMouseEvent*)
{
    if (!m_camera)
        return;

    m_camera->endTransform(true);
    update();
}

void Canvas::wheelEvent(QWheelEvent* e)
{
    if (m_camera) {
        if (e->angleDelta().y() < 0) {
            // Zoom in
            m_camera->zoomBy(ZoomInScale());
            currentZoomLevel += 1;
        } else {
            // Zoom out
            m_camera->zoomBy(ZoomOutScale());
            currentZoomLevel -= 1;
        }
        m_camera->endTransform(true);
        update();
    }
    e->accept(); // disable the event from propagating further to the parent widgets
}

void Canvas::releaseBuffer(Geometry const* g)
{
    delete m_buffers.take(g);
}

void Canvas::releaseBuffers()
{
    for (BodyPlotter* b : m_buffers.values())
        delete b;
    m_buffers.clear();
}

void Canvas::drawBody(const PlottableBody& object)
{
    if (!object.valid())
        return;

    ASSERT(m_shader);
    m_shader->setColor(object.color());
    m_shader->setMatObject(object.matrix());

    Geometry const& geo = object.geo();
    auto it = m_buffers.find(&geo);
    BodyPlotter* buf;
    if (m_buffers.end() == it)
        m_buffers.insert(&geo, buf = new BodyPlotter(geo)); // created on demand
    else
        buf = *it;

    buf->draw();
}

bool Canvas::isInitialized() const
{
    return m_is_initializedGL && m_model != nullptr;
}

void Canvas::defaultView()
{
    // Default view
    if (!isInitialized())
        return;

    const CameraParams defPos({0, cameraDefaultPosY, cameraDefaultPosZ}, // eye
                              {0, 0, 0},                                 // center
                              {0, 0, 1});                                // up

    // Default position of camera for 3D axes and object are the same
    m_camera->lookAt3DAxes(defPos);
    m_camera->lookAt(defPos);
    m_camera->endTransform(true);

    currentZoomLevel = 0; // reset zoom level to default value
    update();
}

void Canvas::sideView()
{
    // Side view at current zoom level
    if (!isInitialized())
        return;

    F3 eye(0, cameraDefaultPosY, 0);

    // Side view 3D axes is zoom scale independent
    m_camera->lookAt3DAxes(CameraParams(eye,         // eye
                                        {0, 0, 0},   // center
                                        {0, 0, 1})); // up

    // Side view 3D object is zoom scale dependent
    if (currentZoomLevel >= 0)
        eye.setY(eye.y() * std::pow(ZoomInScale(), std::abs(currentZoomLevel)));
    else
        eye.setY(eye.y() * std::pow(ZoomOutScale(), std::abs(currentZoomLevel)));

    m_camera->lookAt(CameraParams(eye,         // eye
                                  {0, 0, 0},   // center
                                  {0, 0, 1})); // up

    m_camera->endTransform(true);
    update();
}

void Canvas::topView()
{
    // Top view at current zoom level
    if (!isInitialized())
        return;

    // Setting a tiny offset in y value of eye such that eye and up vectors are not parallel
    Img3D::F3 eye(0, -0.5, -cameraDefaultPosY);

    // Top view 3D axes is zoom scale independent
    m_camera->lookAt3DAxes(CameraParams(eye,         // eye
                                        {0, 0, 0},   // center
                                        {0, 0, 1})); // up

    // Top view 3D object is zoom scale dependent
    if (currentZoomLevel >= 0)
        eye.setZ(eye.z() * std::pow(ZoomInScale(), std::abs(currentZoomLevel)));
    else
        eye.setZ(eye.z() * std::pow(ZoomOutScale(), std::abs(currentZoomLevel)));

    m_camera->lookAt(CameraParams(eye,         // eye
                                  {0, 0, 0},   // center
                                  {0, 0, 1})); // up

    m_camera->endTransform(true);
    update();
}

} // namespace Img3D