-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenderwindow.cpp
462 lines (382 loc) · 14.6 KB
/
renderwindow.cpp
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#include "renderwindow.h"
#include <QTimer>
#include <QMatrix4x4>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
#include <QOpenGLDebugLogger>
#include <QKeyEvent>
#include <QStatusBar>
#include <QDebug>
#include <string>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Core/shader.h"
#include "mainwindow.h"
#include "logger.h"
RenderWindow::RenderWindow(const QSurfaceFormat& format, MainWindow* mainWindow)
: mContext(nullptr), mInitialized(false), mMainWindow(mainWindow)
{
//This is sent to QWindow:
setSurfaceType(QWindow::OpenGLSurface);
setFormat(format);
//Make the OpenGL context
mContext = new QOpenGLContext(this);
//Give the context the wanted OpenGL format (v4.1 Core)
mContext->setFormat(requestedFormat());
if (!mContext->create()) {
delete mContext;
mContext = nullptr;
qDebug() << "Context could not be made - quitting this application";
}
//Make the gameloop timer:
mRenderTimer = new QTimer(this);
}
RenderWindow::~RenderWindow()
{
//cleans up the GPU memory
glDeleteVertexArrays( 1, &mVAO );
glDeleteBuffers( 1, &mVBO );
}
// Sets up the general OpenGL stuff and the buffers needed to render a triangle
void RenderWindow::init()
{
mLogger = Logger::getInstance();
//Connect the gameloop timer to the render function:
//This makes our render loop
connect(mRenderTimer, SIGNAL(timeout()), this, SLOT(render()));
//********************** General OpenGL stuff **********************
//The OpenGL context has to be set.
//The context belongs to the instanse of this class!
if (!mContext->makeCurrent(this)) {
mLogger->logText("makeCurrent() failed", LogType::REALERROR);
return;
}
if (!mInitialized)
mInitialized = true;
initializeOpenGLFunctions();
mLogger->logText("The active GPU and API:", LogType::HIGHLIGHT);
std::string tempString;
tempString += std::string(" Vendor: ") + std::string((char*)glGetString(GL_VENDOR)) + "\n" +
std::string(" Renderer: ") + std::string((char*)glGetString(GL_RENDERER)) + "\n" +
std::string(" Version: ") + std::string((char*)glGetString(GL_VERSION));
mLogger->logText(tempString);
startOpenGLDebugger();
//general OpenGL stuff:
glEnable(GL_DEPTH_TEST); //enables depth sorting - must then use GL_DEPTH_BUFFER_BIT in glClear
//glEnable(GL_CULL_FACE); //draws only front side of models - usually what you want - test it out!
glClearColor(0.4f, 0.4f, 0.4f, 1.0f); //gray color used in glClear GL_COLOR_BUFFER_BIT
glDepthMask(GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINES);
//Set up Shaders
mShaderPrograms.insert(std::pair<std::string, Shader*>("plain", new PlainShader("../3DProgExam/Shaders/plainshader.vert", "../3DProgExam/Shaders/plainshader.frag")));
mShaderPrograms.insert(std::pair<std::string, Shader*>("textured", new TextureShader("../3DProgExam/Shaders/textureshader.vert", "../3DProgExam/Shaders/textureshader.frag")));
mShaderPrograms.insert(std::pair<std::string, Shader*>("phong", new PhongShader("../3DProgExam/Shaders/phongshader.vert", "../3DProgExam/Shaders/phongshader.frag")));
mShaderPrograms.insert(std::pair<std::string, Shader*>("skybox", new SkyBoxShader("../3DProgExam/Shaders/skyboxShader.vert", "../3DProgExam/Shaders/skyboxShader.frag")));
//Set up Scene(s)
Scenes.push_back(new Scene0(mShaderPrograms));
///Initialize all the scenes
for (int i = 0; i < Scenes.size(); i++)
{
Scenes[i]->init();
}
glBindVertexArray(0); //unbinds any VertexArray - good practice
////How to use textures;
//mTexture[0] = new Texture();
//mTexture[1] = new Texture("../3Dprog22/Assets/tex/hund.bmp");
////Set the textures loaded to a texture slot
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, mTexture[0]->id());
//glActiveTexture(GL_TEXTURE1);
//glBindTexture(GL_TEXTURE_2D, mTexture[1]->id());
}
// Called each frame - doing the rendering!!!
void RenderWindow::render()
{
mTimeStart.restart(); //restart FPS clock
mContext->makeCurrent(this); //must be called every frame (every time mContext->swapBuffers is called)
initializeOpenGLFunctions();
//clear the screen for each redraw
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mCurrentCamera = Scenes[activeScene]->mCamera;
///Draw active Scene
Scenes[activeScene]->draw();
/// Other Things
calculateFramerate();
checkForGLerrors();
mContext->swapBuffers(this);
}
void RenderWindow::exposeEvent(QExposeEvent *)
{
//if not already initialized - run init() function - happens on program start up
if (!mInitialized)
init();
//This is just to support modern screens with "double" pixels (Macs and some 4k Windows laptops)
const qreal retinaScale = devicePixelRatio();
//Set viewport width and height to the size of the QWindow we have set up for OpenGL
glViewport(0, 0, static_cast<GLint>(width() * retinaScale), static_cast<GLint>(height() * retinaScale));
//If the window actually is exposed to the screen we start the main loop
//isExposed() is a function in QWindow
if (isExposed())
{
//This timer runs the actual MainLoop == the render()-function
//16 means 16ms = 60 Frames pr second (should be 16.6666666 to be exact...)
mRenderTimer->start(16);
mTimeStart.start();
}
}
void RenderWindow::DrawLine(const glm::vec3& start, const glm::vec3& end, const glm::vec4& color)
{
static uint32_t VAO{};
static uint32_t VBO{};
glm::vec3 data[] = { start, end };
if (VAO == 0)
{
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_DYNAMIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void*)0);
glEnableVertexAttribArray(0);
}
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(data), data);
glUseProgram(mShaderPrograms[0]->getProgram());
auto location = glGetUniformLocation(mShaderPrograms["plain"]->getProgram(), "colorIn");
glUniform4f(location, color.x, color.y, color.z, color.w);
static constexpr glm::mat4 identity(1.f);
location = glGetUniformLocation(mShaderPrograms["plain"]->getProgram(), "model");
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(identity));
glDrawArrays(GL_LINES, 0, 2);
glBindVertexArray(0);
}
void RenderWindow::calculateFramerate()
{
long nsecElapsed = mTimeStart.nsecsElapsed();
static int frameCount{0}; //counting actual frames for a quick "timer" for the statusbar
if (mMainWindow) //if no mainWindow, something is really wrong...
{
++frameCount;
if (frameCount > 30) //once pr 30 frames = update the message == twice pr second (on a 60Hz monitor)
{
//showing some statistics in status bar
mMainWindow->statusBar()->showMessage(" Time pr FrameDraw: " +
QString::number(nsecElapsed/1000000.f, 'g', 4) + " ms | " +
"FPS (approximated): " + QString::number(1E9 / nsecElapsed, 'g', 7));
frameCount = 0; //reset to show a new message in 30 frames
}
}
}
void RenderWindow::checkForGLerrors()
{
if(mOpenGLDebugLogger) //if our machine got this class to work
{
const QList<QOpenGLDebugMessage> messages = mOpenGLDebugLogger->loggedMessages();
for (const QOpenGLDebugMessage &message : messages)
{
if (!(message.type() == message.OtherType)) // get rid of uninteresting "object ...
// will use VIDEO memory as the source for
// buffer object operations"
// valid error message:
mLogger->logText(message.message().toStdString(), LogType::REALERROR);
}
}
else
{
GLenum err = GL_NO_ERROR;
while((err = glGetError()) != GL_NO_ERROR)
{
mLogger->logText("glGetError returns " + std::to_string(err), LogType::REALERROR);
switch (err) {
case 1280:
mLogger->logText("GL_INVALID_ENUM - Given when an enumeration parameter is not a "
"legal enumeration for that function.");
break;
case 1281:
mLogger->logText("GL_INVALID_VALUE - Given when a value parameter is not a legal "
"value for that function.");
break;
case 1282:
mLogger->logText("GL_INVALID_OPERATION - Given when the set of state for a command "
"is not legal for the parameters given to that command. "
"It is also given for commands where combinations of parameters "
"define what the legal parameters are.");
break;
}
}
}
}
void RenderWindow::startOpenGLDebugger()
{
QOpenGLContext * temp = this->context();
if (temp)
{
QSurfaceFormat format = temp->format();
if (! format.testOption(QSurfaceFormat::DebugContext))
mLogger->logText("This system can not use QOpenGLDebugLogger, so we revert to glGetError()",
LogType::HIGHLIGHT);
if(temp->hasExtension(QByteArrayLiteral("GL_KHR_debug")))
{
mLogger->logText("This system can log extended OpenGL errors", LogType::HIGHLIGHT);
mOpenGLDebugLogger = new QOpenGLDebugLogger(this);
if (mOpenGLDebugLogger->initialize()) // initializes in the current context
mLogger->logText("Started Qt OpenGL debug logger");
}
}
}
void RenderWindow::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton)
{
Scenes[activeScene]->mCamera->MouseMove = true;
}
}
void RenderWindow::mouseReleaseEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton)
{
Scenes[activeScene]->mCamera->MouseMove = false;
}
}
void RenderWindow::mouseMoveEvent(QMouseEvent* event)
{
if (Scenes[activeScene]->mCamera->MouseMove)
{
Scenes[activeScene]->mCamera->mouseX = event->y();
Scenes[activeScene]->mCamera->mouseY = event->x();
}
}
void RenderWindow::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Escape)
{
mMainWindow->close(); //Shuts down the whole program
}
if (event->key() == Qt::Key_C)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
if (event->key() == Qt::Key_V)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
if(event->key() == Qt::Key_A)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->AMove = true;;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->AMove = true;
}
if (event->key() == Qt::Key_D)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->DMove = true;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->DMove = true;
}
if(event->key() == Qt::Key_S)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->SMove = true;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->SMove = true;
}
if (event->key() == Qt::Key_W)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->WMove = true;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->WMove = true;
}
if (event->key() == Qt::Key_G)
{
Scenes[activeScene]->bPlayMode = !Scenes[activeScene]->bPlayMode;
}
if (event->key() == Qt::Key_Q)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->QMove = true;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->QMove = true;
}
if (event->key() == Qt::Key_E)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->EMove = true;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->EMove = true;
}
}
void RenderWindow::keyReleaseEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_A)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->AMove = false;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->AMove = false;
}
if (event->key() == Qt::Key_D)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->DMove = false;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->DMove = false;
}
if (event->key() == Qt::Key_S)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->SMove = false;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->SMove = false;
}
if (event->key() == Qt::Key_W)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->WMove = false;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->WMove = false;
}
if (event->key() == Qt::Key_Q)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->QMove = false;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->QMove = false;
}
if (event->key() == Qt::Key_E)
{
if (!Scenes[activeScene]->mCamera->bFollowPlayer)
{
Scenes[activeScene]->mCamera->EMove = false;
}
else
static_cast<InteractiveObject*>(Scenes[activeScene]->mMap3["mia"])->EMove = false;
}
}