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