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