Update gitattributes
[opengl.git] / model.cpp
index 0bb58372e521095542c3e3b2f3b1e6a5be2913b5..9e4cfc6ca026fb0e7e8ee6345acbdaf3bf90f98b 100644 (file)
--- a/model.cpp
+++ b/model.cpp
@@ -1,20 +1,11 @@
 #include "model.hpp"
 #include <iostream>
-#include <assimp/postprocess.h>
 #include <assimp/quaternion.h>
 #include <glm/gtc/type_ptr.hpp>
+#include <glm/gtx/closest_point.hpp>
+#include "util.hpp"
 
-glm::mat4 aiMatrixToMat4(aiMatrix4x4 from) {
-       glm::mat4 to;
-       for (int i = 0; i < 4; i++)
-               for (int j = 0; j < 4; j++)
-                       to[i][j] = from[j][i];
-       return to;
-}
-
-
-Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
-
+Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) : progId(progId), ai(*aiMesh) {
        std::vector<glm::vec3> vertices, normals, tangents, bitangents;
        std::vector<glm::vec2> texCoords;
 
@@ -28,7 +19,7 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
                        normals.push_back(glm::vec3(v.x, v.y, v.z));
                } else {
                        std::cerr << "Missing normals" << std::endl;
-                       exit(1);
+                       abort();
                }
                // check for texture coord set 0
                if (aiMesh->HasTextureCoords(0)) {
@@ -56,13 +47,12 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
        glGenVertexArrays(1, &vao);
        glBindVertexArray(vao);
        
-       GLuint vbos[6];
        glGenBuffers(6, vbos);
-       GLuint vertexVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3];
+       GLuint posVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3];
        GLuint boneVbo = vbos[4];
        
        GLuint posLoc = glGetAttribLocation(progId, "pos");
-       glBindBuffer(GL_ARRAY_BUFFER, vertexVbo);
+       glBindBuffer(GL_ARRAY_BUFFER, posVbo);
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
        glEnableVertexAttribArray(posLoc);
        glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
@@ -90,12 +80,13 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
        for (unsigned int i = 0; i < aiMesh->mNumBones; i++) {
                aiBone *aiBone = aiMesh->mBones[i];
 
-               boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiMatrixToMat4(aiBone->mOffsetMatrix));
+               boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiBone);
 
                for (int j = 0; j < aiBone->mNumWeights; j++) {
                        aiVertexWeight vw = aiBone->mWeights[j];
 
-                       if (!boneWeightMap.count(vw.mVertexId)) boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
+                       if (!boneWeightMap.count(vw.mVertexId))
+                               boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
                        boneWeightMap[vw.mVertexId].push_back(std::pair(i + 1, vw.mWeight));
                }
        }
@@ -122,18 +113,26 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
        glVertexAttribPointer(boneWeightLoc, 4, GL_FLOAT, GL_FALSE, sizeof(VertBones), (const GLvoid *)sizeof(VertBones::ids));
 }
 
