Load lights from model
[opengl.git] / main.cpp
index ef18bf2f72de2475d2f8fda9270445bc1f146524..281da276905660e1e4a5935c1caf961f9c53d97f 100644 (file)
--- a/main.cpp
+++ b/main.cpp
@@ -1,8 +1,6 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <iostream>
-#include <fstream>
-#include <sstream>
 #include <array>
 #include <vector>
 #ifdef __APPLE__
 #include <OpenGL/glew.h>
 #endif
 #include <GLUT/glut.h>
+#include "shapes.hpp"
 #include <glm/glm.hpp>
 #include <glm/ext.hpp>
 #include <glm/gtc/type_ptr.hpp>
+#include <assimp/Importer.hpp>
+#include <assimp/scene.h>
+#include <assimp/postprocess.h>
+#include "model.hpp"
+#include "program.hpp"
+#include "skybox.hpp"
+#include "image.hpp"
+#include "util.hpp"
 
 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
 
 using namespace std;
 
-GLuint* vaos;
-GLuint progId;
-glm::vec3 camPos   = glm::vec3(0.0f, 0.0f,  -5.0f);
-glm::vec3 camFront = glm::vec3(0.0f, 0.0f, 1.0f);
-glm::vec3 camUp    = glm::vec3(0.0f, 1.0f,  0.0f);
-float yaw = 1.57, pitch = 0;
-bool doScale, doRotate, doTranslate;
+GLuint lightVao;
 
