File: window.cpp

package info (click to toggle)
forge 1.0.1-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,312 kB
  • sloc: cpp: 12,447; ansic: 319; xml: 182; makefile: 19
file content (377 lines) | stat: -rw-r--r-- 10,872 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*******************************************************
* Copyright (c) 2015-2019, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/

#include <common.hpp>
#include <sdl/window.hpp>
#include <gl_native_handles.hpp>

#include <glm/gtc/matrix_transform.hpp>
#include <iostream>

using namespace gl;

using glm::rotate;
using glm::translate;
using glm::scale;

#define SDL_THROW_ERROR(msg, err) \
    FG_ERROR("Window constructor "#msg,err)

namespace forge
{
namespace wtk
{

void initWindowToolkit()
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        std::cerr << "ERROR: SDL wasn't able to initialize\n";
        SDL_THROW_ERROR("SDL initialization failed", FG_ERR_GL_ERROR);
    }
}

void destroyWindowToolkit()
{
    SDL_Quit();
}

const glm::mat4 Widget::findTransform(const MatrixHashMap& pMap, const float pX, const float pY)
{
    for (auto it: pMap) {
        const CellIndex& idx = it.first;
        const glm::mat4& mat  = it.second;

        const int rows = std::get<0>(idx);
        const int cols = std::get<1>(idx);

        const int cellWidth  = mWidth/cols;
        const int cellHeight = mHeight/rows;

        const int x = int(pX) / cellWidth;
        const int y = int(pY) / cellHeight;
        const int i = x + y * cols;
        if (i==std::get<2>(idx)) {
            return mat;
        }
    }

    return IDENTITY;
}

const glm::mat4 Widget::getCellViewMatrix(const float pXPos, const float pYPos)
{
    return findTransform(mViewMatrices, pXPos, pYPos);
}

const glm::mat4 Widget::getCellOrientationMatrix(const float pXPos, const float pYPos)
{
    return findTransform(mOrientMatrices, pXPos, pYPos);
}

void Widget::setTransform(MatrixHashMap& pMap, const float pX, const float pY, const glm::mat4 &pMat)
{
    for (auto it: pMap) {
        const CellIndex& idx = it.first;

        const int rows = std::get<0>(idx);
        const int cols = std::get<1>(idx);

        const int cellWidth  = mWidth/cols;
        const int cellHeight = mHeight/rows;

        const int x = int(pX) / cellWidth;
        const int y = int(pY) / cellHeight;
        const int i = x + y * cols;
        if (i==std::get<2>(idx)) {
            pMap[idx] = pMat;
        }
    }
}

void Widget::setCellViewMatrix(const float pXPos, const float pYPos, const glm::mat4& pMatrix)
{
    return setTransform(mViewMatrices, pXPos, pYPos, pMatrix);
}

void Widget::setCellOrientationMatrix(const float pXPos, const float pYPos, const glm::mat4& pMatrix)
{
    return setTransform(mOrientMatrices, pXPos, pYPos, pMatrix);
}


void Widget::resetViewMatrices()
{
    for (auto it: mViewMatrices)
        it.second = IDENTITY;
}


void Widget::resetOrientationMatrices()
{
    for (auto it: mOrientMatrices)
        it.second = IDENTITY;
}

Widget::Widget()
    : mWindow(nullptr), mClose(false), mLastXPos(0), mLastYPos(0), mButton(-1),
    mWidth(512), mHeight(512), mFramePBO(0)
{
}

Widget::Widget(int pWidth, int pHeight, const char* pTitle, const Widget* pWindow, const bool invisible)
    : mWindow(nullptr), mClose(false), mLastXPos(0), mLastYPos(0), mButton(-1), mFramePBO(0)
{
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    if (pWindow != nullptr) {
        pWindow->makeContextCurrent();
        SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
    } else {
        //SDL_GL_MakeCurrent(NULL, NULL);
        SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0);
    }

    mWindow = SDL_CreateWindow(
                            (pTitle!=nullptr ? pTitle : "Forge-Demo"),
                            SDL_WINDOWPOS_UNDEFINED,
                            SDL_WINDOWPOS_UNDEFINED,
                            pWidth, pHeight,
                            (invisible ? SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN
                             : SDL_WINDOW_OPENGL) | SDL_WINDOW_RESIZABLE
                            );
    if (mWindow==NULL) {
        std::cerr<<"Error: Could not Create SDL Window!"<< SDL_GetError() << std::endl;
        SDL_THROW_ERROR("SDL window creation failed", FG_ERR_GL_ERROR);
    }

    mContext = SDL_GL_CreateContext(mWindow);
    if (mContext==NULL) {
        std::cerr<<"Error: Could not OpenGL context!" << SDL_GetError() << std::endl;
        SDL_THROW_ERROR("OpenGL context creation failed", FG_ERR_GL_ERROR);
    }

    SDL_GL_SetSwapInterval(1);
    mWindowId = SDL_GetWindowID(mWindow);
    SDL_GetWindowSize(mWindow, &mWidth, &mHeight);
}

Widget::~Widget()
{
    glDeleteBuffers(1, &mFramePBO);

    SDL_DestroyWindow(mWindow);
    SDL_GL_DeleteContext(mContext);
}

SDL_Window* Widget::getNativeHandle() const
{
    return mWindow;
}

void Widget::makeContextCurrent() const
{
    SDL_GL_MakeCurrent(mWindow, mContext);
}

long long Widget::getGLContextHandle()
{
    return opengl::getCurrentContextHandle();
}

long long Widget::getDisplayHandle()
{
    return opengl::getCurrentDisplayHandle();
}

void Widget::setTitle(const char* pTitle)
{
    SDL_SetWindowTitle(mWindow, (pTitle!=nullptr ? pTitle : "Forge-Demo"));
}

