Refactor modes up into classes
[opengl.git] / main.cpp
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <iostream>
4 #include <array>
5 #include <vector>
6 #include <dirent.h>
7 #ifdef __APPLE__
8 #include <GL/glew.h>
9 #else
10 #include <OpenGL/glew.h>
11 #endif
12 #include <GLUT/glut.h>
13 #include "shapes.hpp"
14 #include <glm/glm.hpp>
15 #include <glm/ext.hpp>
16 #include <glm/gtc/type_ptr.hpp>
17 #include <assimp/Importer.hpp>
18 #include <assimp/scene.h>
19 #include <assimp/postprocess.h>
20 #include "model.hpp"
21 #include "program.hpp"
22 #include "skybox.hpp"
23 #include "image.hpp"
24 #include "util.hpp"
25 #include "ik.hpp"
26 #include "blendshapes.hpp"
27 #include "ui.hpp"
28
29 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
30
31 using namespace std;
32
33 GLuint lightVao, cursorVao;
34 GLuint cursorNumIndices;
35
36 Program *textureProg, *plainProg, *reflectProg, *pbrProg, *cursorProg;
37
38 std::vector<Skybox> skyboxes;
39 int activeSkybox = 0;
40
41 Assimp::Importer importer; // Need to keep this around, otherwise stuff disappears!
42 /* Model *sceneModel; */
43
44 glm::vec3 camPos = {0, 0, -5}, camFront = {0, 0, 1}, camUp = {0, 1, 0};
45 float fov = glm::radians(30.f), znear = 0.01f, zfar = 10000.f;
46 float yaw = 1.57, pitch = 0;
47
48 Model *targetModel; // The model that the selection is happening on
49 Model::VertexLookup closestVertex;
50 // How close a vertex needs to be to the cursor before it is "over"
51 const float closestVertexThreshold = 0.5;
52
53 std::map<VertIdx, glm::vec3> manipulators;
54 VertIdx curManipulator = {-1,-1};
55
56 BlendshapeModel bsModel;
57 bool playBlendshapeAnim = false;
58
59 struct Light {
60         glm::mat4 trans;
61         glm::vec3 color;
62 };
63
64 std::vector<Light> lights;
65
66 bool discoLights = false;
67
68 int windowWidth = 800, windowHeight = 600;
69 float aspect() {
70         return (float)windowWidth / (float)windowHeight;
71 }       
72
73 inline glm::mat4 projMat() {
74         return glm::perspective(fov, aspect(), znear, zfar);
75 }
76
77 inline glm::mat4 viewMat() {
78         return glm::lookAt(camPos, camPos + camFront, camUp);
79 }
80
81 void setProjectionAndViewUniforms(GLuint progId) {
82         GLuint projLoc = glGetUniformLocation(progId, "projection");
83         glm::mat4 proj = projMat();
84         glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
85
86         GLuint viewLoc = glGetUniformLocation(progId, "view");
87         glm::mat4 view = viewMat();
88         glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
89
90         GLuint camPosLoc = glGetUniformLocation(progId, "camPos");
91         glUniform3fv(camPosLoc, 1, glm::value_ptr(camPos));
92 }
93
94 void setLightColorAndPos(GLuint progId, glm::vec3 lightPos, glm::vec4 lightColor) {
95         GLuint lightColorLoc = glGetUniformLocation(progId, "lightColor");
96         glUniform4fv(lightColorLoc, 1, glm::value_ptr(lightColor));
97
98         GLuint lightPosLoc = glGetUniformLocation(progId, "vLightPos");
99         glUniform3fv(lightPosLoc, 1, glm::value_ptr(lightPos));
100
101         GLuint viewPosLoc = glGetUniformLocation(progId, "vViewPos");
102         glUniform3fv(viewPosLoc, 1, glm::value_ptr(camPos));
103 }
104
105 void drawPlainProg(Program *p, GLuint vao, glm::mat4 trans, glm::vec3 color) {
106         glUseProgram(p->progId);
107         glBindVertexArray(vao);
108         setProjectionAndViewUniforms(p->progId);
109         glm::mat4 model = glm::scale(trans, glm::vec3(0.3));
110         GLuint modelLoc = glGetUniformLocation(p->progId, "model");
111         glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
112
113         GLuint colorLoc = glGetUniformLocation(p->progId, "color");
114         glUniform4fv(colorLoc, 1, glm::value_ptr(color));
115                 
116         glDrawArrays(GL_TRIANGLES, 0, 36);
117 }
118
119 void drawLight(Light &light) {
120         drawPlainProg(plainProg, lightVao, light.trans, light.color);
121 }
122
123 int findNodeTrans(const struct aiNode *n, const struct aiString name, glm::mat4 *dest) {
124         if (strcmp(n->mName.data, name.data) == 0) {
125                 *dest = aiMatrixToMat4(n->mTransformation);
126                 return 0;
127         }
128         for (int i = 0; i < n->mNumChildren; i++) {
129                 if (findNodeTrans(n->mChildren[i], name, dest) == 0) {
130                         glm::mat4 t = aiMatrixToMat4(n->mTransformation);
131                         *dest = t * *dest;
132                         return 0;
133                 }
134         }
135         return 1;
136 }
137
138 glm::mat4 worldSpaceToModelSpace(aiNode *node, glm::mat4 m) {
139         aiNode *parent = node;
140         glm::mat4 res = m;
141         std::vector<glm::mat4> trans;
142         while (parent != nullptr) {
143                 /* res = res * glm::inverse(aiMatrixToMat4(parent->mTransformation)); */
144                 trans.push_back(glm::inverse(aiMatrixToMat4(parent->mTransformation)));
145                 parent = parent->mParent;
146         }
147         while (!trans.empty()) { res = trans.back() * res; trans.pop_back(); }
148         return res;
149 }
150
151 bool keyStates[256] = {false};
152
153 void keyboard(unsigned char key, int x, int y) {
154         keyStates[key] = true;
155         if (key == 'z')
156                 activeSkybox = (activeSkybox + 1) % skyboxes.size();
157         if (key == 'c')
158                 discoLights = !discoLights;
159 }
160
161 void keyboardUp(unsigned char key, int x, int y) {
162         keyStates[key] = false;
163 }
164
165 int mouseX, mouseY;
166
167 struct Mode {
168         virtual void display(float d) = 0;
169         virtual void timer() = 0;
170         virtual void motion(int x, int y, int dx, int dy) = 0;
171         virtual void passiveMotion(int x, int y, int dx, int dy) = 0;
172         virtual void mouse(int button, int state, int x, int y) = 0;
173 };
174
175 struct AnimationMode : public Mode {
176         Model *sceneModel;
177
178         AnimationMode(std::string modelPath) {
179                 const aiScene *scene = importer.ReadFile(
180                                 modelPath, aiProcess_Triangulate | aiProcess_CalcTangentSpace |
181                                 aiProcess_GenNormals | aiProcess_FlipUVs);
182                 if (!scene) {
183                         std::cerr << importer.GetErrorString() << std::endl;
184                         exit(1);
185                 }
186
187                 if (scene->mNumCameras > 0) {
188                         aiCamera *cam = scene->mCameras[0];
189                         glm::mat4 camTrans;
190                         if (findNodeTrans(scene->mRootNode, cam->mName, &camTrans) != 0)
191                                 abort(); // there must be a node with the same name as camera
192
193                         camPos = {camTrans[3][0], camTrans[3][1], camTrans[3][2]};
194
195                         glm::vec3 camLookAt =
196                                 glm::vec3(cam->mLookAt.x, cam->mLookAt.y, cam->mLookAt.z);
197                         camFront = camLookAt - camPos;
198
199                         camUp = glm::vec3(cam->mUp.x, cam->mUp.y, cam->mUp.z);
200
201                         fov = cam->mHorizontalFOV;
202                         // TODO: aspectRatio = cam->mAspect;
203                         znear = cam->mClipPlaneNear;
204                         zfar = cam->mClipPlaneFar;
205                 }
206
207                 for (int i = 0; i < scene->mNumLights; i++) {
208                         aiLight *light = scene->mLights[i];
209                         glm::mat4 trans;
210                         findNodeTrans(scene->mRootNode, light->mName, &trans);
211                         glm::vec3 col = {light->mColorAmbient.r, light->mColorAmbient.g,
212                                 light->mColorAmbient.b};
213                         Light l = {trans, col};
214                         lights.push_back(l);
215                 }
216
217                 sceneModel = new Model(scene, *pbrProg);
218         }
219         
220         void display(float d) override {
221                 sceneModel->draw(skyboxes[activeSkybox], d * 1000);
222         }
223
224         void timer() override {};
225         void motion(int x, int y, int dx, int dy) override {}
226         void passiveMotion(int x, int y, int dx, int dy) override {}
227         void mouse(int button, int state, int x, int y) override {}
228 };
229
230
231 // TODO: move these inside
232 bool needToCalculateClosestVertex = false;
233 bool needToInterpolateBlendshapes = false;
234 struct BlendshapeMode : public Mode {
235
236         class Delegate : public ControlWindowDelegate {
237                 public:
238
239                         virtual void weightChanged(int blendshape, float weight) override {
240                                 bsModel.blendshapes[blendshape].weight = weight;
241                                 needToInterpolateBlendshapes = true;
242                         }
243
244                         virtual void solveWeights(std::vector<float> &newWeights) override {
245                                 ::solveWeights(&bsModel, manipulators);
246                                 for (int i = 0; i < newWeights.size(); i++)
247                                         newWeights[i] = bsModel.blendshapes[i].weight;
248                                 needToInterpolateBlendshapes = true;
249                         }
250
251                         virtual void resetManipulators() override {
252                                 manipulators.clear();
253                                 curManipulator = { -1, -1 };
254                         }
255
256                         virtual void playbackChanged(bool playing) override {
257                                 playBlendshapeAnim = playing;
258                         }
259         };
260
261         Delegate cwDelegate;
262         ControlWindow controlWindow;
263
264         BlendshapeMode(std::string directory) {
265                 loadBlendshapes(directory, *pbrProg, &bsModel);
266                 targetModel = bsModel.model;
267
268                 size_t numBlends = bsModel.blendshapes.size();
269                 std::vector<std::string> names(numBlends);
270                 for (int i = 0; i < numBlends; i++) names[i] = bsModel.blendshapes[i].name;
271                 
272                 controlWindow = createControlWindow(names, &cwDelegate);
273
274                 camPos = { 0, 18, 81 };
275                 camFront = { 0, 0, -1 };
276                 camUp = { 0, 1, 0 };
277                 zfar = 10000;
278                 znear = 0.1f;
279         }
280
281         void drawCursor(glm::vec3 pos, glm::vec3 color, float scale = 1) {
282                 glUseProgram(cursorProg->progId);
283                 glBindVertexArray(cursorVao);
284                 setProjectionAndViewUniforms(cursorProg->progId);
285                 glm::mat4 model = glm::scale(glm::translate(glm::mat4(1), pos), glm::vec3(scale * 0.4));
286                 GLuint modelLoc = glGetUniformLocation(cursorProg->progId, "model");
287                 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
288
289                 GLuint colorLoc = glGetUniformLocation(cursorProg->progId, "color");
290                 glUniform4fv(colorLoc, 1, glm::value_ptr(color));
291
292                 glDrawElements(GL_TRIANGLES, cursorNumIndices, GL_UNSIGNED_INT, 0);
293         }
294
295         void display(float d) override {
296                 if (closestVertex.distance < closestVertexThreshold)
297                         drawCursor(closestVertex.pos, {0.5,0,1}, 0.9);
298
299                 for (auto v: manipulators) {
300                         glm::vec3 color = { 0.4, 1, 0 };
301                         if (closestVertex.meshIdx == v.first.first &&
302                                         closestVertex.vertIdx == v.first.second)
303                                 color = {1, 0, 0};
304                         drawCursor(v.second, color);
305
306                         glm::vec3 origVertex = aiVector3DToVec3(bsModel.model->meshes[v.first.first].ai.mVertices[v.first.second]);
307                         drawCursor(origVertex, {0,0,1}, 0.7);
308                 }
309
310                 bsModel.model->draw(skyboxes[activeSkybox], d * 1000);
311         }
312
313         void timer() override {
314                 float xSpeed = 0, ySpeed = 0, zSpeed = 0;
315 #pragma clang diagnostic push
316 #pragma clang diagnostic ignored "-Wchar-subscripts"
317                 if (keyStates['w'])
318                         zSpeed = 0.1f;
319                 if (keyStates['s'])
320                         zSpeed = -0.1f;
321                 if (keyStates['a'])
322                         xSpeed = 0.1f;
323                 if (keyStates['d'])
324                         xSpeed = -0.1f;
325                 if (keyStates['q'])
326                         ySpeed = 0.1f;
327                 if (keyStates['e'])
328                         ySpeed = -0.1f;
329 #pragma clang diagnostic pop
330
331                 if (playBlendshapeAnim) {
332                         stepBlendshapeAnim(&bsModel);
333                         needToInterpolateBlendshapes = true;
334                         std::vector<float> newWeights(bsModel.blendshapes.size());
335                         for (int i = 0; i < bsModel.blendshapes.size(); i++)
336                                 newWeights[i] = bsModel.blendshapes[i].weight;
337                         updateWeights(&controlWindow, newWeights);
338                 }
339
340                 if (curManipulator.first != -1 && curManipulator.second != -1) {
341                         manipulators[curManipulator].x += xSpeed;
342                         manipulators[curManipulator].y += ySpeed;
343                         manipulators[curManipulator].z += zSpeed;
344                 }
345
346                 if (needToInterpolateBlendshapes) {
347                         interpolateBlendshapes(&bsModel);
348                         needToInterpolateBlendshapes = false;
349                 }
350
351                 if (needToCalculateClosestVertex) {
352                         GLint vpArr[4]; glGetIntegerv(GL_VIEWPORT, vpArr);
353                         glm::vec4 viewport(vpArr[0], vpArr[1], vpArr[2], vpArr[3]);
354                         glm::vec3 selectedPos = glm::unProject(glm::vec3(mouseX * 2, viewport[3] - mouseY * 2, 1), // hidpi
355                                         viewMat(),
356                                         projMat(),
357                                         viewport);
358
359                         closestVertex = targetModel->closestVertex(targetModel->getRoot(), camPos, selectedPos);
360                         needToCalculateClosestVertex = false;
361                 }
362         }
363
364
365         void motion(int x, int y, int dx, int dy) override {
366                 if (closestVertex.distance > closestVertexThreshold) {
367                         const glm::vec3 origin(0,18,0);
368                         const float sensitivity = 0.003f;
369                         auto camMat = glm::translate(glm::mat4(1), origin + camPos);
370                         auto rotation = glm::rotate(glm::rotate(glm::mat4(1), -dx * sensitivity, {0, 1, 0}),
371                                         -dy * sensitivity, {1, 0, 0});
372                         auto rotAroundOrig = camMat * rotation * glm::translate(glm::mat4(1), origin - camPos);
373                         camPos = rotAroundOrig * glm::vec4(camPos, 0);
374                         camFront = origin - camPos; // face center
375                 }
376                 needToCalculateClosestVertex = true;
377         }
378
379         void passiveMotion(int x, int y, int dx, int dy) override {
380                 needToCalculateClosestVertex = true;
381         }
382
383         void mouse(int button, int state, int x, int y) override {
384                 if (isPanelFocused(controlWindow))
385                         return;
386
387                 if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
388                         if (closestVertex.distance < closestVertexThreshold) {
389                                 VertIdx idx = { closestVertex.meshIdx, closestVertex.vertIdx };
390                                 if (manipulators.count(idx) <= 0)
391                                         manipulators[idx] = closestVertex.pos;
392                                 curManipulator = idx;
393                         }
394                 }
395         }
396 };
397
398 Mode *curMode;
399
400
401 void display() {
402         glClearColor(0.5, 0.5, 0.5, 1);
403         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
404         glViewport(0, 0, windowWidth * 2, windowHeight * 2);
405
406         float d = (float)glutGet(GLUT_ELAPSED_TIME) * 0.001f;
407
408         glUseProgram(getUtilProg()->progId);
409         setProjectionAndViewUniforms(getUtilProg()->progId);
410
411         glUseProgram(pbrProg->progId);
412         setProjectionAndViewUniforms(pbrProg->progId);
413
414         size_t numLights = lights.size() + (discoLights ? 3 : 0);
415         glm::vec3 lightPositions[numLights], lightColors[numLights];
416         for (int i = 0; i < lights.size(); i++) {
417                 lightPositions[i] = glm::vec3(lights[i].trans[3]);
418                 lightColors[i] = lights[i].color;
419         }
420
421         if (discoLights) {
422                 for (int i = numLights - 3; i < numLights; i++) {
423                         auto m = glm::translate(glm::mat4(1.f), glm::vec3(-2.5, 0, 0));
424                         m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(1, 0, 0));
425                         m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(0, 1, 0));
426                         m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(0, 0, 1));
427                         lightPositions[i] = glm::vec3(m * glm::vec4(5, 0, 0, 1));
428                         lightColors[i] = glm::vec3(0.2);
429                         if (i % 3 == 0) lightColors[i].x = sin(d);
430                         if (i % 3 == 1) lightColors[i].y = cos(d * 3);
431                         if (i % 3 == 2) lightColors[i].z = cos(d);
432                 }
433         }
434
435         glUniform1ui(glGetUniformLocation(pbrProg->progId, "numLights"), numLights);
436         glUniform3fv(glGetUniformLocation(pbrProg->progId, "lightPositions"), numLights, glm::value_ptr(lightPositions[0]));
437         glUniform3fv(glGetUniformLocation(pbrProg->progId, "lightColors"), numLights, glm::value_ptr(lightColors[0]));
438
439 #ifdef COWEDBOY_IK
440         { 
441                 glm::vec3 targetPos(sin(d) * 2 + 3, -2, 1);
442                 Light targetLight = { glm::translate(glm::mat4(1), targetPos), {0.5, 1, 1}  };
443                 drawLight(targetLight);
444                 inverseKinematics(*sceneModel->find("Shoulder.L"), *sceneModel->find("Finger.L"), targetPos);
445
446                 targetPos = { sin(d * 2) * 2 - 5, 2.5, 0 };
447                 targetLight = { glm::translate(glm::mat4(1), targetPos), {1, 1, 0.5}  };
448                 drawLight(targetLight);
449                 inverseKinematics(*sceneModel->find("Shoulder.R"), *sceneModel->find("Finger.R"), targetPos);
450         }
451 #endif
452
453         curMode->display(d);
454
455         for (Light &light: lights) drawLight(light);
456
457         // TODO: restore
458         /* if (discoLights) { */
459         /*      for (int i = numLights - 3; i < numLights; i++) { */
460         /*              Light l = { lightPositions[i], lightColors[i] }; */
461         /*              drawLight(l); */
462         /*      } */
463         /* } */
464
465         skyboxes[activeSkybox].draw(projMat(), viewMat());
466
467         glutSwapBuffers();
468 }
469
470 void setupPlainBuffers(GLuint progId, std::vector<glm::vec3> vertices) {
471         GLuint verticesSize = vertices.size() * sizeof(glm::vec3);
472
473         glGenVertexArrays(1, &lightVao);
474         GLuint vbo;
475         glBindVertexArray(lightVao);
476         glGenBuffers(1, &vbo);
477         glBindBuffer(GL_ARRAY_BUFFER, vbo);
478         glBufferData(GL_ARRAY_BUFFER, verticesSize, NULL, GL_STATIC_DRAW);
479         glBufferSubData(GL_ARRAY_BUFFER, 0, verticesSize, glm::value_ptr(vertices[0]));
480         GLuint posLoc = glGetAttribLocation(progId, "vPosition");
481         glEnableVertexAttribArray(posLoc);
482         glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
483 }
484
485 GLuint setupBuffersWithIndices(GLuint progId, GLuint vao,
486                                                          std::vector<glm::vec3> vertices,
487                                                          std::vector<GLuint> indices) {
488         GLuint vbos[2];
489         glBindVertexArray(vao);
490         glGenBuffers(2, vbos);
491
492         int verticesSize = vertices.size() * sizeof(glm::vec3);
493         // positions
494         glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
495         glBufferData(GL_ARRAY_BUFFER, verticesSize, NULL, GL_STATIC_DRAW);
496         glBufferSubData(GL_ARRAY_BUFFER, 0, verticesSize,
497                                         glm::value_ptr(vertices[0]));
498
499         GLuint posLoc = glGetAttribLocation(progId, "vPosition");
500         glEnableVertexAttribArray(posLoc);
501         glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
502
503         // indices
504         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbos[1]);
505         glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
506
507         return indices.size();
508 }
509
510
511 void init() {
512         initUtilProg();
513
514         plainProg = new Program("plainvertex.glsl", "plainfrag.glsl");
515         glUseProgram(plainProg->progId);
516         setupPlainBuffers(plainProg->progId, cube());
517         plainProg->validate();
518
519         cursorProg = new Program("plainvertex.glsl", "plainfrag.glsl");
520         glUseProgram(cursorProg->progId);
521         glGenVertexArrays(1, &cursorVao);
522         cursorNumIndices = setupBuffersWithIndices(cursorProg->progId, cursorVao, sphere(), sphereIndices());
523         cursorProg->validate();
524
525         skyboxes.push_back(Skybox(Image("skyboxes/loft/Newport_Loft_Ref.hdr")));
526         skyboxes.push_back(Skybox(Image("skyboxes/wooden_lounge_8k.hdr")));
527         skyboxes.push_back(Skybox(Image("skyboxes/machine_shop_02_8k.hdr")));
528         skyboxes.push_back(Skybox(Image("skyboxes/pink_sunrise_8k.hdr")));
529
530         pbrProg = new Program("pbrvert.glsl", "pbrfrag.glsl");
531         glUseProgram(pbrProg->progId);
532
533         /* if (curMode == Default) { */
534                 /* const std::string scenePath = "models/cowedboy.glb"; */
535                 /* const aiScene *scene = importer.ReadFile( */
536                 /*              scenePath, aiProcess_Triangulate | aiProcess_CalcTangentSpace | */
537                 /*              aiProcess_GenNormals | aiProcess_FlipUVs); */
538                 /* if (!scene) { */
539                 /*      std::cerr << importer.GetErrorString() << std::endl; */
540                 /*      exit(1); */
541                 /* } */
542
543                 /* if (scene->mNumCameras > 0) { */
544                 /*      aiCamera *cam = scene->mCameras[0]; */
545                 /*      glm::mat4 camTrans; */
546                 /*      if (findNodeTrans(scene->mRootNode, cam->mName, &camTrans) != 0) */
547                 /*              abort(); // there must be a node with the same name as camera */
548
549                 /*      camPos = {camTrans[3][0], camTrans[3][1], camTrans[3][2]}; */
550
551                 /*      glm::vec3 camLookAt = */
552                 /*              glm::vec3(cam->mLookAt.x, cam->mLookAt.y, cam->mLookAt.z); */
553                 /*      camFront = camLookAt - camPos; */
554
555                 /*      camUp = glm::vec3(cam->mUp.x, cam->mUp.y, cam->mUp.z); */
556
557                 /*      fov = cam->mHorizontalFOV; */
558                 /*      // TODO: aspectRatio = cam->mAspect; */
559                 /*      znear = cam->mClipPlaneNear; */
560                 /*      zfar = cam->mClipPlaneFar; */
561                 /* } */
562
563                 /* for (int i = 0; i < scene->mNumLights; i++) { */
564                 /*      aiLight *light = scene->mLights[i]; */
565                 /*      glm::mat4 trans; */
566                 /*      findNodeTrans(scene->mRootNode, light->mName, &trans); */
567                 /*      glm::vec3 col = {light->mColorAmbient.r, light->mColorAmbient.g, */
568                 /*              light->mColorAmbient.b}; */
569                 /*      Light l = {trans, col}; */
570                 /*      lights.push_back(l); */
571                 /* } */
572
573                 /* sceneModel = new Model(scene, *pbrProg); */
574         /* } */
575
576         /* if (curMode == Blendshapes) { */
577         /*      loadBlendshapes("models/high-res-blendshapes/", *pbrProg, &bsModel); */
578         /*      targetModel = bsModel.model; */
579
580         /*      size_t numBlends = bsModel.blendshapes.size(); */
581         /*      std::vector<std::string> names(numBlends); */
582         /*      for (int i = 0; i < numBlends; i++) names[i] = bsModel.blendshapes[i].name; */
583         /*      controlWindow = createControlWindow(names, &cwDelegate); */
584
585         /*      camPos = { 0, 18, 81 }; */
586         /*      camFront = { 0, 0, -1 }; */
587         /*      camUp = { 0, 1, 0 }; */
588         /*      zfar = 10000; */
589         /*      znear = 0.1f; */
590         /* } */
591
592         glEnable(GL_DEPTH_TEST); 
593         glEnable(GL_CULL_FACE); 
594         // prevent edge artifacts in specular cubemaps
595         glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
596
597         glViewport(0, 0, windowWidth * 2, windowHeight * 2);
598 }
599
600
601 /* #define ENABLE_MOVEMENT */
602 void timer(int _) {
603 #ifdef ENABLE_MOVEMENT
604         float xSpeed = 0.f, ySpeed = 0.f, zSpeed = 0.f;
605
606 #pragma clang diagnostic push
607 #pragma clang diagnostic ignored "-Wchar-subscripts"
608         if (keyStates['w'])
609                 zSpeed = 0.1f;
610         if (keyStates['s'])
611                 zSpeed = -0.1f;
612         if (keyStates['a'])
613                 xSpeed = 0.1f;
614         if (keyStates['d'])
615                 xSpeed = -0.1f;
616         if (keyStates['q'])
617                 ySpeed = 0.1f;
618         if (keyStates['e'])
619                 ySpeed = -0.1f;
620 #pragma clang diagnostic pop
621
622         camPos.x += xSpeed * sin(yaw) + zSpeed * cos(yaw);
623         camPos.y += ySpeed;
624         camPos.z += zSpeed * sin(yaw) - xSpeed * cos(yaw);
625 #endif
626
627         curMode->timer();
628
629         /* if (curMode == Blendshapes) { */
630         /*      float xSpeed = 0, ySpeed = 0, zSpeed = 0; */
631 /* #pragma clang diagnostic push */
632 /* #pragma clang diagnostic ignored "-Wchar-subscripts" */
633         /*      if (keyStates['w']) */
634         /*              zSpeed = 0.1f; */
635         /*      if (keyStates['s']) */
636         /*              zSpeed = -0.1f; */
637         /*      if (keyStates['a']) */
638         /*              xSpeed = 0.1f; */
639         /*      if (keyStates['d']) */
640         /*              xSpeed = -0.1f; */
641         /*      if (keyStates['q']) */
642         /*              ySpeed = 0.1f; */
643         /*      if (keyStates['e']) */
644         /*              ySpeed = -0.1f; */
645 /* #pragma clang diagnostic pop */
646
647         /*      if (playBlendshapeAnim) { */
648         /*              stepBlendshapeAnim(&bsModel); */
649         /*              needToInterpolateBlendshapes = true; */
650         /*              std::vector<float> newWeights(bsModel.blendshapes.size()); */
651         /*              for (int i = 0; i < bsModel.blendshapes.size(); i++) */
652         /*                      newWeights[i] = bsModel.blendshapes[i].weight; */
653         /*              updateWeights(&controlWindow, newWeights); */
654         /*      } */
655
656         /*      if (curManipulator.first != -1 && curManipulator.second != -1) { */
657         /*              manipulators[curManipulator].x += xSpeed; */
658         /*              manipulators[curManipulator].y += ySpeed; */
659         /*              manipulators[curManipulator].z += zSpeed; */
660         /*      } */
661
662         /*      if (needToInterpolateBlendshapes) { */
663         /*              interpolateBlendshapes(&bsModel); */
664         /*              needToInterpolateBlendshapes = false; */
665         /*      } */
666
667         /*      if (needToCalculateClosestVertex) { */
668         /*              GLint vpArr[4]; glGetIntegerv(GL_VIEWPORT, vpArr); */
669         /*              glm::vec4 viewport(vpArr[0], vpArr[1], vpArr[2], vpArr[3]); */
670         /*              glm::vec3 selectedPos = glm::unProject(glm::vec3(mouseX * 2, viewport[3] - mouseY * 2, 1), // hidpi */
671         /*                              viewMat(), */
672         /*                              projMat(), */
673         /*                              viewport); */
674
675         /*              closestVertex = targetModel->closestVertex(targetModel->getRoot(), camPos, selectedPos); */
676         /*              needToCalculateClosestVertex = false; */
677         /*      } */
678         /* } */
679
680         glutPostRedisplay();
681         glutTimerFunc(16, timer, 0);
682 }
683
684 int prevMouseX, prevMouseY;
685 bool firstMouse = true;
686
687 void motion(int x, int y) {
688         if (firstMouse) {
689                 prevMouseX = x;
690                 prevMouseY = y;
691                 firstMouse = false;
692         }
693         float dx = x - prevMouseX, dy = y - prevMouseY;
694         prevMouseX = x; prevMouseY = y;
695         
696         curMode->motion(x, y, dx, dy);
697 }
698
699 void passiveMotion(int x, int y) {
700         if (firstMouse) {
701                 prevMouseX = x;
702                 prevMouseY = y;
703                 firstMouse = false;
704         }
705         mouseX = x; mouseY = y;
706         int dx = x - prevMouseX, dy = y - prevMouseY;
707         prevMouseX = x;
708         prevMouseY = y;
709 #ifdef ENABLE_MOVEMENT
710         const float sensitivity = 0.005f;
711         yaw += dx * sensitivity;
712         pitch -= dy * sensitivity;
713
714         glm::vec3 front;
715         front.x = cos(pitch) * cos(yaw);
716         front.y = sin(pitch);
717         front.z = cos(pitch) * sin(yaw);
718         camFront = glm::normalize(front);
719
720         if (pitch < -1.57079632679 || pitch >= 1.57079632679) {
721                 camUp = glm::vec3(0, -1, 0);
722         } else {
723                 camUp = glm::vec3(0, 1, 0);
724         }
725 #endif
726
727         curMode->passiveMotion(x, y, dx, dy);
728 }
729
730 void mouse(int button, int state, int x, int y) {
731         curMode->mouse(button, state, x, y);
732
733 #ifdef ENABLE_MOVEMENT
734         if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
735                 firstMouse = true;
736 #endif
737 }
738
739 void reshape(int newWidth, int newHeight) {
740         windowWidth = newWidth, windowHeight = newHeight;
741 }
742
743 int main(int argc, char** argv) {
744         glutInit(&argc, argv);
745         glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGB|GLUT_3_2_CORE_PROFILE);
746         glutInitWindowSize(windowWidth, windowHeight);
747         glutCreateWindow("Physically Based Rendering");
748         glutDisplayFunc(display);
749         glutReshapeFunc(reshape);
750
751         glewInit();
752
753         // TODO: parse argv
754         init();
755         curMode = new AnimationMode("movieAssets/scene.glb");
756
757         glutKeyboardFunc(keyboard);
758         glutKeyboardUpFunc(keyboardUp);
759         glutTimerFunc(16, timer, 0);
760         glutMotionFunc(motion);
761         glutPassiveMotionFunc(passiveMotion);
762         glutMouseFunc(mouse);
763
764         glutMainLoop();
765
766         return 0;
767 }
768