X-Git-Url: https://git.lukelau.me/?p=opengl.git;a=blobdiff_plain;f=model.cpp;h=f4fc307ebca7db0515ce0af40bc74d916ccc2021;hp=8046e29434fcf467b29942dc56aa5b60b76b84cf;hb=45e43c5d0b6a1415185211128d82190fd19c3fe9;hpb=ba9c738e8660304aa0341eb44118e63502a4a009 diff --git a/model.cpp b/model.cpp index 8046e29..f4fc307 100644 --- a/model.cpp +++ b/model.cpp @@ -1,7 +1,9 @@ #include "model.hpp" #include -#include +#include #include +#include "util.hpp" + Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) { @@ -17,16 +19,8 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) { aiVector3D v = aiMesh->mNormals[i]; normals.push_back(glm::vec3(v.x, v.y, v.z)); } else { - normals.push_back(glm::vec3(0)); - } - if (aiMesh->HasTangentsAndBitangents()) { - aiVector3D t = aiMesh->mTangents[i]; - tangents.push_back(glm::vec3(t.x, t.y, t.z)); - aiVector3D b = aiMesh->mBitangents[i]; - bitangents.push_back(glm::vec3(b.x, b.y, b.z)); - } else { - tangents.push_back(glm::vec3(0)); - bitangents.push_back(glm::vec3(0)); + std::cerr << "Missing normals" << std::endl; + abort(); } // check for texture coord set 0 if (aiMesh->HasTextureCoords(0)) { @@ -57,15 +51,15 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) { GLuint vbos[6]; glGenBuffers(6, vbos); GLuint vertexVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3]; - GLuint tangentVbo = vbos[4], bitangentVbo = vbos[5]; + GLuint boneVbo = vbos[4]; - GLuint posLoc = glGetAttribLocation(progId, "vPosition"); + GLuint posLoc = glGetAttribLocation(progId, "pos"); glBindBuffer(GL_ARRAY_BUFFER, vertexVbo); 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); - GLuint normalLoc = glGetAttribLocation(progId, "vNormal"); + GLuint normalLoc = glGetAttribLocation(progId, "unscaledNormal"); glBindBuffer(GL_ARRAY_BUFFER, normalVbo); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); glEnableVertexAttribArray(normalLoc); @@ -77,88 +71,323 @@ Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) { glEnableVertexAttribArray(texCoordLoc); glVertexAttribPointer(texCoordLoc, 2, GL_FLOAT, GL_FALSE, 0, 0); - GLuint tangentLoc = glGetAttribLocation(progId, "tangent"); - glBindBuffer(GL_ARRAY_BUFFER, tangentVbo); - glBufferData(GL_ARRAY_BUFFER, tangents.size() * sizeof(glm::vec3), &tangents[0], GL_STATIC_DRAW); - glEnableVertexAttribArray(tangentLoc); - glVertexAttribPointer(tangentLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); - - GLuint bitangentLoc = glGetAttribLocation(progId, "bitangent"); - glBindBuffer(GL_ARRAY_BUFFER, bitangentVbo); - glBufferData(GL_ARRAY_BUFFER, bitangents.size() * sizeof(glm::vec3), &bitangents[0], GL_STATIC_DRAW); - glEnableVertexAttribArray(bitangentLoc); - glVertexAttribPointer(bitangentLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVbo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW); -}; -Model::Node::Node(const aiNode &node, GLuint progId): ai(node), progId(progId) { + // bones + std::vector vertBones(aiMesh->mNumVertices); + + std::map>> boneWeightMap; + + 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, aiBone); + + for (int j = 0; j < aiBone->mNumWeights; j++) { + aiVertexWeight vw = aiBone->mWeights[j]; + + if (!boneWeightMap.count(vw.mVertexId)) + boneWeightMap[vw.mVertexId] = std::vector>(); + boneWeightMap[vw.mVertexId].push_back(std::pair(i + 1, vw.mWeight)); + } + } + + for (auto pair: boneWeightMap) { + unsigned int vertexId = pair.first; + for (int i = 0; i < pair.second.size() && i < 4; i++) { + unsigned int boneId = pair.second[i].first; + float weight = pair.second[i].second; + vertBones[vertexId].ids[i] = boneId; + vertBones[vertexId].weights[i] = weight; + } + } + + glBindBuffer(GL_ARRAY_BUFFER, boneVbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(VertBones) * vertBones.size(), &vertBones[0], GL_STATIC_DRAW); + + GLuint boneIdLoc = glGetAttribLocation(progId, "boneIds"); + glEnableVertexAttribArray(boneIdLoc); + glVertexAttribIPointer(boneIdLoc, 4, GL_INT, sizeof(VertBones), 0); + + GLuint boneWeightLoc = glGetAttribLocation(progId, "boneWeights"); + glEnableVertexAttribArray(boneWeightLoc); + glVertexAttribPointer(boneWeightLoc, 4, GL_FLOAT, GL_FALSE, sizeof(VertBones), (const GLvoid *)sizeof(VertBones::ids)); +} + +Model::Node::Node(aiNode &node, GLuint progId, AnimMap *am, std::set 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)); + aiNode *child = node.mChildren[i]; + children.push_back(new Node(*child, progId, am, allBones, this)); + } +} + +glm::mat4 lerpPosition(const aiNodeAnim *anim, const float tick) { + if (anim->mNumPositionKeys == 0) return glm::mat4(1.f); + + int yIndex = -1; + for (int i = 0; i < anim->mNumPositionKeys; i++) { + aiVectorKey vk = anim->mPositionKeys[i]; + if (vk.mTime > tick) { + yIndex = i; + break; + } + } + aiVector3D lerpPos; + 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]; + + lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime); + } + aiMatrix4x4 result; + aiMatrix4x4::Translation(lerpPos, result); + return aiMatrixToMat4(result); +} + +glm::mat4 lerpRotation(const aiNodeAnim *anim, const float tick) { + int yIndex = -1; + for (int i = 0; i < anim->mNumRotationKeys; i++) { + aiQuatKey vk = anim->mRotationKeys[i]; + if (vk.mTime > tick) { + yIndex = i; + break; + } + } + + 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]; + auto Y = anim->mRotationKeys[yIndex]; + + float mix = (tick - X.mTime) / (Y.mTime - X.mTime); + + aiQuaternion::Interpolate(result, X.mValue, Y.mValue, mix); + + } + return aiMatrixToMat4(aiMatrix4x4(result.GetMatrix())); +} + +glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) { + int yIndex = -1; + for (int i = 0; i < anim->mNumScalingKeys; i++) { + aiVectorKey vk = anim->mScalingKeys[i]; + if (vk.mTime > tick) { + yIndex = i; + break; + } + } + + aiVector3D lerpPos; + if (yIndex < 1) { + lerpPos = anim->mScalingKeys[0].mValue; + } else { + auto X = anim->mScalingKeys[yIndex - 1]; + auto Y = anim->mScalingKeys[yIndex]; + + lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime); + } + aiMatrix4x4 result; + aiMatrix4x4::Scaling(lerpPos, result); + return aiMatrixToMat4(result); +} + +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) { + aiTrans *= lerpPosition(nodeAnim, t); + aiTrans *= lerpRotation(nodeAnim, t); + aiTrans *= lerpScaling(nodeAnim, t); + } } } -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; + glm::mat4 m = parentTrans * aiTrans * transform; + return 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 &meshes, const std::vector &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 = parentTrans * aiMatrixToMat4(ai.mTransformation) * 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); + // bones + std::vector idBones(17, glm::mat4(1.f)); + glUniformMatrix4fv(glGetUniformLocation(progId, "bones"), 17, GL_FALSE, glm::value_ptr(idBones[0])); + + // bonemap: map from bone nodes to bone ids and aiBones + for (auto pair: mesh.boneMap) { + + 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); + + 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()); + glUniformMatrix4fv(boneLoc, 1, GL_FALSE, glm::value_ptr(boneTrans)); + } + Material material = materials[mesh.materialIndex]; material.bind(); + glUniform1i(glGetUniformLocation(progId, "irradianceMap"), 4); + glActiveTexture(GL_TEXTURE4); + glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getIrradianceMap()); + + glUniform1i(glGetUniformLocation(progId, "prefilterMap"), 5); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getPrefilterMap()); + + glUniform1i(glGetUniformLocation(progId, "brdfMap"), 6); + glActiveTexture(GL_TEXTURE6); + glBindTexture(GL_TEXTURE_2D, skybox.getBRDFMap()); + glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(m)); glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0); } - for (Node *child: children) child->draw(meshes, materials, m); + for (Node *child: children) child->draw(meshes, materials, skybox, tick, boneTransforms, m); } -Model::Model(const std::string &path, GLuint progId): progId(progId) { - const aiScene *scene = importer.ReadFile(path, - aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenNormals); - 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 allBones; for (int i = 0; i < scene->mNumMeshes; i++) { const aiMesh *mesh = scene->mMeshes[i]; - meshes.push_back(Mesh(mesh, progId)); + 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())); } for (unsigned int i = 0; i < scene->mNumMaterials; i++) { const aiMaterial &material = *scene->mMaterials[i]; - materials.push_back(Material(material, progId)); + materials.push_back(Material(material, *scene, p.progId)); } - root = new Node(*(scene->mRootNode), progId); + for (int i = 0; i < scene->mNumAnimations; i++) { + const aiAnimation *aiAnim = scene->mAnimations[i]; + + std::map> nodeAnims; + + for (int j = 0; j < aiAnim->mNumChannels; j++) { + const aiNodeAnim *nodeAnim = aiAnim->mChannels[j]; + std::string nodeName = std::string(nodeAnim->mNodeName.C_Str()); + + if (!nodeAnims.count(nodeName)) nodeAnims[nodeName] = std::vector(); + + nodeAnims[nodeName].push_back(nodeAnim); + } + + for (std::pair> pair: nodeAnims) { + std::string nodeName = pair.first; + + if (!animMap.count(nodeName)) animMap[nodeName] = std::vector(); + animMap[nodeName].push_back({ aiAnim->mDuration, pair.second }); + } + } + + root = new Node(*(scene->mRootNode), p.progId, &animMap, allBones, nullptr); +} + + +std::map Model::calcBoneTransforms(const Node &n, const float tick, const std::set 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() const { - root->draw(meshes, materials); +void Model::draw(Skybox skybox, const float tick) const { + glUseProgram(program.progId); + + std::set 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) { - const aiNode *node = root->ai.FindNode(aiString(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) const { + const aiNode *node = root->ai.FindNode(name); Model::Node* res = root->findNode(*node); return res; } @@ -171,3 +400,7 @@ Model::Node* Model::Node::findNode(const aiNode &aiNode) { } return nullptr; } + +bool Model::Node::operator==(const Model::Node &rhs) const { + return &ai == &rhs.ai; +}