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