New skyboxes
[opengl.git] / main.cpp
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <iostream>
4 #include <array>
5 #include <vector>
6 #ifdef __APPLE__
7 #include <GL/glew.h>
8 #else
9 #include <OpenGL/glew.h>
10 #endif
11 #include <GLUT/glut.h>
12 #include "shapes.hpp"
13 #include <glm/glm.hpp>
14 #include <glm/ext.hpp>
15 #include <glm/gtc/type_ptr.hpp>
16 #include <assimp/Importer.hpp>
17 #include <assimp/scene.h>
18 #include <assimp/postprocess.h>
19 #include "model.hpp"
20 #include "program.hpp"
21 #include "skybox.hpp"
22 #include "image.hpp"
23
24 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
25
26 using namespace std;
27
28 GLuint lightVao;
29
30 Program *textureProg, *plainProg, *reflectProg, *pbrProg;
31
32 std::vector<Skybox> skyboxes;
33 int activeSkybox = 0;
34
35 Assimp::Importer importer; // Need to keep this around, otherwise stuff disappears!
36 Model *sceneModel;
37
38 glm::vec3 camPos = {0, 0, -5}, camFront = {0, 0, 1}, camUp = {0, 1, 0};
39 float fov = glm::radians(30.f), znear = 0.01f, zfar = 10000.f;
40 float yaw = 1.57, pitch = 0;
41
42 struct Light {
43         glm::vec3 pos;
44         glm::vec3 color;
45 };
46
47 std::vector<Light> lights = {
48         { glm::vec3(5, 2, -5), glm::vec3(1) },
49         { glm::vec3(0, 2, -5), glm::vec3(1) },
50         { glm::vec3(-5, 2, -5), glm::vec3(1) },
51 };
52
53 int activeLight = 0;
54
55 bool discoLights = false;
56
57 int windowWidth = 800, windowHeight = 600;
58
59 float aspect() {
60         return (float)windowWidth / (float)windowHeight;
61 }       
62
63 glm::mat4 projMat() {
64         return glm::perspective(fov, aspect(), znear, zfar);
65 }
66
67 glm::mat4 viewMat() {
68         return glm::lookAt(camPos, camPos + camFront, camUp);
69 }
70
71 void setProjectionAndViewUniforms(GLuint progId) {
72         GLuint projLoc = glGetUniformLocation(progId, "projection");
73         glm::mat4 proj = projMat();
74         glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
75
76         GLuint viewLoc = glGetUniformLocation(progId, "view");
77         glm::mat4 view = viewMat();
78         glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
79
80         GLuint camPosLoc = glGetUniformLocation(progId, "camPos");
81         glUniform3fv(camPosLoc, 1, glm::value_ptr(camPos));
82 }
83
84 void setLightColorAndPos(GLuint progId, glm::vec3 lightPos, glm::vec4 lightColor) {
85         GLuint lightColorLoc = glGetUniformLocation(progId, "lightColor");
86         glUniform4fv(lightColorLoc, 1, glm::value_ptr(lightColor));
87
88         GLuint lightPosLoc = glGetUniformLocation(progId, "vLightPos");
89         glUniform3fv(lightPosLoc, 1, glm::value_ptr(lightPos));
90
91         GLuint viewPosLoc = glGetUniformLocation(progId, "vViewPos");
92         glUniform3fv(viewPosLoc, 1, glm::value_ptr(camPos));
93 }
94
95 void drawLight(Light &light) {
96         glUseProgram(plainProg->progId);
97         glBindVertexArray(lightVao);
98         setProjectionAndViewUniforms(plainProg->progId);
99         glm::mat4 model = glm::translate(glm::mat4(1.f), light.pos);
100         model = glm::scale(model, glm::vec3(0.2));
101         GLuint modelLoc = glGetUniformLocation(plainProg->progId, "model");
102         glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
103
104         GLuint colorLoc = glGetUniformLocation(plainProg->progId, "color");
105         glUniform4fv(colorLoc, 1, glm::value_ptr(light.color));
106                 
107         glDrawArrays(GL_TRIANGLES, 0, 36);
108 }
109
110
111 void display() {
112         glClearColor(0.5, 0.5, 0.5, 1);
113         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
114         glViewport(0, 0, windowWidth * 2, windowHeight * 2);
115
116         float d = (float)glutGet(GLUT_ELAPSED_TIME) * 0.001f;
117
118         glUseProgram(pbrProg->progId);
119         setProjectionAndViewUniforms(pbrProg->progId);
120
121         glm::vec3 lightPositions[6], lightColors[6];
122         for (int i = 0; i < 3; i++) {
123                 lightPositions[i] = lights[i].pos;
124                 lightColors[i] = lights[i].color;
125         }
126
127         for (int i = 3; i < 6; i++) {
128                 if (discoLights) {
129                         auto m = glm::translate(glm::mat4(1.f), glm::vec3(-2.5, 0, 0));
130                         m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(1, 0, 0));
131                         m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(0, 1, 0));
132                         m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(0, 0, 1));
133                         lightPositions[i] = glm::vec3(m * glm::vec4(5, 0, 0, 1));
134                         lightColors[i] = glm::vec3(0.2);
135                         if (i == 3) lightColors[i].x = sin(d);
136                         if (i == 4) lightColors[i].y = cos(d * 3);
137                         if (i == 5) lightColors[i].z = cos(d);
138                 } else {
139                         lightPositions[i] = glm::vec3(0);
140                         lightColors[i] = glm::vec3(0);
141                 }
142         }
143         
144         glUniform3fv(glGetUniformLocation(pbrProg->progId, "lightPositions"), 6, glm::value_ptr(lightPositions[0]));
145         glUniform3fv(glGetUniformLocation(pbrProg->progId, "lightColors"), 6, glm::value_ptr(lightColors[0]));
146
147         /* pbr->getRoot()->model = glm::rotate(glm::mat4(1.f), glm::radians(d * 10), glm::vec3(0, 1, 0)); */
148         sceneModel->draw(skyboxes[activeSkybox], d * 1000);
149
150         for (Light &light: lights) drawLight(light);
151
152         if (discoLights) {
153                 for (int i = 3; i < 6; i++) {
154                         Light l { lightPositions[i], lightColors[i] };
155                         drawLight(l);
156                 }
157         }
158
159         skyboxes[activeSkybox].draw(projMat(), viewMat());
160
161         glutSwapBuffers();
162 }
163
164 void setupLightBuffers(GLuint progId) {
165         auto vertices = cube();
166         GLuint verticesSize = 36 * 3 * sizeof(GLfloat);
167
168         glGenVertexArrays(1, &lightVao);
169         GLuint vbo;
170         glBindVertexArray(lightVao);
171         glGenBuffers(1, &vbo);
172         glBindBuffer(GL_ARRAY_BUFFER, vbo);
173         glBufferData(GL_ARRAY_BUFFER, verticesSize, NULL, GL_STATIC_DRAW);
174         glBufferSubData(GL_ARRAY_BUFFER, 0, verticesSize, glm::value_ptr(vertices[0]));
175         GLuint posLoc = glGetAttribLocation(progId, "vPosition");
176         glEnableVertexAttribArray(posLoc);
177         glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
178 }
179
180 int findNodeTrans(struct aiNode *n, const struct aiString name, glm::mat4 *dest) {
181         if (strcmp(n->mName.data, name.data) == 0) {
182                 *dest = aiMatrixToMat4(n->mTransformation);
183                 return 0;
184         }
185         for (int i = 0; i < n->mNumChildren; i++) {
186                 if (findNodeTrans(n->mChildren[i], name, dest) == 0) {
187                         glm::mat4 t = aiMatrixToMat4(n->mTransformation);
188                         *dest = t * *dest;
189                         return 0;
190                 }
191         }
192         return 1;
193 }
194
195 void init() {
196         plainProg = new Program("plainvertex.glsl", "plainfrag.glsl");
197         glUseProgram(plainProg->progId);
198         setupLightBuffers(plainProg->progId);
199         plainProg->validate();
200
201         skyboxes.push_back(Skybox(Image("skyboxes/wooden_lounge_8k.hdr")));
202         skyboxes.push_back(Skybox(Image("skyboxes/machine_shop_02_8k.hdr")));
203         skyboxes.push_back(Skybox(Image("skyboxes/pink_sunrise_8k.hdr")));
204
205         pbrProg = new Program("pbrvert.glsl", "pbrfrag.glsl");
206         glUseProgram(pbrProg->progId);
207
208         const aiScene *scene = importer.ReadFile("models/newtonsCradle.glb", aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenNormals | aiProcess_FlipUVs);
209         if (!scene) {
210                 std::cerr << importer.GetErrorString() << std::endl;
211                 exit(1);
212         }
213
214         if (scene->mNumCameras > 0) {
215                 struct aiCamera *cam = scene->mCameras[0];
216                 glm::mat4 camTrans;
217                 if (findNodeTrans(scene->mRootNode, cam->mName, &camTrans) != 0)
218                         abort(); // there must be a node with the same name as camera
219
220                 camPos = { camTrans[3][0], camTrans[3][1], camTrans[3][2] };
221
222                 glm::vec3 camLookAt = glm::vec3(cam->mLookAt.x, cam->mLookAt.y, cam->mLookAt.z);
223                 camFront = camLookAt - camPos;
224
225                 camUp = glm::vec3(cam->mUp.x, cam->mUp.y, cam->mUp.z);
226                 
227                 fov = cam->mHorizontalFOV;
228                 // TODO: aspectRatio = cam->mAspect;
229                 znear = cam->mClipPlaneNear;
230                 zfar = cam->mClipPlaneFar;
231         }
232
233         sceneModel = new Model(scene, *pbrProg);
234
235         glEnable(GL_DEPTH_TEST); 
236         glEnable(GL_CULL_FACE); 
237         // prevent edge artifacts in specular cubemaps
238         glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
239
240         glViewport(0, 0, windowWidth, windowHeight);
241 }
242
243 bool keyStates[256] = {false};
244
245 void keyboard(unsigned char key, int x, int y) {
246         keyStates[key] = true;
247         if (key == 'z')
248                 activeSkybox = (activeSkybox + 1) % skyboxes.size();
249         if (key == 'x')
250                 activeLight = (activeLight + 1) % lights.size();
251         if (key == 'c')
252                 discoLights = !discoLights;
253 }
254
255 void keyboardUp(unsigned char key, int x, int y) {
256         keyStates[key] = false;
257 }
258
259 void timer(int _) {
260         float xSpeed = 0.f, ySpeed = 0.f, zSpeed = 0.f;
261         if (keyStates['w'])
262                 zSpeed = 0.1f;
263         if (keyStates['s'])
264                 zSpeed = -0.1f;
265         if (keyStates['a'])
266                 xSpeed = 0.1f;
267         if (keyStates['d'])
268                 xSpeed = -0.1f;
269         if (keyStates['q'])
270                 ySpeed = 0.1f;
271         if (keyStates['e'])
272                 ySpeed = -0.1f;
273
274         if (keyStates['j']) lights[activeLight].pos.z += 0.1f;
275         if (keyStates['k']) lights[activeLight].pos.z -= 0.1f;
276         if (keyStates['h']) lights[activeLight].pos.x -= 0.1f;
277         if (keyStates['l']) lights[activeLight].pos.x += 0.1f;
278         if (keyStates['m']) lights[activeLight].pos.y -= 0.1f;
279         if (keyStates['n']) lights[activeLight].pos.y += 0.1f;
280
281         camPos.x += xSpeed * sin(yaw) + zSpeed * cos(yaw);
282         camPos.y += ySpeed;
283         camPos.z += zSpeed * sin(yaw) - xSpeed * cos(yaw);
284         glutPostRedisplay();
285         glutTimerFunc(16, timer, 0);
286 }
287
288 int prevMouseX, prevMouseY;
289 bool firstMouse = true;
290
291 void motion(int x, int y) {
292         if (firstMouse) {
293                 prevMouseX = x;
294                 prevMouseY = y;
295                 firstMouse = false;
296         }
297         int dx = x - prevMouseX, dy = y - prevMouseY;
298
299         prevMouseX = x;
300         prevMouseY = y;
301
302         const float sensitivity = 0.005f;
303         yaw += dx * sensitivity;
304         pitch -= dy * sensitivity;
305
306         glm::vec3 front;
307         front.x = cos(pitch) * cos(yaw);
308         front.y = sin(pitch);
309         front.z = cos(pitch) * sin(yaw);
310         camFront = glm::normalize(front);
311
312         if (pitch < -1.57079632679 || pitch >= 1.57079632679) {
313                 camUp = glm::vec3(0, -1, 0);
314         } else {
315                 camUp = glm::vec3(0, 1, 0);
316         }
317 }
318
319 void mouse(int button, int state, int x, int y) {
320         if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
321                 firstMouse = true;
322 }
323
324 void reshape(int newWidth, int newHeight) {
325         windowWidth = newWidth, windowHeight = newHeight;
326 }
327
328 int main(int argc, char** argv) {
329         glutInit(&argc, argv);
330         glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGB|GLUT_3_2_CORE_PROFILE);
331         glutInitWindowSize(windowWidth, windowHeight);
332         glutCreateWindow("Physically Based Rendering");
333         glutDisplayFunc(display);
334         glutReshapeFunc(reshape);
335
336         glewInit();
337         
338         init();
339
340         glutKeyboardFunc(keyboard);
341         glutKeyboardUpFunc(keyboardUp);
342         glutTimerFunc(16, timer, 0);
343         glutMotionFunc(motion);
344         glutMouseFunc(mouse);
345
346         glutMainLoop();
347
348         return 0;
349 }
350