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