-void display() {
-       glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
-       glUseProgram(progId);
-       glBindVertexArray(vaos[0]);
+Program *textureProg, *plainProg, *reflectProg, *pbrProg;
 
-       float d = (float)glutGet(GLUT_ELAPSED_TIME) * 0.001f;
+std::vector<Skybox> skyboxes;
+int activeSkybox = 0;
 
-       GLuint projId = glGetUniformLocation(progId, "projection");
-       glm::mat4 proj = glm::perspective(glm::radians(45.f), 1.33f, 0.01f, 10000.f);
-       glUniformMatrix4fv(projId, 1, GL_FALSE, glm::value_ptr(proj));
+Assimp::Importer importer; // Need to keep this around, otherwise stuff disappears!
+Model *sceneModel;
 
-       GLuint viewId = glGetUniformLocation(progId, "view");
-       glm::mat4 view = glm::lookAt(camPos, camPos + camFront, camUp);
-       glUniformMatrix4fv(viewId, 1, GL_FALSE, glm::value_ptr(view));
+glm::vec3 camPos = {0, 0, -5}, camFront = {0, 0, 1}, camUp = {0, 1, 0};
+float fov = glm::radians(30.f), znear = 0.01f, zfar = 10000.f;
+float yaw = 1.57, pitch = 0;
 
-       GLuint lightPosLoc = glGetUniformLocation(progId, "lightPos");
-       glm::vec3 lightPos = glm::vec3(sin(d) * 10, 0, 0);//10 * cos(d));
-       glUniform3fv(lightPosLoc, 1, glm::value_ptr(lightPos));
+struct Light {
+       glm::mat4 trans;
+       glm::vec3 color;
+};
 
-       GLuint viewPosLoc = glGetUniformLocation(progId, "viewPos");
-       glUniform3fv(viewPosLoc, 1, glm::value_ptr(camPos));
+std::vector<Light> lights;
 
-       GLuint modelId = glGetUniformLocation(progId, "model");
+bool discoLights = false;
 
-       for (int i = 0; i < 10; i++) {
+int windowWidth = 800, windowHeight = 600;
 
-               glm::mat4 model = glm::mat4(1.f);
+float aspect() {
+       return (float)windowWidth / (float)windowHeight;
+}      
 
-               model = glm::translate(model, glm::vec3(sin(i * 30) * 10, 0, i * 2 - 10));
+glm::mat4 projMat() {
+       return glm::perspective(fov, aspect(), znear, zfar);
+}
 
-               if (doRotate) {
-                       model = glm::rotate(model, d * glm::radians(30.f), glm::vec3(0.f, 1.f, 0.f));
-                       model = glm::rotate(model, d * glm::radians(20.f), glm::vec3(1.f, 0.f, 0.f));
+glm::mat4 viewMat() {
+       return glm::lookAt(camPos, camPos + camFront, camUp);
 }
 
-               if (doScale)
-                       model = glm::scale(model, glm::vec3(1.f, 0.7f + 0.7f * (1 + sin(d + (i + 3))), 1.f));
+void setProjectionAndViewUniforms(GLuint progId) {
+       GLuint projLoc = glGetUniformLocation(progId, "projection");
+       glm::mat4 proj = projMat();
+       glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
 
-               if (doTranslate)
-                       model = glm::translate(model, glm::vec3(sin(d + (i + 1)), cos(d + (i + -3)), sin(d + (i + 4))));
+       GLuint viewLoc = glGetUniformLocation(progId, "view");
+       glm::mat4 view = viewMat();
+       glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
 
+       GLuint camPosLoc = glGetUniformLocation(progId, "camPos");
+       glUniform3fv(camPosLoc, 1, glm::value_ptr(camPos));
+}
 
-               glUniformMatrix4fv(modelId, 1, GL_FALSE, glm::value_ptr(model));
+void setLightColorAndPos(GLuint progId, glm::vec3 lightPos, glm::vec4 lightColor) {
+       GLuint lightColorLoc = glGetUniformLocation(progId, "lightColor");
+       glUniform4fv(lightColorLoc, 1, glm::value_ptr(lightColor));
 
-               glDrawArrays(GL_TRIANGLES, 0, 12);
-       }
-       glutSwapBuffers();
+       GLuint lightPosLoc = glGetUniformLocation(progId, "vLightPos");
+       glUniform3fv(lightPosLoc, 1, glm::value_ptr(lightPos));
+
+       GLuint viewPosLoc = glGetUniformLocation(progId, "vViewPos");
+       glUniform3fv(viewPosLoc, 1, glm::value_ptr(camPos));
 }
 
-void attachShader(GLuint progId, const char* filePath, GLenum type) {
-       GLuint shader = glCreateShader(type);
+void drawLight(Light &light) {
+       glUseProgram(plainProg->progId);
+       glBindVertexArray(lightVao);
+       setProjectionAndViewUniforms(plainProg->progId);
+       glm::mat4 model = glm::scale(light.trans, glm::vec3(0.2));
+       GLuint modelLoc = glGetUniformLocation(plainProg->progId, "model");
+       glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
 
-       if (!shader) {
-               fprintf(stderr, "error creating shader\n");
-               exit(1);
-       }
+       GLuint colorLoc = glGetUniformLocation(plainProg->progId, "color");
+       glUniform4fv(colorLoc, 1, glm::value_ptr(light.color));
                
-       ifstream file(filePath);
-       stringstream buffer;
-       buffer << file.rdbuf();
-       string str = buffer.str();
-       const char* contents = str.c_str();
-
-       glShaderSource(shader, 1, (const GLchar**)&contents, NULL);
-       glCompileShader(shader);
-       GLint success;
-       glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
-       if (!success) {
-               GLchar log[1024];
-               glGetShaderInfoLog(shader, 1024, NULL, log);
-               fprintf(stderr, "error: %s\n", log);
-               exit(1);
-       }
-       glAttachShader(progId, shader);
+       glDrawArrays(GL_TRIANGLES, 0, 36);
 }
 
-GLuint compileShaders(char* vertexShader, char* fragmentShader) {
-       GLuint progId = glCreateProgram();
 
-       attachShader(progId, vertexShader, GL_VERTEX_SHADER);
-       attachShader(progId, fragmentShader, GL_FRAGMENT_SHADER);
+void display() {
+       glClearColor(0.5, 0.5, 0.5, 1);
+       glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
+       glViewport(0, 0, windowWidth * 2, windowHeight * 2);
 
-       glLinkProgram(progId);
-       GLint success = 0;
-       glGetProgramiv(progId, GL_LINK_STATUS, &success);
-       if (!success) {
-               GLchar log[1024];
-               glGetProgramInfoLog(progId, sizeof(log), NULL, log);
-               fprintf(stderr, "error linking: %s\n", log);
-               exit(1);
+       float d = (float)glutGet(GLUT_ELAPSED_TIME) * 0.001f;
+
+       glUseProgram(getUtilProg()->progId);
+       setProjectionAndViewUniforms(getUtilProg()->progId);
+
+       glUseProgram(pbrProg->progId);
+       setProjectionAndViewUniforms(pbrProg->progId);
+
+       size_t numLights = lights.size() + (discoLights ? 3 : 0);
+       glm::vec3 lightPositions[numLights], lightColors[numLights];
+       for (int i = 0; i < lights.size(); i++) {
+               lightPositions[i] = glm::vec3(lights[i].trans[3]);
+               lightColors[i] = lights[i].color;
        }
 
-       return progId;
+       if (discoLights) {
+               for (int i = numLights - 3; i < numLights; i++) {
+                       auto m = glm::translate(glm::mat4(1.f), glm::vec3(-2.5, 0, 0));
+                       m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(1, 0, 0));
+                       m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(0, 1, 0));
+                       m = glm::rotate(m, glm::radians(d * 100 + i * 30), glm::vec3(0, 0, 1));
+                       lightPositions[i] = glm::vec3(m * glm::vec4(5, 0, 0, 1));
+                       lightColors[i] = glm::vec3(0.2);
+                       if (i % 3 == 0) lightColors[i].x = sin(d);
+                       if (i % 3 == 1) lightColors[i].y = cos(d * 3);
+                       if (i % 3 == 2) lightColors[i].z = cos(d);
+               }
        }
        
-#define BUFFER_OFFSET(i) ((char *)NULL + (i))
+       glUniform1ui(glGetUniformLocation(pbrProg->progId, "numLights"), numLights);
+       glUniform3fv(glGetUniformLocation(pbrProg->progId, "lightPositions"), numLights, glm::value_ptr(lightPositions[0]));
+       glUniform3fv(glGetUniformLocation(pbrProg->progId, "lightColors"), numLights, glm::value_ptr(lightColors[0]));
 
-GLuint setupBuffers(glm::vec3* vertices, glm::vec3* normals, GLuint progId) {
+       /* sceneModel->find("Top Bone")->transform = glm::rotate(glm::mat4(1), d / 5.f, { 1, 0, 0}); */
+       /* sceneModel->find("Bottom Bone")->transform = glm::rotate(glm::mat4(1), d / 3.f, { 1, 0, 0}); */
+       sceneModel->draw(skyboxes[activeSkybox], d * 1000);
 
-       GLfloat colors[] = {
-               0, 1, 0, 1,
-               1, 0, 0, 1,
-               0, 0, 1, 1,
+       for (Light &light: lights) drawLight(light);
 
-               0, 1, 0, 1,
-               1, 0, 0, 1,
-               0, 0, 1, 1,
+       // TODO: restore
+       /* if (discoLights) { */
+       /*      for (int i = numLights - 3; i < numLights; i++) { */
+       /*              Light l = { lightPositions[i], lightColors[i] }; */
+       /*              drawLight(l); */
+       /*      } */
+       /* } */
 
-               0, 1, 0, 1,
-               1, 0, 0, 1,
-               0, 0, 1, 1,
+       skyboxes[activeSkybox].draw(projMat(), viewMat());
 
-               0, 1, 0, 1,
-               1, 0, 0, 1,
-               0, 0, 1, 1
-       };
+       glutSwapBuffers();
+}
 
-       GLuint numVerts = 12;
+void setupLightBuffers(GLuint progId) {
+       auto vertices = cube();
+       GLuint verticesSize = 36 * 3 * sizeof(GLfloat);
 
+       glGenVertexArrays(1, &lightVao);
        GLuint vbo;
+       glBindVertexArray(lightVao);
        glGenBuffers(1, &vbo);
-
-       GLuint vao;
-       glGenVertexArrays(1, &vao);
-
-       GLuint posId = glGetAttribLocation(progId, "vPosition");
-       GLuint colorId = glGetAttribLocation(progId, "vColor");
-       GLuint normalLoc = glGetAttribLocation(progId, "vNormal");
-
-       GLuint vertsLen = numVerts * 3 * sizeof(GLfloat);
-       GLuint colorsLen = numVerts * 4 * sizeof(GLfloat);
-       GLuint normalLen = numVerts * 3 * sizeof(GLfloat);
-
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
-       glBufferData(GL_ARRAY_BUFFER, vertsLen + colorsLen + normalLen, NULL, GL_STATIC_DRAW);
+       glBufferData(GL_ARRAY_BUFFER, verticesSize, NULL, GL_STATIC_DRAW);
+       glBufferSubData(GL_ARRAY_BUFFER, 0, verticesSize, glm::value_ptr(vertices[0]));
+       GLuint posLoc = glGetAttribLocation(progId, "vPosition");
+       glEnableVertexAttribArray(posLoc);
+       glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
+}
 
-       glBufferSubData(GL_ARRAY_BUFFER, 0, vertsLen, glm::value_ptr(vertices[0]));
-       glBufferSubData(GL_ARRAY_BUFFER, vertsLen, colorsLen, colors);
-       glBufferSubData(GL_ARRAY_BUFFER, vertsLen + colorsLen, normalLen, glm::value_ptr(normals[0]));
+int findNodeTrans(struct aiNode *n, const struct aiString name, glm::mat4 *dest) {
+       if (strcmp(n->mName.data, name.data) == 0) {
+               *dest = aiMatrixToMat4(n->mTransformation);
+               return 0;
+       }
+       for (int i = 0; i < n->mNumChildren; i++) {
+               if (findNodeTrans(n->mChildren[i], name, dest) == 0) {
+                       glm::mat4 t = aiMatrixToMat4(n->mTransformation);
+                       *dest = t * *dest;
+                       return 0;
+               }
+       }
+       return 1;
+}
 
-       glBindVertexArray(vao);
+void init() {
+       initUtilProg();
 
-       glEnableVertexAttribArray(posId);
-       glVertexAttribPointer(posId, 3, GL_FLOAT, GL_FALSE, 0, 0);
+       plainProg = new Program("plainvertex.glsl", "plainfrag.glsl");
+       glUseProgram(plainProg->progId);
+       setupLightBuffers(plainProg->progId);
+       plainProg->validate();
 
-       glEnableVertexAttribArray(colorId);
-       glVertexAttribPointer(colorId, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(vertsLen));
+       skyboxes.push_back(Skybox(Image("skyboxes/loft/Newport_Loft_Ref.hdr")));
+       skyboxes.push_back(Skybox(Image("skyboxes/wooden_lounge_8k.hdr")));
+       skyboxes.push_back(Skybox(Image("skyboxes/machine_shop_02_8k.hdr")));
+       skyboxes.push_back(Skybox(Image("skyboxes/pink_sunrise_8k.hdr")));
 
-       glEnableVertexAttribArray(normalLoc);
-       glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(vertsLen + colorsLen));
+       pbrProg = new Program("pbrvert.glsl", "pbrfrag.glsl");
+       glUseProgram(pbrProg->progId);
 
-       return vao;
+       const std::string scenePath = "models/newtonsCradle.glb";
+       const aiScene *scene = importer.ReadFile(scenePath, aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenNormals | aiProcess_FlipUVs);
+       if (!scene) {
+               std::cerr << importer.GetErrorString() << std::endl;
+               exit(1);
        }
 
-void validateProgram(GLuint progId) {
-       glValidateProgram(progId);
+       if (scene->mNumCameras > 0) {
+               aiCamera *cam = scene->mCameras[0];
+               glm::mat4 camTrans;
+               if (findNodeTrans(scene->mRootNode, cam->mName, &camTrans) != 0)
+                       abort(); // there must be a node with the same name as camera
 
-       GLint success;
-       glGetProgramiv(progId, GL_VALIDATE_STATUS, &success);
-       if (!success) {
-               GLchar log[1024];
-               glGetProgramInfoLog(progId, sizeof(log), NULL, log);
-               fprintf(stderr, "error: %s\n", log);
-               exit(1);
-       }
-}
+               camPos = { camTrans[3][0], camTrans[3][1], camTrans[3][2] };
 
-void init() {
-       glm::vec3 vertices[12] = {
-               glm::vec3(0.0f, 1.0f, 0.0f),
-               glm::vec3(1.0f, -1.0f, -1.0f),
-               glm::vec3(-1.0f, -1.0f, -1.0f),
-
-               glm::vec3(0.0f, 1.0f, 0.0f),
-               glm::vec3(-1.0f, -1.0f, 1.0f),
-               glm::vec3(1.0f, -1.0f, 1.0f),
-
-               glm::vec3(0.0f, 1.0f, 0.0f),
-               glm::vec3(-1.0f, -1.0f, -1.0f),
-               glm::vec3(-1.0f, -1.0f, 1.0f),
-
-               glm::vec3(0.0f, 1.0f, 0.0f),
-               glm::vec3(1.0f, -1.0f, 1.0f),
-               glm::vec3(1.0f, -1.0f, -1.0f)
-       };
+               glm::vec3 camLookAt = glm::vec3(cam->mLookAt.x, cam->mLookAt.y, cam->mLookAt.z);
+               camFront = camLookAt - camPos;
 
-       // work out the normals
-       glm::vec3 normals[12];
-       for (int i = 0; i < 4; i++) {
-               glm::vec3 a = vertices[i * 3];
-               glm::vec3 b = vertices[i * 3 + 1];
-               glm::vec3 c = vertices[i * 3 + 2];
-               glm::vec3 u = glm::normalize(a - c);
-               glm::vec3 v = glm::normalize(b - c);
-               glm::vec3 norm = glm::normalize(glm::cross(v, u));
-               for(int j = 0; j < 3; j++) {
-                       normals[i * 3 + j] = glm::vec3(norm);
-               }
+               camUp = glm::vec3(cam->mUp.x, cam->mUp.y, cam->mUp.z);
+               
+               fov = cam->mHorizontalFOV;
+               // TODO: aspectRatio = cam->mAspect;
+               znear = cam->mClipPlaneNear;
+               zfar = cam->mClipPlaneFar;
        }
 
-       vaos = new GLuint[2];
+       for (int i = 0; i < scene->mNumLights; i++) {
+               aiLight *light = scene->mLights[i];
+               glm::mat4 trans; findNodeTrans(scene->mRootNode, light->mName, &trans);
+               glm::vec3 col = { light->mColorAmbient.r, light->mColorAmbient.g, light->mColorAmbient.b };
+               Light l = { trans, col };
+               lights.push_back(l);
+       }
 
-       progId = compileShaders((char*)"vertex.glsl", (char*)"fragment.glsl");
-       glUseProgram(progId);
-       vaos[0] = setupBuffers(vertices, normals, progId);
-       validateProgram(progId);
+       sceneModel = new Model(scene, *pbrProg);
 
        glEnable(GL_DEPTH_TEST); 
        glEnable(GL_CULL_FACE); 
+       // prevent edge artifacts in specular cubemaps
+       glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
+
+       glViewport(0, 0, windowWidth, windowHeight);
 }
 
-bool* keyStates = new bool[256];
+bool keyStates[256] = {false};
 
 void keyboard(unsigned char key, int x, int y) {
        keyStates[key] = true;
        if (key == 'z')
-               doScale = !doScale;
-       if (key == 'x')
-               doRotate = !doRotate;
+               activeSkybox = (activeSkybox + 1) % skyboxes.size();
        if (key == 'c')
-               doTranslate = !doTranslate;
+               discoLights = !discoLights;
 }
 
 void keyboardUp(unsigned char key, int x, int y) {
        keyStates[key] = false;
 }
 
+#define ENABLE_MOVEMENT
+
 void timer(int _) {
+#ifdef ENABLE_MOVEMENT
        float xSpeed = 0.f, ySpeed = 0.f, zSpeed = 0.f;
        if (keyStates['w'])
                zSpeed = 0.1f;
@@ -272,6 +285,7 @@ void timer(int _) {
        camPos.x += xSpeed * sin(yaw) + zSpeed * cos(yaw);
        camPos.y += ySpeed;
        camPos.z += zSpeed * sin(yaw) - xSpeed * cos(yaw);
+#endif
        glutPostRedisplay();
        glutTimerFunc(16, timer, 0);
 }
@@ -280,6 +294,7 @@ int prevMouseX, prevMouseY;
 bool firstMouse = true;
 
 void motion(int x, int y) {
+#ifdef ENABLE_MOVEMENT
        if (firstMouse) {
                prevMouseX = x;
                prevMouseY = y;
@@ -299,6 +314,13 @@ void motion(int x, int y) {
        front.y = sin(pitch);
        front.z = cos(pitch) * sin(yaw);
        camFront = glm::normalize(front);
+
+       if (pitch < -1.57079632679 || pitch >= 1.57079632679) {
+               camUp = glm::vec3(0, -1, 0);
+       } else {
+               camUp = glm::vec3(0, 1, 0);
+       }
+#endif
 }
 
 void mouse(int button, int state, int x, int y) {
@@ -306,12 +328,17 @@ void mouse(int button, int state, int x, int y) {
                firstMouse = true;
 }
 
+void reshape(int newWidth, int newHeight) {
+       windowWidth = newWidth, windowHeight = newHeight;
+}
+
 int main(int argc, char** argv) {
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGB|GLUT_3_2_CORE_PROFILE);
-       glutInitWindowSize(800, 600);
-       int win = glutCreateWindow("Hello Triangle");
+       glutInitWindowSize(windowWidth, windowHeight);
+       glutCreateWindow("Physically Based Rendering");
        glutDisplayFunc(display);
+       glutReshapeFunc(reshape);
 
        glewInit();