-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
407 lines (331 loc) · 14.2 KB
/
main.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
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <stdexcept>
#include <glm/vec3.hpp>
#include <glm/matrix.hpp>
#include <glm\gtc\matrix_transform.hpp>
#include <glm\gtc\type_ptr.hpp>
#include "Lib/Consts.h"
#include "Lib/Util.h"
#include "Lib/World/Input.h"
#include "Lib/World/World.h"
#include "Lib/Objects/Cube.h"
#include "Lib/Objects/Plane.h"
#include "Lib/Objects/TriangleThing.h"
#include "Lib/Objects/SplittingPlane.h"
#include "Lib/Objects/TriangleObject.h"
#include "Shaders/Shader.h"
#include "Lib/World/Light.h"
#include "Util/objLoader/OBJ_Loader.h"
#include "Intersection/KdTree.h"
#include <chrono>
using namespace std;
void setup();
void addObjects(World& world);
void addComplexObject(World& world);
void visualizeRaycast(KdStructs::RayHit* hit, Camera camera, glm::vec3 directionVector);
void framebufferSizeCallback(GLFWwindow* window, int width, int height);
void mousePositionCallback(GLFWwindow* window, double xPos, double yPos);
void windowFocusCallback(GLFWwindow* window, int isFocused);
// FPS calculation
int numberOfFrames = 0;
double lastTime = 0.0;
Shader shader;
Shader depthMapShader;
World world;
Light light;
glm::mat4 lightSpaceMat;
unsigned int depthMapFBO;
unsigned int depthMap;
GLFWwindow* window = nullptr;
int samplingMode = 1;
double delay = 0.25;
double timePressed = 0;
// Kd-Tree
KdTree* kdtree = nullptr;
int main()
{
setup();
timePressed = glfwGetTime();
while (!glfwWindowShouldClose(window))
{
// Sets one color for window (background).
glClearColor(0.2f, 0.4f, 0.4f, 1.0f);
// Clear color buffer and depth buffer.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Handle input.
Input::ProcessContinuousInput(window);
// Render depth of scene to depthMap texture
depthMapShader.activate();
depthMapShader.setMat4("lightSpaceMat", lightSpaceMat);
glViewport(0, 0, Consts::RENDERING::SHADOW_WITH, Consts::RENDERING::SHADOW_HEIGHT);
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glClear(GL_DEPTH_BUFFER_BIT);
// Prevent peter panning by using back-faces
glCullFace(GL_FRONT);
// Render world's depth
world.renderWorld(depthMapShader);
glCullFace(GL_BACK);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Reset viewport.
glViewport(0, 0, Consts::SCREEN::WIDTH, Consts::SCREEN::HEIGHT);
// Clear color buffer and depth buffer.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.activate();
shader.setVec3("lightPos", light.position);
shader.setMat4("lightSpaceMat", lightSpaceMat);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, depthMap);
// Render world.
world.update(shader);
// Swaps the drawn buffer with the buffer that got written to.
glfwSwapBuffers(window);
// Checks if any events are triggered and executes callbacks.
glfwPollEvents();
// Show last input
std::string lastInput = "Last Input: " + Input::lastInput;
glfwSetWindowTitle(window, lastInput.c_str());
// Antialiasing input
if (World::useAntiAliasing)
glEnable(GL_MULTISAMPLE);
else
glDisable(GL_MULTISAMPLE);
// Change anti aliasing mode. Requires restart.
if (glfwGetKey(window, GLFW_KEY_F6) == GLFW_PRESS)
{
samplingMode = (samplingMode + 1) % 8;
Input::lastInput = "Switched anti aliasing mode to mode " + std::to_string(samplingMode);
glfwDestroyWindow(window);
setup();
}
// Change anti aliasing mode. Requires restart.
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1) == GLFW_PRESS && timePressed + delay < glfwGetTime())
{
Input::lastInput = "Raycast add";
timePressed = glfwGetTime();
// Get ray origin and direction
Camera camera = World::GetCamera();
KdStructs::Vector position = KdStructs::Vector(camera.Position.x, camera.Position.y, camera.Position.z);
glm::vec3 directionVector = camera.Orientation * glm::vec3(0, 0, -1);
// Normalize
directionVector = glm::normalize(directionVector);
KdStructs::Vector direction = KdStructs::Vector(directionVector.x, directionVector.y, directionVector.z);
// Cast ray into scene
KdStructs::RayHit* hit = nullptr;
std::cout << "\n[*] Casting Ray." << std::endl;
auto start = std::chrono::high_resolution_clock::now();
kdtree->raycast(KdStructs::Ray(position, direction, 1000), hit);
auto end = std::chrono::high_resolution_clock::now();
visualizeRaycast(hit, camera, directionVector);
std::cout << "Raycast time: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " microseconds." << std::endl;
std::cout << std::endl;
}
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_2) == GLFW_PRESS) {
Input::lastInput = "Removed raycast information";
world.intersectionPoint = nullptr;
world.intersectionTriangle = nullptr;
world.rayLine = nullptr;
}
}
glfwTerminate();
return 0;
}
void setup()
{
//----------------------------------------------------------------------------------------------------
// SETUP
//----------------------------------------------------------------------------------------------------
glfwInit();
// Tell GLFW that we're using OpenGL version 3.3 .
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// Tell GLFW to use Core_Profile -> Smaller subset without backwards-compatibility (not needed).
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Set Anti-Aliasing
glfwWindowHint(GLFW_SAMPLES, samplingMode);
window = glfwCreateWindow(Consts::SCREEN::WIDTH, Consts::SCREEN::HEIGHT, "", nullptr, nullptr);
if (window == nullptr)
{
glfwTerminate();
throw std::runtime_error("Failed to create the GLFW-Window");
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
throw std::runtime_error("Failed to initialize GLAD");
}
// Set OpenGL viewport.
glViewport(0, 0, Consts::SCREEN::WIDTH, Consts::SCREEN::HEIGHT);
// Register events.
glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
glfwSetCursorPosCallback(window, mousePositionCallback);
glfwSetWindowFocusCallback(window, windowFocusCallback);
glfwSetKeyCallback(window, Input::ProcessSingleInput);
glfwSetScrollCallback(window, Input::ProcessScrollInput);
glEnable(GL_DEPTH_TEST);
// Lock cursor.
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetInputMode(window, GLFW_STICKY_KEYS, GLFW_TRUE);
// Show wireframe?
if (Consts::RENDERING::USE_WIREFRAME_MODE)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//----------------------------------------------------------------------------------------------------
// RENDERING
//----------------------------------------------------------------------------------------------------
// Projection Matrix for adding perspective.
glm::mat4 projectionMat;
projectionMat = glm::perspective(glm::radians(45.0f), (float)Consts::SCREEN::WIDTH / (float)Consts::SCREEN::HEIGHT, 0.1f, 100.0f);
shader = Shader(Consts::PATHS::SHADOW_VERT_SHADER, Consts::PATHS::SHADOW_FRAG_SHADER);
shader.activate();
shader.setInt("diffuseTexture", 0);
shader.setInt("shadowMap", 1);
shader.setInt("normalMap", 2);
shader.setMat4("projectionMat", projectionMat);
shader.setFloat("ambientLightAmount", 0.5f);
light = Light(glm::vec3(-11.0f, 10.0f, 0.0f), 3.0f);
lightSpaceMat = light.activateLight(shader);
addObjects(world);
//addComplexObject(world);
// KD-TREE
std::vector<float> vertices = world.getAllObjectVertices();
std::vector<unsigned int> indices = world.getAllObjectIndices();
std::cout << "\n[*] Building kd-tree (slow)" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
kdtree = new KdTree(&vertices[0], vertices.size() / 3);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "[->] Done!" << std::endl;
std::cout << "Building time: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " microseconds." << std::endl;
kdtree->printStatistics();
// Add bounding boxes.
std::vector<KdStructs::Node*> nodes = kdtree->getNodes();
for (KdStructs::Node* node : nodes) {
glm::vec3 position = glm::vec3(node->point->pos[0], node->point->pos[1], node->point->pos[2]);
glm::vec3 max = glm::vec3(node->max[0], node->max[1], node->max[2]);
glm::vec3 min = glm::vec3(node->min[0], node->min[1], node->min[2]);
world.addBoundingBox(new BoundingBox(position, max, min));
}
//----------------------------------------------------------------------------------------------------
// SHADOWS
//----------------------------------------------------------------------------------------------------
// DepthMap Shader
depthMapShader = Shader(Consts::PATHS::DEPTH_MAP_VERT_SHADER, Consts::PATHS::DEPTH_MAP_FRAG_SHADER);
depthMapShader.activate();
// Framebuffer for rendering the depthMap.
glGenFramebuffers(1, &depthMapFBO);
// Create depthMap texture.
glGenTextures(1, &depthMap);
glBindTexture(GL_TEXTURE_2D, depthMap);
// Set resolution and only use 'DEPTH_COMPONENT', only need depth.
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, Consts::RENDERING::SHADOW_WITH, Consts::RENDERING::SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Everything outside of light frustum has depth of 1.0 -> no shadow.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
float borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
// Attach depth texture to FrameBufferObject's depth buffer.
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
// Tell OpenGL that we don't need any color.
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void addObjects(World& world)
{
Material rocksMat = Material::RocksMat();
Material woodMat = Material::WoodMat();
Material brickMat = Material::BrickMat();
Material brick2Mat = Material::Brick2Mat();
// Add objects.
world.addObject(new Cube(woodMat, glm::vec3(0, -2, 0), glm::vec3(0, 0, 0), glm::vec3(20.0f, 2.0f, 20.0f)));
world.addObject(new Cube(rocksMat, glm::vec3(), glm::vec3()));
world.addObject(new Cube(brick2Mat, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(), glm::vec3(0.5f, 1.0f, 0.5f)));
world.addObject(new Cube(rocksMat, glm::vec3(0.0f, 3.0f, -7.0f), glm::vec3()));
world.addObject(new Cube(brickMat, glm::vec3(-3.0f, 0.0f, 2.0f), glm::vec3(45.0f, 45.0f, 0.0f)));
world.addObject(new Cube(brick2Mat, glm::vec3(-5.0f, 3.0f, 0.0f), glm::vec3(120.0f, 0.0f, 0.0f)));
world.addObject(new Cube(brick2Mat, glm::vec3(2.0f, 0.0f, 4.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 0.25f, 2.0f)));
world.addObject(new Cube(brickMat, glm::vec3(2.0f, 1.0f, 4.0f), glm::vec3(70.0f, 120.0f, 45.0f)));
world.addObject(new TriangleThing(brickMat, glm::vec3(-3.0f, 0.0f, -4.0f), glm::vec3(0.0f, 0.0f, 0.0f)));
world.addObject(new TriangleThing(woodMat, glm::vec3(-4.0f, 2.0f, 4.0f), glm::vec3(90.0f, 0.0f, 45.0f)));
world.addObject(new TriangleThing(rocksMat, glm::vec3(4.0f, 1.0f, -4.0f), glm::vec3(0.0f, 120.0f, 45.0f)));
}
void addComplexObject(World& world) {
objl::Loader loader;
std::cout << "\n[*] Loading file" << std::endl;
std::string filePath = "Resources/Nubian/nubian_complex.obj";
//std::string filePath = "Resources/Nubian/Monkey.obj";
if (loader.LoadFile(filePath)) {
std::cout << "[->] Done!" << std::endl;
std::cout << "Vertices: " << loader.LoadedVertices.size() << std::endl;
std::cout << "Indices: " << loader.LoadedIndices.size() << std::endl;
}
else {
std::cout << "[X] Could not load file!" << std::endl;
return;
}
objl::Mesh mesh = loader.LoadedMeshes[0];
std::vector<float>* vertices = new std::vector<float>();
std::vector<float>* normals = new std::vector<float>();
std::vector<float>* uvs = new std::vector<float>();
for (const objl::Vertex& vertex : mesh.Vertices)
{
vertices->push_back(vertex.Position.X);
vertices->push_back(vertex.Position.Y);
vertices->push_back(vertex.Position.Z);
normals->push_back(vertex.Normal.X);
normals->push_back(vertex.Normal.Y);
normals->push_back(vertex.Normal.Z);
uvs->push_back(vertex.TextureCoordinate.X);
uvs->push_back(vertex.TextureCoordinate.Y);
}
std::vector<unsigned int>* indices = new std::vector<unsigned int>(mesh.Indices);
//unsigned int texture = Util::LoadTexture("Resources/Plant/texture.jpg", GL_RGB);
//unsigned int normal = Util::LoadTexture("Resources/Plant/normals.jpg", GL_RGB);
//Material mat = Material(&texture, &normal, glm::vec3(1));
Material mat = Material::WoodMat();
Object* object = new Object(mat, glm::vec3(0), glm::vec3(0));
object->init(vertices->data(), normals->data(), uvs->data(), mesh.Vertices.size(), indices->data(), indices->size());
world.addObject(object);
}
void visualizeRaycast(KdStructs::RayHit* hit, Camera camera, glm::vec3 directionVector)
{
// Add ray to scene.
world.addRay(new Line(camera.Position, camera.Position + directionVector * 1000.0f));
if (hit != nullptr) {
std::cout << "[->] Hit at: " << hit->position << std::endl;
// Add colorful triangle to scene.
glm::vec3 hitPosition = glm::vec3(hit->position[0], hit->position[1], hit->position[2]);
float* vertices = new float[9]{
hit->triangle->a[0], hit->triangle->a[1], hit->triangle->a[2],
hit->triangle->b[0], hit->triangle->b[1], hit->triangle->b[2],
hit->triangle->c[0], hit->triangle->c[1], hit->triangle->c[2],
};
TriangleObject* triangle = new TriangleObject(vertices, glm::vec3(1, 0, 0));
// Move triangle a bit in camera direction to prevent overlapping.
triangle->translate(directionVector * -0.001f);
// Add ray to intersection.
world.addRay(new Line(camera.Position, hitPosition));
// Add intersecion point.
world.addIntersection(new Point(hitPosition), triangle);
}
else {
std::cout << "[->] No hit!" << std::endl;
// Remove intersection point and triangle.
world.intersectionPoint = nullptr;
world.intersectionTriangle = nullptr;
}
}
void framebufferSizeCallback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void mousePositionCallback(GLFWwindow* window, double xPos, double yPos)
{
World::GetCamera().ProcessMouse(xPos, yPos);
}
void windowFocusCallback(GLFWwindow* window, int isFocused)
{
World::GetCamera().IsWindowFocused = isFocused;
}