void Widget::setPos(int pX, int pY)
{
    SDL_SetWindowPosition(mWindow, pX, pY);
}

void Widget::setSize(unsigned pW, unsigned pH)
{
    SDL_SetWindowSize(mWindow, pW, pH);
}

void Widget::swapBuffers()
{
    SDL_GL_SwapWindow(mWindow);

    glReadBuffer(GL_FRONT);
    glBindBuffer(GL_PIXEL_PACK_BUFFER, mFramePBO);
    glReadPixels(0, 0, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
}

void Widget::hide()
{
    mClose = true;
    SDL_HideWindow(mWindow);
}

void Widget::show()
{
    mClose = false;
    SDL_ShowWindow(mWindow);
}

bool Widget::close()
{
    return mClose;
}

void Widget::resetCloseFlag()
{
    if(mClose==true) {
        show();
    }
}

void Widget::pollEvents()
{
    static const float SPEED = 0.005f;
    SDL_Event evnt;

    while (SDL_PollEvent(&evnt)) {
        /* handle window events that are triggered
           when the window with window id 'mWindowId' is in focus
           */
        if (evnt.key.windowID == mWindowId) {
            if (evnt.type == SDL_WINDOWEVENT) {
                switch(evnt.window.event) {
                    case SDL_WINDOWEVENT_CLOSE:
                        mClose = true;
                        break;
                    case SDL_WINDOWEVENT_RESIZED:
                        mWidth      = evnt.window.data1;
                        mHeight     = evnt.window.data2;
                        resizePixelBuffers();
                        break;
                }
            }

            if (evnt.type == SDL_KEYDOWN) {
                switch(evnt.key.keysym.sym) {
                    case SDLK_ESCAPE:
                        mClose = true; break;
                    default:
                        mMod = evnt.key.keysym.sym;
                        break;
                }
            } else if (evnt.type == SDL_KEYUP) {
                mMod = -1;
            }

            int x, y;
            SDL_GetMouseState(&x, &y);
            // reset UI transforms upon mouse middle click
            if(evnt.type == SDL_MOUSEBUTTONUP) {
                if(evnt.button.button == SDL_BUTTON_MIDDLE &&
                        (mMod == SDLK_LCTRL || mMod==SDLK_RCTRL)) {
                    setCellViewMatrix(x, y, IDENTITY);
                    setCellOrientationMatrix(x, y, IDENTITY);
                }
            }

            const glm::mat4 viewMat = getCellViewMatrix(x, y);

            if(evnt.type == SDL_MOUSEMOTION) {
                if(evnt.motion.state == SDL_BUTTON_LMASK) {
                    double deltaX = -evnt.motion.xrel;
                    double deltaY = -evnt.motion.yrel;

                    glm::mat4 vMat(1);

                    if (mMod==SDLK_LALT || mMod==SDLK_RALT || mMod==SDLK_LCTRL || mMod==SDLK_RCTRL) {
                        // Zoom
                        if(deltaY != 0) {
                            if(deltaY < 0) {
                                deltaY = 1.0 / (-deltaY);
                            }
                            vMat = scale(viewMat, glm::vec3(pow(deltaY, SPEED)));
                        }
                    } else {
                        // Translate
                        vMat = translate(viewMat, glm::vec3(-deltaX, deltaY, 0.0f) * SPEED);
                    }
                    setCellViewMatrix(x, y, vMat);
                } else if (evnt.motion.state == SDL_BUTTON_RMASK) {
                    const glm::mat4 orientationMat = getCellOrientationMatrix(x, y);
                    // Rotations
                    int width, height;
                    SDL_GetWindowSize(mWindow, &width, &height);

                    int xPos = evnt.motion.x;
                    int yPos = evnt.motion.y;

                    if (mLastXPos != xPos || mLastYPos != yPos) {
                        glm::vec3 op1 = trackballPoint(mLastXPos, mLastYPos, width, height);
                        glm::vec3 op2 = trackballPoint(xPos, yPos, width, height);

                        float angle = std::acos(std::min(1.0f, glm::dot(op1, op2)));

                        glm::vec3 axisInCamCoord = glm::cross(op1, op2);

                        glm::mat3 camera2object = glm::inverse(glm::mat3(viewMat));
                        glm::vec3 axisInObjCoord = camera2object * axisInCamCoord;

                        glm::mat4 oMat = glm::rotate(orientationMat,
                                                     glm::degrees(angle), axisInObjCoord);
                        setCellOrientationMatrix(x, y, oMat);
                    }
                }

                mLastXPos = evnt.motion.x;
                mLastYPos = evnt.motion.y;
            }
        }
    }
}

void Widget::resizePixelBuffers()
{
    if (mFramePBO!=0)
        glDeleteBuffers(1, &mFramePBO);

    uint w = mWidth;
    uint h = mHeight;

    glGenBuffers(1, &mFramePBO);
    glBindBuffer(GL_PIXEL_PACK_BUFFER, mFramePBO);
    glBufferData(GL_PIXEL_PACK_BUFFER, w*h*4*sizeof(uchar), 0, GL_DYNAMIC_READ);
    glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
}

const glm::mat4 Widget::getViewMatrix(const CellIndex& pIndex)
{
    if (mViewMatrices.find(pIndex)==mViewMatrices.end()) {
        mViewMatrices.emplace(pIndex, IDENTITY);
    }
    return mViewMatrices[pIndex];
}

const glm::mat4 Widget::getOrientationMatrix(const CellIndex& pIndex)
{
    if (mOrientMatrices.find(pIndex)==mOrientMatrices.end()) {
        mOrientMatrices.emplace(pIndex, IDENTITY);
    }
    return mOrientMatrices[pIndex];
}

}
}