3 #include <assimp/quaternion.h>
4 #include <glm/gtc/type_ptr.hpp>
7 Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
9 std::vector<glm::vec3> vertices, normals, tangents, bitangents;
10 std::vector<glm::vec2> texCoords;
12 for (int i = 0; i < aiMesh->mNumVertices; i++) {
13 if (aiMesh->HasPositions()) {
14 aiVector3D v = aiMesh->mVertices[i];
15 vertices.push_back(glm::vec3(v.x, v.y, v.z));
17 if (aiMesh->HasNormals()) {
18 aiVector3D v = aiMesh->mNormals[i];
19 normals.push_back(glm::vec3(v.x, v.y, v.z));
21 std::cerr << "Missing normals" << std::endl;
24 // check for texture coord set 0
25 if (aiMesh->HasTextureCoords(0)) {
26 const aiVector3D v = aiMesh->mTextureCoords[0][i];
27 texCoords.push_back(glm::vec2(v.x, v.y));
29 texCoords.push_back(glm::vec2(0));
31 materialIndex = aiMesh->mMaterialIndex;
34 std::vector<GLuint> indices;
36 for (int i = 0; i < aiMesh->mNumFaces; i++) {
37 const aiFace &face = aiMesh->mFaces[i];
38 if(face.mNumIndices == 3) {
39 indices.push_back(face.mIndices[0]);
40 indices.push_back(face.mIndices[1]);
41 indices.push_back(face.mIndices[2]);
45 numIndices = indices.size();
47 glGenVertexArrays(1, &vao);
48 glBindVertexArray(vao);
51 glGenBuffers(6, vbos);
52 GLuint vertexVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3];
53 GLuint boneVbo = vbos[4];
55 GLuint posLoc = glGetAttribLocation(progId, "pos");
56 glBindBuffer(GL_ARRAY_BUFFER, vertexVbo);
57 glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
58 glEnableVertexAttribArray(posLoc);
59 glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
61 GLuint normalLoc = glGetAttribLocation(progId, "unscaledNormal");
62 glBindBuffer(GL_ARRAY_BUFFER, normalVbo);
63 glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
64 glEnableVertexAttribArray(normalLoc);
65 glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
67 GLuint texCoordLoc = glGetAttribLocation(progId, "vTexCoord");
68 glBindBuffer(GL_ARRAY_BUFFER, texCoordVbo);
69 glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(glm::vec2), &texCoords[0], GL_STATIC_DRAW);
70 glEnableVertexAttribArray(texCoordLoc);
71 glVertexAttribPointer(texCoordLoc, 2, GL_FLOAT, GL_FALSE, 0, 0);
73 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVbo);
74 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
77 std::vector<VertBones> vertBones(aiMesh->mNumVertices);
79 std::map<unsigned int, std::vector<std::pair<unsigned int, float>>> boneWeightMap;
81 for (unsigned int i = 0; i < aiMesh->mNumBones; i++) {
82 aiBone *aiBone = aiMesh->mBones[i];
84 boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiMatrixToMat4(aiBone->mOffsetMatrix));
86 for (int j = 0; j < aiBone->mNumWeights; j++) {
87 aiVertexWeight vw = aiBone->mWeights[j];
89 if (!boneWeightMap.count(vw.mVertexId)) boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
90 boneWeightMap[vw.mVertexId].push_back(std::pair(i + 1, vw.mWeight));
94 for (auto pair: boneWeightMap) {
95 unsigned int vertexId = pair.first;
96 for (int i = 0; i < pair.second.size() && i < 4; i++) {
97 unsigned int boneId = pair.second[i].first;
98 float weight = pair.second[i].second;
99 vertBones[vertexId].ids[i] = boneId;
100 vertBones[vertexId].weights[i] = weight;
104 glBindBuffer(GL_ARRAY_BUFFER, boneVbo);
105 glBufferData(GL_ARRAY_BUFFER, sizeof(VertBones) * vertBones.size(), &vertBones[0], GL_STATIC_DRAW);
107 GLuint boneIdLoc = glGetAttribLocation(progId, "boneIds");
108 glEnableVertexAttribArray(boneIdLoc);
109 glVertexAttribIPointer(boneIdLoc, 4, GL_INT, sizeof(VertBones), 0);
111 GLuint boneWeightLoc = glGetAttribLocation(progId, "boneWeights");
112 glEnableVertexAttribArray(boneWeightLoc);
113 glVertexAttribPointer(boneWeightLoc, 4, GL_FLOAT, GL_FALSE, sizeof(VertBones), (const GLvoid *)sizeof(VertBones::ids));
116 Model::Node::Node(const aiNode &node, GLuint progId, AnimMap *am): ai(node), progId(progId), animMap(am) {
117 for (int i = 0; i < node.mNumMeshes; i++) {
118 meshIndices.push_back(node.mMeshes[i]);
120 for (int i = 0; i < node.mNumChildren; i++) {
121 const aiNode *child = node.mChildren[i];
122 children.push_back(new Node(*child, progId, am));
126 glm::mat4 lerpPosition(const aiNodeAnim *anim, const float tick) {
127 if (anim->mNumPositionKeys == 0) return glm::mat4(1.f);
130 for (int i = 0; i < anim->mNumPositionKeys; i++) {
131 aiVectorKey vk = anim->mPositionKeys[i];
132 if (vk.mTime > tick) {
139 lerpPos = anim->mPositionKeys[0].mValue;
140 } else if (yIndex == -1) {
141 lerpPos = anim->mPositionKeys[anim->mNumPositionKeys - 1].mValue;
143 auto X = anim->mPositionKeys[yIndex - 1];
144 auto Y = anim->mPositionKeys[yIndex];
146 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
149 aiMatrix4x4::Translation(lerpPos, result);
150 return aiMatrixToMat4(result);
153 glm::mat4 lerpRotation(const aiNodeAnim *anim, const float tick) {
155 for (int i = 0; i < anim->mNumRotationKeys; i++) {
156 aiQuatKey vk = anim->mRotationKeys[i];
157 if (vk.mTime > tick) {
165 result = anim->mRotationKeys[0].mValue;
166 } else if (yIndex == -1) {
167 result = anim->mRotationKeys[anim->mNumRotationKeys - 1].mValue;
170 auto X = anim->mRotationKeys[yIndex - 1];
171 auto Y = anim->mRotationKeys[yIndex];
173 float mix = (tick - X.mTime) / (Y.mTime - X.mTime);
175 aiQuaternion::Interpolate(result, X.mValue, Y.mValue, mix);
178 return aiMatrixToMat4(aiMatrix4x4(result.GetMatrix()));
181 glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) {
183 for (int i = 0; i < anim->mNumScalingKeys; i++) {
184 aiVectorKey vk = anim->mScalingKeys[i];
185 if (vk.mTime > tick) {
193 lerpPos = anim->mScalingKeys[0].mValue;
195 auto X = anim->mScalingKeys[yIndex - 1];
196 auto Y = anim->mScalingKeys[yIndex];
198 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
201 aiMatrix4x4::Scaling(lerpPos, result);
202 return aiMatrixToMat4(result);
205 void Model::Node::draw( const std::vector<Mesh> &meshes,
206 const std::vector<Material> &materials,
209 glm::mat4 parentTrans = glm::mat4(1),
210 BoneTransforms boneTransforms = BoneTransforms()) const {
212 GLuint modelLoc = glGetUniformLocation(progId, "model");
214 glm::mat4 animTrans(1.f);
215 if (animMap->count(std::string(ai.mName.C_Str()))) {
216 for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) {
217 float t = fmod(tick, anim.duration);
218 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
219 animTrans *= lerpPosition(nodeAnim, t);
220 animTrans *= lerpRotation(nodeAnim, t);
221 animTrans *= lerpScaling(nodeAnim, t);
227 glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation);
229 /* for (auto child: children) { */
230 /* boneTransforms[std::string(ai.mName.C_Str())] = m; */
233 for (unsigned int i: meshIndices) {
234 const Mesh &mesh = meshes[i];
235 glBindVertexArray(mesh.vao);
238 std::vector<glm::mat4> idBones(17, glm::mat4(1.f));
239 glUniformMatrix4fv(glGetUniformLocation(progId, "bones"), 17, GL_FALSE, glm::value_ptr(idBones[0]));
241 for (std::pair<std::string, std::pair<unsigned int, glm::mat4>> pair: mesh.boneMap) {
243 std::string nodeName = pair.first;
244 unsigned int boneId = pair.second.first;
245 // This is actually an inverse-bind matrix
246 // i.e. position of the mesh in bone space
247 // so no need to inverse again!
248 // https://github.com/assimp/assimp/pull/1803/files
249 glm::mat4 boneOffset = pair.second.second;
251 glm::mat4 boneTrans(1.f);
252 /* if (boneTransforms.count(nodeName)) { */
253 /* std::cerr << "got bone transform from map" << std::endl; */
254 /* boneTrans = boneTransforms[nodeName]; */
256 for (const Animation anim: animMap->at(nodeName)) {
257 float t = fmod(tick, anim.duration);
258 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
259 boneTrans = boneTrans * lerpPosition(nodeAnim, t);
260 boneTrans = boneTrans * lerpRotation(nodeAnim, t);
261 boneTrans = boneTrans * lerpScaling(nodeAnim, t);
265 boneTrans = boneTrans * boneOffset;
268 std::string boneLocStr = "bones[" + std::to_string(boneId) + "]";
269 GLuint boneLoc = glGetUniformLocation(progId, boneLocStr.c_str());
270 glUniformMatrix4fv(boneLoc, 1, GL_FALSE, glm::value_ptr(boneTrans));
273 Material material = materials[mesh.materialIndex];
276 glUniform1i(glGetUniformLocation(progId, "irradianceMap"), 4);
277 glActiveTexture(GL_TEXTURE4);
278 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getIrradianceMap());
280 glUniform1i(glGetUniformLocation(progId, "prefilterMap"), 5);
281 glActiveTexture(GL_TEXTURE5);
282 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getPrefilterMap());
284 glUniform1i(glGetUniformLocation(progId, "brdfMap"), 6);
285 glActiveTexture(GL_TEXTURE6);
286 glBindTexture(GL_TEXTURE_2D, skybox.getBRDFMap());
288 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(m));
290 glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
292 for (Node *child: children) child->draw(meshes, materials, skybox, tick, m, boneTransforms);
295 Model::Model(const aiScene *scene, Program p): program(p) {
296 glUseProgram(p.progId);
298 for (int i = 0; i < scene->mNumMeshes; i++) {
299 const aiMesh *mesh = scene->mMeshes[i];
300 meshes.push_back(Mesh(mesh, p.progId));
303 // TODO: handle default material inserted at the end by assimp
304 for (unsigned int i = 0; i < scene->mNumMaterials - 1; i++) {
305 const aiMaterial &material = *scene->mMaterials[i];
306 materials.push_back(Material(material, *scene, p.progId));
309 AnimMap *animMap = new AnimMap();
310 for (int i = 0; i < scene->mNumAnimations; i++) {
311 const aiAnimation *aiAnim = scene->mAnimations[i];
313 std::map<std::string, std::vector<const aiNodeAnim*>> nodeAnims;
315 for (int j = 0; j < aiAnim->mNumChannels; j++) {
316 const aiNodeAnim *nodeAnim = aiAnim->mChannels[j];
317 std::string nodeName = std::string(nodeAnim->mNodeName.C_Str());
319 if (!nodeAnims.count(nodeName)) nodeAnims[nodeName] = std::vector<const aiNodeAnim*>();
321 nodeAnims[nodeName].push_back(nodeAnim);
324 for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
325 std::string nodeName = pair.first;
327 if (!animMap->count(nodeName)) (*animMap)[nodeName] = std::vector<const Animation>();
328 (*animMap)[nodeName].push_back({ aiAnim->mDuration, pair.second });
332 root = new Node(*(scene->mRootNode), p.progId, animMap);
335 /* void Model::calcBoneTransforms(aiNode &node, glm::mat4 parentTrans = glm::mat4(1), BoneTransforms boneTrans = BoneTransforms()) { */
336 /* glm::mat4 animTrans(1.f); */
337 /* if (animMap->count(std::string(ai.mName.C_Str()))) { */
338 /* for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) { */
339 /* float t = fmod(tick, anim.duration); */
340 /* for (const aiNodeAnim *nodeAnim: anim.nodeAnims) { */
341 /* animTrans *= lerpPosition(nodeAnim, t); */
342 /* animTrans *= lerpRotation(nodeAnim, t); */
343 /* animTrans *= lerpScaling(nodeAnim, t); */
349 /* glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model; */
352 void Model::draw(Skybox skybox, const float tick) const {
353 glUseProgram(program.progId);
357 root->draw(meshes, materials, skybox, tick);
360 Model::Node* Model::find(const std::string &name) {
361 return find(aiString(name));
364 Model::Node* Model::find(const aiString name) {
365 const aiNode *node = root->ai.FindNode(name);
366 Model::Node* res = root->findNode(*node);
370 Model::Node* Model::Node::findNode(const aiNode &aiNode) {
371 if (&ai == &aiNode) return this;
372 for (Model::Node *child: children) {
373 Model::Node *res = child->findNode(aiNode);