3 #include <assimp/quaternion.h>
4 #include <glm/gtc/type_ptr.hpp>
8 Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
10 std::vector<glm::vec3> vertices, normals, tangents, bitangents;
11 std::vector<glm::vec2> texCoords;
13 for (int i = 0; i < aiMesh->mNumVertices; i++) {
14 if (aiMesh->HasPositions()) {
15 aiVector3D v = aiMesh->mVertices[i];
16 vertices.push_back(glm::vec3(v.x, v.y, v.z));
18 if (aiMesh->HasNormals()) {
19 aiVector3D v = aiMesh->mNormals[i];
20 normals.push_back(glm::vec3(v.x, v.y, v.z));
22 std::cerr << "Missing normals" << std::endl;
25 // check for texture coord set 0
26 if (aiMesh->HasTextureCoords(0)) {
27 const aiVector3D v = aiMesh->mTextureCoords[0][i];
28 texCoords.push_back(glm::vec2(v.x, v.y));
30 texCoords.push_back(glm::vec2(0));
32 materialIndex = aiMesh->mMaterialIndex;
35 std::vector<GLuint> indices;
37 for (int i = 0; i < aiMesh->mNumFaces; i++) {
38 const aiFace &face = aiMesh->mFaces[i];
39 if(face.mNumIndices == 3) {
40 indices.push_back(face.mIndices[0]);
41 indices.push_back(face.mIndices[1]);
42 indices.push_back(face.mIndices[2]);
46 numIndices = indices.size();
48 glGenVertexArrays(1, &vao);
49 glBindVertexArray(vao);
52 glGenBuffers(6, vbos);
53 GLuint vertexVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3];
54 GLuint boneVbo = vbos[4];
56 GLuint posLoc = glGetAttribLocation(progId, "pos");
57 glBindBuffer(GL_ARRAY_BUFFER, vertexVbo);
58 glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
59 glEnableVertexAttribArray(posLoc);
60 glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
62 GLuint normalLoc = glGetAttribLocation(progId, "unscaledNormal");
63 glBindBuffer(GL_ARRAY_BUFFER, normalVbo);
64 glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
65 glEnableVertexAttribArray(normalLoc);
66 glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
68 GLuint texCoordLoc = glGetAttribLocation(progId, "vTexCoord");
69 glBindBuffer(GL_ARRAY_BUFFER, texCoordVbo);
70 glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(glm::vec2), &texCoords[0], GL_STATIC_DRAW);
71 glEnableVertexAttribArray(texCoordLoc);
72 glVertexAttribPointer(texCoordLoc, 2, GL_FLOAT, GL_FALSE, 0, 0);
74 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVbo);
75 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
78 std::vector<VertBones> vertBones(aiMesh->mNumVertices);
80 std::map<unsigned int, std::vector<std::pair<unsigned int, float>>> boneWeightMap;
82 for (unsigned int i = 0; i < aiMesh->mNumBones; i++) {
83 aiBone *aiBone = aiMesh->mBones[i];
85 boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiBone);
87 for (int j = 0; j < aiBone->mNumWeights; j++) {
88 aiVertexWeight vw = aiBone->mWeights[j];
90 if (!boneWeightMap.count(vw.mVertexId))
91 boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
92 boneWeightMap[vw.mVertexId].push_back(std::pair(i + 1, vw.mWeight));
96 for (auto pair: boneWeightMap) {
97 unsigned int vertexId = pair.first;
98 for (int i = 0; i < pair.second.size() && i < 4; i++) {
99 unsigned int boneId = pair.second[i].first;
100 float weight = pair.second[i].second;
101 vertBones[vertexId].ids[i] = boneId;
102 vertBones[vertexId].weights[i] = weight;
106 glBindBuffer(GL_ARRAY_BUFFER, boneVbo);
107 glBufferData(GL_ARRAY_BUFFER, sizeof(VertBones) * vertBones.size(), &vertBones[0], GL_STATIC_DRAW);
109 GLuint boneIdLoc = glGetAttribLocation(progId, "boneIds");
110 glEnableVertexAttribArray(boneIdLoc);
111 glVertexAttribIPointer(boneIdLoc, 4, GL_INT, sizeof(VertBones), 0);
113 GLuint boneWeightLoc = glGetAttribLocation(progId, "boneWeights");
114 glEnableVertexAttribArray(boneWeightLoc);
115 glVertexAttribPointer(boneWeightLoc, 4, GL_FLOAT, GL_FALSE, sizeof(VertBones), (const GLvoid *)sizeof(VertBones::ids));
118 Model::Node::Node(const aiNode &node, GLuint progId, AnimMap *am): ai(node), progId(progId), animMap(am) {
119 for (int i = 0; i < node.mNumMeshes; i++) {
120 meshIndices.push_back(node.mMeshes[i]);
122 for (int i = 0; i < node.mNumChildren; i++) {
123 const aiNode *child = node.mChildren[i];
124 children.push_back(new Node(*child, progId, am));
128 glm::mat4 lerpPosition(const aiNodeAnim *anim, const float tick) {
129 if (anim->mNumPositionKeys == 0) return glm::mat4(1.f);
132 for (int i = 0; i < anim->mNumPositionKeys; i++) {
133 aiVectorKey vk = anim->mPositionKeys[i];
134 if (vk.mTime > tick) {
141 lerpPos = anim->mPositionKeys[0].mValue;
142 } else if (yIndex == -1) {
143 lerpPos = anim->mPositionKeys[anim->mNumPositionKeys - 1].mValue;
145 auto X = anim->mPositionKeys[yIndex - 1];
146 auto Y = anim->mPositionKeys[yIndex];
148 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
151 aiMatrix4x4::Translation(lerpPos, result);
152 return aiMatrixToMat4(result);
155 glm::mat4 lerpRotation(const aiNodeAnim *anim, const float tick) {
157 for (int i = 0; i < anim->mNumRotationKeys; i++) {
158 aiQuatKey vk = anim->mRotationKeys[i];
159 if (vk.mTime > tick) {
167 result = anim->mRotationKeys[0].mValue;
168 } else if (yIndex == -1) {
169 result = anim->mRotationKeys[anim->mNumRotationKeys - 1].mValue;
172 auto X = anim->mRotationKeys[yIndex - 1];
173 auto Y = anim->mRotationKeys[yIndex];
175 float mix = (tick - X.mTime) / (Y.mTime - X.mTime);
177 aiQuaternion::Interpolate(result, X.mValue, Y.mValue, mix);
180 return aiMatrixToMat4(aiMatrix4x4(result.GetMatrix()));
183 glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) {
185 for (int i = 0; i < anim->mNumScalingKeys; i++) {
186 aiVectorKey vk = anim->mScalingKeys[i];
187 if (vk.mTime > tick) {
195 lerpPos = anim->mScalingKeys[0].mValue;
197 auto X = anim->mScalingKeys[yIndex - 1];
198 auto Y = anim->mScalingKeys[yIndex];
200 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
203 aiMatrix4x4::Scaling(lerpPos, result);
204 return aiMatrixToMat4(result);
207 glm::mat4 Model::Node::totalTrans(const glm::mat4 parentTrans, const float tick) const {
208 glm::mat4 aiTrans = aiMatrixToMat4(ai.mTransformation);
209 if (animMap->count(std::string(ai.mName.C_Str()))) {
210 for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) {
211 // animations are *absolute*
212 // they replace aiNode.mTransformation!!
213 aiTrans = glm::mat4(1);
214 float t = fmod(tick, anim.duration);
215 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
216 aiTrans *= lerpPosition(nodeAnim, t);
217 aiTrans *= lerpRotation(nodeAnim, t);
218 aiTrans *= lerpScaling(nodeAnim, t);
223 glm::mat4 m = parentTrans * aiTrans * transform;
227 void Model::Node::draw( const std::vector<Mesh> &meshes,
228 const std::vector<Material> &materials,
231 const BoneTransforms &boneTransforms,
232 glm::mat4 parentTrans = glm::mat4(1)) const {
234 GLuint modelLoc = glGetUniformLocation(progId, "model");
235 glm::mat4 m = totalTrans(parentTrans, tick);
241 for (unsigned int i: meshIndices) {
242 const Mesh &mesh = meshes[i];
243 glBindVertexArray(mesh.vao);
246 std::vector<glm::mat4> idBones(17, glm::mat4(1.f));
247 glUniformMatrix4fv(glGetUniformLocation(progId, "bones"), 17, GL_FALSE, glm::value_ptr(idBones[0]));
249 // bonemap: map from bone nodes to bone ids and aiBones
250 for (auto pair: mesh.boneMap) {
252 std::string boneName = pair.first;
254 unsigned int boneId = pair.second.first;
255 aiBone *bone = pair.second.second;
256 // This is actually an inverse-bind matrix
257 // i.e. transforms bone space -> mesh space
258 // so no need to inverse again!
259 // https://github.com/assimp/assimp/pull/1803/files
260 glm::mat4 boneOffset = aiMatrixToMat4(bone->mOffsetMatrix);
262 if (!boneTransforms.count(boneName)) abort();
263 glm::mat4 boneTrans = boneTransforms.at(boneName);
265 boneTrans = boneTrans * boneOffset;
267 std::string boneLocStr = "bones[" + std::to_string(boneId) + "]";
268 GLuint boneLoc = glGetUniformLocation(progId, boneLocStr.c_str());
269 glUniformMatrix4fv(boneLoc, 1, GL_FALSE, glm::value_ptr(boneTrans));
272 Material material = materials[mesh.materialIndex];
275 glUniform1i(glGetUniformLocation(progId, "irradianceMap"), 4);
276 glActiveTexture(GL_TEXTURE4);
277 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getIrradianceMap());
279 glUniform1i(glGetUniformLocation(progId, "prefilterMap"), 5);
280 glActiveTexture(GL_TEXTURE5);
281 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getPrefilterMap());
283 glUniform1i(glGetUniformLocation(progId, "brdfMap"), 6);
284 glActiveTexture(GL_TEXTURE6);
285 glBindTexture(GL_TEXTURE_2D, skybox.getBRDFMap());
287 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(m));
289 glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
291 for (Node *child: children) child->draw(meshes, materials, skybox, tick, boneTransforms, m);
294 void printMatrix4x4(aiMatrix4x4 m) {
295 fprintf(stderr, "%f, %f, %f, %f\n", m.a1, m.a2, m.a3, m.a4);
296 fprintf(stderr, "%f, %f, %f, %f\n", m.b1, m.b2, m.b3, m.b4);
297 fprintf(stderr, "%f, %f, %f, %f\n", m.c1, m.c2, m.c3, m.c4);
298 fprintf(stderr, "%f, %f, %f, %f\n", m.d1, m.d2, m.d3, m.d4);
301 void printHierarchy(aiNode *n, int indent = 0) {
302 for (int i = 0; i < indent; i++)
303 fprintf(stderr, "\t");
304 fprintf(stderr,"%s\n", n->mName.C_Str());
305 printMatrix4x4(n->mTransformation);
306 for (int i = 0; i < n->mNumChildren; i++)
307 printHierarchy(n->mChildren[i], indent + 1);
310 Model::Model(const aiScene *scene, Program p): program(p) {
311 glUseProgram(p.progId);
313 for (int i = 0; i < scene->mNumMeshes; i++) {
314 const aiMesh *mesh = scene->mMeshes[i];
315 meshes.push_back(Mesh(mesh, p.progId));
318 for (unsigned int i = 0; i < scene->mNumMaterials; i++) {
319 const aiMaterial &material = *scene->mMaterials[i];
320 materials.push_back(Material(material, *scene, p.progId));
323 for (int i = 0; i < scene->mNumAnimations; i++) {
324 const aiAnimation *aiAnim = scene->mAnimations[i];
326 std::map<std::string, std::vector<const aiNodeAnim*>> nodeAnims;
328 for (int j = 0; j < aiAnim->mNumChannels; j++) {
329 const aiNodeAnim *nodeAnim = aiAnim->mChannels[j];
330 std::string nodeName = std::string(nodeAnim->mNodeName.C_Str());
332 if (!nodeAnims.count(nodeName)) nodeAnims[nodeName] = std::vector<const aiNodeAnim*>();
334 nodeAnims[nodeName].push_back(nodeAnim);
337 for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
338 std::string nodeName = pair.first;
340 if (!animMap.count(nodeName)) animMap[nodeName] = std::vector<const Animation>();
341 animMap[nodeName].push_back({ aiAnim->mDuration, pair.second });
345 root = new Node(*(scene->mRootNode), p.progId, &animMap);
349 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 {
350 std::string name = std::string(n.ai.mName.C_Str());
352 glm::mat4 m = n.totalTrans(parentTrans, tick);
355 if (bones.count(name) > 0)
356 res[std::string(n.ai.mName.C_Str())] = m; // take part in hierarchy
358 m = glm::mat4(1); // ignore this node transformation
359 for (const auto child: n.getChildren())
360 res.merge(calcBoneTransforms(*child, tick, bones, m));
364 void Model::draw(Skybox skybox, const float tick) const {
365 glUseProgram(program.progId);
367 std::set<std::string> bones;
368 for (auto m: this->meshes) {
369 for (auto b: m.boneMap) {
370 bones.insert(b.first);
373 auto boneTransforms = calcBoneTransforms(*root, tick, bones);
375 root->draw(meshes, materials, skybox, tick, boneTransforms);
378 Model::Node* Model::find(const std::string &name) const {
379 return find(aiString(name));
382 Model::Node* Model::find(const aiString name) const {
383 const aiNode *node = root->ai.FindNode(name);
384 Model::Node* res = root->findNode(*node);
388 Model::Node* Model::Node::findNode(const aiNode &aiNode) {
389 if (&ai == &aiNode) return this;
390 for (Model::Node *child: children) {
391 Model::Node *res = child->findNode(aiNode);