-Model::Node::Node(const aiNode &node, GLuint progId, AnimMap *am): ai(node), progId(progId), animMap(am) {
+void Model::Mesh::updatePosBuffer() const {
+       GLuint posLoc = glGetAttribLocation(progId, "pos");
+       GLuint posVbo = vbos[0];
+       glBindBuffer(GL_ARRAY_BUFFER, posVbo);
+       glBufferData(GL_ARRAY_BUFFER, ai.mNumVertices * sizeof(aiVector3D), ai.mVertices, GL_STATIC_DRAW);
+       glEnableVertexAttribArray(posLoc);
+       glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
+}
+
+Model::Node::Node(aiNode &node, GLuint progId, AnimMap *am, std::set<std::string> allBones, Node *p): ai(node), parent(p), progId(progId), animMap(am), isBone(allBones.count(std::string(node.mName.C_Str())) > 0) {
        for (int i = 0; i < node.mNumMeshes; i++) {
                meshIndices.push_back(node.mMeshes[i]);
        }
        for (int i = 0; i < node.mNumChildren; i++) {
-               const aiNode *child = node.mChildren[i];
-               children.push_back(new Node(*child, progId, am));
+               aiNode *child = node.mChildren[i];
+               children.push_back(new Node(*child, progId, am, allBones, this));
        }
 }
 
-glm::mat4 lerp(const aiNodeAnim *anim, const float tick) {
-       
+glm::mat4 lerpPosition(const aiNodeAnim *anim, const float tick) {
        if (anim->mNumPositionKeys == 0) return glm::mat4(1.f);
 
        int yIndex = -1;
@@ -145,8 +144,10 @@ glm::mat4 lerp(const aiNodeAnim *anim, const float tick) {
                }
        }
        aiVector3D lerpPos;
-       if (yIndex < 1) {
+       if (yIndex == 0) {
                lerpPos = anim->mPositionKeys[0].mValue;
+       } else if (yIndex == -1) {
+               lerpPos = anim->mPositionKeys[anim->mNumPositionKeys - 1].mValue;
        } else {
                auto X = anim->mPositionKeys[yIndex - 1];
                auto Y = anim->mPositionKeys[yIndex];
@@ -171,6 +172,8 @@ glm::mat4 lerpRotation(const aiNodeAnim *anim, const float tick) {
        aiQuaternion result;
        if (yIndex < 1) {
                result = anim->mRotationKeys[0].mValue;
+       } else if (yIndex == -1) {
+               result = anim->mRotationKeys[anim->mNumRotationKeys - 1].mValue;
        } else {
 
                auto X = anim->mRotationKeys[yIndex - 1];
@@ -208,36 +211,51 @@ glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) {
        return aiMatrixToMat4(result);
 }
 
-void Model::Node::draw(        const std::vector<Mesh> &meshes,
-                                               const std::vector<Material> &materials,
-                                               const Skybox skybox,
-                                               const float tick,
-                                               glm::mat4 parentTrans = glm::mat4(1),
-                                               BoneTransforms boneTransforms = BoneTransforms()) const {
-
-       GLuint modelLoc = glGetUniformLocation(progId, "model");
-
-       glm::mat4 animTrans(1.f);
+glm::mat4 Model::Node::totalTrans(const glm::mat4 parentTrans, const float tick) const {
+       glm::mat4 aiTrans = aiMatrixToMat4(ai.mTransformation);
        if (animMap->count(std::string(ai.mName.C_Str()))) {
                for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) {
+                       // animations are *absolute*
+                       // they replace aiNode.mTransformation!!
+                       aiTrans = glm::mat4(1);
                        float t = fmod(tick, anim.duration);
                        for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
-                               animTrans *= lerp(nodeAnim, t);
-                               animTrans *= lerpRotation(nodeAnim, t);
-                               animTrans *= lerpScaling(nodeAnim, t);
+                               aiTrans *= lerpPosition(nodeAnim, t);
+                               aiTrans *= lerpRotation(nodeAnim, t);
+                               aiTrans *= lerpScaling(nodeAnim, t);
                        }
                }
-               /* std::cerr << std::string(ai.mName.C_Str()) << animTrans[0][0] << std::endl; */
        }
 
+       glm::mat4 m = parentTrans * aiTrans * transform;
+       return m;
+}
 
-       glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model;
-
-       for (auto child: children) {
-               //set to parent transforms
-               boneTransforms[std::string(ai.mName.C_Str())] = m;
+const Model::Node &Model::Node::getRoot() const {
+       const Model::Node *rootPtr = this;
+       while (rootPtr->parent != nullptr)
+               rootPtr = rootPtr->parent;
+       const Model::Node &root = *rootPtr;
+       return root;
 }
 
+void Model::Node::draw(        const std::vector<Mesh> &meshes,
+                                               const std::vector<Material> &materials,
+                                               const Skybox skybox,
+                                               const float tick,
+                                               const BoneTransforms &boneTransforms,
+                                               glm::mat4 parentTrans = glm::mat4(1)) const {
+
+       GLuint modelLoc = glGetUniformLocation(progId, "model");
+       glm::mat4 m = totalTrans(parentTrans, tick);
+
+#ifdef DEBUG_NODES
+       if (isBone)
+               drawDebugNode(m, {0, 0.5, 1, 1});
+       else
+               drawDebugNode(m);
+#endif
+
        for (unsigned int i: meshIndices) {
                const Mesh &mesh = meshes[i];
                glBindVertexArray(mesh.vao);
@@ -246,29 +264,23 @@ void Model::Node::draw(   const std::vector<Mesh> &meshes,
                std::vector<glm::mat4> idBones(17, glm::mat4(1.f));
                glUniformMatrix4fv(glGetUniformLocation(progId, "bones"), 17, GL_FALSE, glm::value_ptr(idBones[0]));
 
-               for (std::pair<std::string, std::pair<unsigned int, glm::mat4>> pair: mesh.boneMap) {
+               // bonemap: map from bone nodes to bone ids and aiBones
+               for (auto pair: mesh.boneMap) {
 
-                       std::string nodeName = pair.first;
-                       unsigned int boneId = pair.second.first;
-                       glm::mat4 boneOffset = pair.second.second;
-
-                       glm::mat4 boneTrans(1.f);
-                       if (boneTransforms.count(nodeName)) boneTrans = boneTransforms[nodeName];
-                       int j = 0;
-                       for (const Animation anim: animMap->at(nodeName)) {
-                               float t = fmod(tick, anim.duration);
-                               for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
-                                       boneTrans = boneTrans * lerp(nodeAnim, t);
-                                       boneTrans = boneTrans * lerpRotation(nodeAnim, t);
-                                       /* boneTrans = boneTrans * lerpScaling(nodeAnim, t); */
-                                       j++;
-                               }
-                       }
-                       assert(j == 1);
+                       std::string boneName = pair.first;
 
+                       unsigned int boneId = pair.second.first;
+                       aiBone *bone = pair.second.second;
+                       // This is actually an inverse-bind matrix
+                       // i.e. transforms bone space -> mesh space
+                       // so no need to inverse again!
+                       // https://github.com/assimp/assimp/pull/1803/files
+                       glm::mat4 boneOffset = aiMatrixToMat4(bone->mOffsetMatrix);
 
-                       boneTrans = boneTrans * glm::inverse(boneOffset);
+                       if (!boneTransforms.count(boneName)) abort();
+                       glm::mat4 boneTrans = boneTransforms.at(boneName);
 
+                       boneTrans = boneTrans * boneOffset;
 
                        std::string boneLocStr = "bones[" + std::to_string(boneId) + "]";
                        GLuint boneLoc = glGetUniformLocation(progId, boneLocStr.c_str());
@@ -294,31 +306,34 @@ void Model::Node::draw(   const std::vector<Mesh> &meshes,
 
                glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
        }
-       for (Node *child: children) child->draw(meshes, materials, skybox, tick, m, boneTransforms);
+       for (Node *child: children) child->draw(meshes, materials, skybox, tick, boneTransforms, m);
 }
 
-Model::Model(const std::string &path, Program p): program(p) {
-       glUseProgram(p.progId);
-       
-       const aiScene *scene = importer.ReadFile(path, 
-                       aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenNormals | aiProcess_FlipUVs);
-       if (!scene) {
-               std::cerr << importer.GetErrorString() << std::endl;
-               exit(1);
+void printHierarchy(aiNode *n, int indent = 0) {
+       for (int i = 0; i < indent; i++)
+               fprintf(stderr, "\t");
+       fprintf(stderr,"%s\n", n->mName.C_Str());
+       printMatrix4x4(n->mTransformation);
+       for (int i = 0; i < n->mNumChildren; i++)
+               printHierarchy(n->mChildren[i], indent + 1);
 }
 
+Model::Model(const aiScene *scene, Program p): program(p) {
+       glUseProgram(p.progId);
+
+       std::set<std::string> allBones;
        for (int i = 0; i < scene->mNumMeshes; i++) {
                const aiMesh *mesh = scene->mMeshes[i];
                meshes.push_back(Mesh(mesh, p.progId));
+               for (int j = 0; j < mesh->mNumBones; j++)
+                       allBones.insert(std::string(mesh->mBones[j]->mName.C_Str()));
        }
 
-       // TODO: handle default material inserted at the end by assimp
-       for (unsigned int i = 0; i < scene->mNumMaterials - 1; i++) {
+       for (unsigned int i = 0; i < scene->mNumMaterials; i++) {
                const aiMaterial &material = *scene->mMaterials[i];
-               materials.push_back(Material(material, p.progId));
+               materials.push_back(Material(material, *scene, p.progId));
        }
 
-       AnimMap *animMap = new AnimMap();
        for (int i = 0; i < scene->mNumAnimations; i++) {
                const aiAnimation *aiAnim = scene->mAnimations[i];
 
@@ -336,24 +351,49 @@ Model::Model(const std::string &path, Program p): program(p) {
                for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
                        std::string nodeName = pair.first;
 
-                       if (!animMap->count(nodeName)) (*animMap)[nodeName] = std::vector<const Animation>();
-                       (*animMap)[nodeName].push_back({ 7500, pair.second });
+                       if (!animMap.count(nodeName)) animMap[nodeName] = std::vector<const Animation>();
+                       animMap[nodeName].push_back({ aiAnim->mDuration, pair.second });
                }
        }
 
-       root = new Node(*(scene->mRootNode), p.progId, animMap);
+       root = new Node(*(scene->mRootNode), p.progId, &animMap, allBones, nullptr);
+}
+
+
+std::map<std::string, glm::mat4> Model::calcBoneTransforms(const Node &n, const float tick, const std::set<std::string> bones, const glm::mat4 parentTrans = glm::mat4(1)) const {
+       std::string name = std::string(n.ai.mName.C_Str());
+
+       glm::mat4 m = n.totalTrans(parentTrans, tick);
+
+       BoneTransforms res;
+       if (bones.count(name) > 0)
+               res[std::string(n.ai.mName.C_Str())] = m; // take part in hierarchy
+       else
+               m = glm::mat4(1); // ignore this node transformation
+       for (const auto child: n.getChildren())
+               res.merge(calcBoneTransforms(*child, tick, bones, m));
+       return res;
 }
 
 void Model::draw(Skybox skybox, const float tick) const {
        glUseProgram(program.progId);
-       root->draw(meshes, materials, skybox, tick);
+
+       std::set<std::string> bones;
+       for (auto m: this->meshes) {
+               for (auto b: m.boneMap) {
+                       bones.insert(b.first);
+               }
        }
+       auto boneTransforms = calcBoneTransforms(*root, tick, bones);
 
-Model::Node* Model::find(const std::string &name) {
+       root->draw(meshes, materials, skybox, tick, boneTransforms);
+}
+
+Model::Node* Model::find(const std::string &name) const {
        return find(aiString(name));
 }
 
-Model::Node* Model::find(const aiString name) {
+Model::Node* Model::find(const aiString name) const {
        const aiNode *node = root->ai.FindNode(name);
        Model::Node* res = root->findNode(*node);
        return res;
@@ -367,3 +407,46 @@ Model::Node* Model::Node::findNode(const aiNode &aiNode) {
        }
        return nullptr;
 }
+
+bool Model::Node::operator==(const Model::Node &rhs) const {
+       return &ai == &rhs.ai;
+}
+
+// Returns closest vertex in world space and distance
+// a and b define the line in 3d space
+Model::VertexLookup Model::closestVertex(Model::Node &n, glm::vec3 a, glm::vec3 b, glm::mat4 parentTrans) const {
+       Model::VertexLookup closest;
+       closest.distance = FLT_MAX;
+
+       for (int i = 0; i < n.ai.mNumMeshes; i++) {
+               int meshIdx = n.ai.mMeshes[i];
+               const aiMesh &mesh = meshes[meshIdx].ai;
+
+               for (int j = 0; j < mesh.mNumVertices; j++) {
+                       if (mesh.HasNormals()) {
+                               auto n = aiVector3DToVec3(mesh.mNormals[j]);
+                               if (glm::dot(n, glm::normalize(b - a)) > 0)
+                                       continue;
+                       }
+                       glm::vec4 vPos = glm::vec4(aiVector3DToVec3(mesh.mVertices[j]), 1);
+                       // Move from model space -> world space
+                       vPos = parentTrans * aiMatrixToMat4(n.ai.mTransformation) * vPos;
+                       float dist = glm::distance(glm::vec3(vPos),
+                                                       glm::closestPointOnLine(glm::vec3(vPos), a, b));
+                       if (dist < closest.distance) {
+                               closest.pos = glm::vec3(vPos);
+                               closest.distance = dist;
+                               closest.meshIdx = i;
+                               closest.vertIdx = j;
+                       }
+               }
+       }
+       
+       for (auto child: n.getChildren()) {
+               auto childRes = closestVertex(*child, a, b, parentTrans * aiMatrixToMat4(n.ai.mTransformation));
+               if (childRes.distance < closest.distance) 
+                       closest = childRes;
+       }
+
+       return closest;
+}