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