-
Notifications
You must be signed in to change notification settings - Fork 0
/
Window.cpp
426 lines (361 loc) · 12.5 KB
/
Window.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
//
// Created by Jean-Luc Thumm on 11/25/17.
//
#include "Window.h"
#include "util.h"
#include "MeshBank.h"
#include "Geometry.h"
#include "DirLight.hpp"
#include "PointLight.hpp"
#include "PointLightObj.hpp"
#include "Mover.hpp"
#include "MaterialBank.hpp"
#include "Road.hpp"
#include "Grass.hpp"
#include "Bound.hpp"
#include "BoundObj.hpp"
#include "Game.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include <glm/ext.hpp>
using std::cerr;
using std::endl;
using std::cout;
static Window *instance;
Window &Window::I() {
if (!instance) {
throw std::runtime_error{"Tried to get Window instance when none instantiated"};
}
return *instance;
}
void Window::resize_callback(GLFWwindow *window, int width, int height) {
instance->handleResize(window, width, height);
}
void Window::key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) {
instance->handleKey(window, key, scancode, action, mods);
}
void Window::mouse_button_callback(GLFWwindow *window, int button, int action, int mods) {
instance->handleMouseButton(window, button, action, mods);
}
void Window::mouse_move_callback(GLFWwindow *window, double xpos, double ypos) {
instance->handleMouseMove(window, xpos, ypos);
}
void Window::mouse_scroll_callback(GLFWwindow *window, double xoffset, double yoffset) {
instance->handleMouseScroll(window, xoffset, yoffset);
}
void Window::error_callback(int error, const char *description) {
cerr << description << endl;
}
void Window::handleKey(GLFWwindow *w, int key, int scancode, int action, int mods) {
if (action == GLFW_PRESS) {
auto result = keyListeners.find(key);
if (result != keyListeners.end()) {
for (EventListener *listener : result->second) {
listener->receive(key);
}
}
switch (key) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(w, GL_TRUE);
break;
case GLFW_KEY_S:
float factor;
if (mods == GLFW_MOD_SHIFT) {
factor = 1.0f - SCALE_SCALE;
}
else {
factor = 1.0f + SCALE_SCALE;
}
graph.scale(glm::vec3{factor});
break;
case GLFW_KEY_R:
cam.reset();
break;
case GLFW_KEY_C:
orbitFlag = false;
transFlag = false;
break;
default:
break;
}
}
}
void Window::handleMouseButton(GLFWwindow *w, int button, int action, int mods) {
double xpos, ypos;
glfwGetCursorPos(w, &xpos, &ypos);
if (button == GLFW_MOUSE_BUTTON_LEFT) {
if (action == GLFW_PRESS && mods != GLFW_MOD_SHIFT) {
Ray ray = raycast(static_cast<float>(xpos), static_cast<float>(ypos));
std::list<Node *> hits = graph.hit(ray);
if (hits.empty()) {
orbitFlag = true;
lastOrbitPoint = trackBallMapping(static_cast<float>(xpos),
static_cast<float>(ypos));
cam.save(); // use current state as reference for transformations
}
else {
// TODO pick the closest event listener instead of first
selected = dynamic_cast<EventListener *>(*(hits.begin()));
if (selected != nullptr) {
selected->receive(Event{Event::PRESS, ray});
}
}
}
else if (action == GLFW_RELEASE && mods != GLFW_MOD_SHIFT) {
if (selected != nullptr) {
Ray ray = raycast(static_cast<float>(xpos), static_cast<float>(ypos));
selected->receive(Event{Event::RELEASE, ray});
selected = nullptr;
}
orbitFlag = false;
dragFlag = false;
}
else if (action == GLFW_PRESS) {
transFlag = true;
lastTransPoint = glm::vec2{xpos, ypos};
}
else if (action == GLFW_RELEASE) {
transFlag = false;
}
}
}
void Window::handleMouseMove(GLFWwindow *w, double xpos, double ypos) {
if (selected != nullptr) {
Ray ray = raycast(static_cast<float>(xpos), static_cast<float>(ypos));
selected->receive(Event{Event::DRAG, ray});
return;
}
if (orbitFlag) {
dragFlag = true;
glm::vec3 curPoint = trackBallMapping(static_cast<float>(xpos), static_cast<float>(ypos));
glm::vec3 direction = curPoint - lastOrbitPoint;
float velocity = glm::length(direction);
if (velocity < 0.0001) return; // only act when movement is great enough
glm::vec3 rotAxis = glm::cross(lastOrbitPoint, curPoint);
float rotAngle = velocity * ROT_SCALE;
cam.statefulRotate(-rotAngle, rotAxis);
}
if (transFlag) {
auto deltaX = static_cast<float>(xpos - lastTransPoint.x);
auto deltaY = static_cast<float>(lastTransPoint.y - ypos);
glm::vec3 transVec{deltaX, deltaY, 0};
}
}
void Window::handleMouseScroll(GLFWwindow *w, double xoffset, double yoffset) {
glm::vec3 transVec = {0, 0, SCROLL_SCALE * yoffset};
}
void Window::handleResize(GLFWwindow *w, int width, int height) {
#ifdef __APPLE__
glfwGetFramebufferSize(w, &width,
&height); // In case your Mac has a retina display
#endif
this->width = width;
this->height = height;
glViewport(0, 0, width, height);
if (height > 0) {
projection = glm::perspective(45.0f, (float) width / (float) height, 0.1f,
1000.0f);
}
}
glm::vec3 Window::trackBallMapping(float x, float y) {
int w = width / 2;
int h = height / 2;
glm::vec3 v;
#ifdef __APPLE__ // retina bullshit
v.x = (2.0f * x - w) / w;
v.y = (h - 2.0f * y) / h;
v.z = 0.0;
#else
v.x = (x - w) / w;
v.y = (h - y) / h;
v.z = 0.0;
#endif
float d = glm::length(v);
d = (d < 1.0f) ? d : 1.0f;
v.z = std::sqrt(1.001f - d * d);
return glm::normalize(v);
}
Ray Window::raycast(float mouseX, float mouseY) {
#ifdef __APPLE__ // retina bullshit
float x = (2.0f * mouseX) / (width * 0.5f) - 1.0f;
float y = (2.0f * mouseY) / (height * 0.5f) - 1.0f;
#else
float x = mouseX / (width * 0.5f) - 1.0f;
float y = mouseY / (height * 0.5f) - 1.0f;
#endif
glm::mat4 invVP = glm::inverse(projection * cam.viewMatrix());
glm::vec4 screenPos = glm::vec4(x, -y, 1.0f, 1.0f);
glm::vec4 worldPos = invVP * screenPos;
auto dir = glm::vec3{worldPos};
return Ray{cam.position(), dir};
}
void Window::registerHandlers(GLFWwindow *w) {
glfwSetErrorCallback(error_callback);
glfwSetKeyCallback(w, key_callback);
glfwSetFramebufferSizeCallback(w, resize_callback);
glfwSetMouseButtonCallback(w, mouse_button_callback);
glfwSetCursorPosCallback(w, mouse_move_callback);
glfwSetScrollCallback(w, mouse_scroll_callback);
}
GLFWwindow *Window::makeGLFWWindow(int width, int height) {
if (!glfwInit()) {
cerr << "Failed to initialize GLFW" << endl;
return nullptr;
}
#ifdef __APPLE__
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// Enable forward compatibility and allow a modern OpenGL context
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
glfwWindowHint(GLFW_SAMPLES, 4);
GLFWwindow *window = glfwCreateWindow(width, height, "Window", nullptr,
nullptr);
if (!window) {
cerr << "Failed to open GLFW window" << endl;
glfwTerminate();
return nullptr;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwGetFramebufferSize(window, &width, &height);
// print info
std::printf("Renderer: %s\n", (char *) glGetString(GL_RENDERER));
std::printf("OpenGL version: %s\n", (char *) glGetString(GL_VERSION));
#ifdef GL_SHADING_LANGUAGE_VERSION
std::printf("GLSL version: %s\n",
(char *) glGetString(GL_SHADING_LANGUAGE_VERSION));
#endif
handleResize(window, width, height); // sets values for current size
#ifndef __APPLE__
GLenum err = glewInit();
if (GLEW_OK != err) {
cerr << "Error: " << glewGetErrorString(err) << endl;
glfwTerminate();
}
cout << "Current GLEW version: " << glewGetString(GLEW_VERSION) << endl;
#endif
glGetString(GL_RENDERER);
return window;
}
void Window::setOpenGLPrefs() {
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// glClearColor(0.05f, 0.8f, 0.85f, 1.0f);
glClearColor(0, 0, 0, 1);
glEnable(GL_LINE_SMOOTH);
glLineWidth(1.0);
glEnable(GL_PROGRAM_POINT_SIZE);
}
void Window::display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// skybox->draw(cam.viewMatrix(), projection);
graph.draw(glm::mat4{}, cam.viewMatrix(), projection);
glfwPollEvents();
glfwSwapBuffers(glfwWindow);
}
void Window::idle() {
using namespace std::chrono;
if (renderStarted) {
auto now = high_resolution_clock::now();
auto delta = duration_cast<milliseconds>(now - lastFrameTime);
lastFrameTime = now;
graph.update(delta);
}
else {
lastFrameTime = high_resolution_clock::now();
renderStarted = true;
graph.update(milliseconds{0});
}
}
void Window::start() {
if (started) {
throw std::runtime_error{"Cannot start already started Window"};
}
started = true;
while (!glfwWindowShouldClose(glfwWindow)) {
idle();
display();
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
util::print_error(error);
}
}
}
Window::~Window() {
glfwDestroyWindow(glfwWindow);
glfwTerminate();
}
const glm::mat4 &Window::View() {
return cam.viewMatrix();
}
const glm::mat4 &Window::Projection() {
return projection;
}
GLuint Window::SkyboxTexture() {
return skybox->TextureID();
}
glm::vec3 Window::CameraPos() {
return cam.position();
}
void Window::subscribe(int key, EventListener *listener) {
auto result = keyListeners.insert(std::make_pair(key, std::vector<EventListener *>{listener}));
if (!result.second) {
// key already exists
(result.first)->second.push_back(listener);
}
}
Window::Window(int width, int height)
: width{width}, height{height}, orbitFlag{false}, transFlag{false}, dragFlag{false},
started{false}, selected{nullptr}, renderStarted{false},
cam{
glm::vec3{8.482504, 6.766706, 5.124335},
glm::vec3{0.0f, 0.0f, 0.0f},
glm::vec3{0.0f, 1.0f, 0.0f}
} {
instance = this;
glfwWindow = makeGLFWWindow(width, height);
if (!glfwWindow) throw std::runtime_error{"Could not make GLFW window"};
setOpenGLPrefs();
registerHandlers(glfwWindow);
instantiateSingletons();
setupScene();
}
void Window::instantiateSingletons() {
MaterialBank::instantiate();
MeshBank::instantiate();
}
void Window::setupScene() {
srand(time(NULL));
// Shaders
auto cubeMapShader = std::make_shared<Shader>("shader/sky.vert", "shader/sky.frag");
auto lightShader = std::make_shared<Shader>("shader/light.vert", "shader/light.frag");
auto phongShader = std::make_shared<Shader>("shader/simple_forward.vert",
"shader/material_only.frag");
auto noLightShader = std::make_shared<Shader>("shader/no_lighting.vert",
"shader/no_lighting.frag");
auto colorShader = std::make_shared<Shader>("shader/color.vert", "shader/color.frag");
boundShader = colorShader;
// Meshes
MeshBank::refID cubeID = MeshBank::I()->load("obj/cube.obj");
MeshBank::refID carID = MeshBank::I()->load("obj/porsche/mod.obj");
MeshBank::refID grassID = MeshBank::I()->load("obj/grass.obj");
MeshBank::refID roadID = MeshBank::I()->load("obj/road.obj");
auto *dirLight = new DirLight{
glm::vec3{1.0, -1.0, -0.2},
glm::vec3{1.0, 1.0, 1.0},
0
};
dirLight->attach(phongShader);
graph.addChild(dirLight);
game = new Game{carID, grassID, cubeID, roadID, phongShader, lightShader};
graph.addChild(game);
}
const std::shared_ptr<Shader> &Window::BoundShader() {
return boundShader;
}
Game *Window::getGame() {
return game;
}