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;
245 if (animMap->count(nodeName) <= 0) break;
247 unsigned int boneId = pair.second.first;
248 // This is actually an inverse-bind matrix
249 // i.e. position of the mesh in bone space
250 // so no need to inverse again!
251 // https://github.com/assimp/assimp/pull/1803/files
252 glm::mat4 boneOffset = pair.second.second;
254 glm::mat4 boneTrans(1.f);
255 /* if (boneTransforms.count(nodeName)) { */
256 /* std::cerr << "got bone transform from map" << std::endl; */
257 /* boneTrans = boneTransforms[nodeName]; */
259 for (const Animation anim: animMap->at(nodeName)) {
260 float t = fmod(tick, anim.duration);
261 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
262 boneTrans = boneTrans * lerpPosition(nodeAnim, t);
263 boneTrans = boneTrans * lerpRotation(nodeAnim, t);
264 boneTrans = boneTrans * lerpScaling(nodeAnim, t);
268 boneTrans = boneTrans * boneOffset;
271 std::string boneLocStr = "bones[" + std::to_string(boneId) + "]";
272 GLuint boneLoc = glGetUniformLocation(progId, boneLocStr.c_str());
273 glUniformMatrix4fv(boneLoc, 1, GL_FALSE, glm::value_ptr(boneTrans));
276 Material material = materials[mesh.materialIndex];
279 glUniform1i(glGetUniformLocation(progId, "irradianceMap"), 4);
280 glActiveTexture(GL_TEXTURE4);
281 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getIrradianceMap());
283 glUniform1i(glGetUniformLocation(progId, "prefilterMap"), 5);
284 glActiveTexture(GL_TEXTURE5);
285 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getPrefilterMap());
287 glUniform1i(glGetUniformLocation(progId, "brdfMap"), 6);
288 glActiveTexture(GL_TEXTURE6);
289 glBindTexture(GL_TEXTURE_2D, skybox.getBRDFMap());
291 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(m));
293 glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
295 for (Node *child: children) child->draw(meshes, materials, skybox, tick, m, boneTransforms);
298 Model::Model(const aiScene *scene, Program p): program(p) {
299 glUseProgram(p.progId);
301 for (int i = 0; i < scene->mNumMeshes; i++) {
302 const aiMesh *mesh = scene->mMeshes[i];
303 meshes.push_back(Mesh(mesh, p.progId));
306 // TODO: handle default material inserted at the end by assimp
307 for (unsigned int i = 0; i < scene->mNumMaterials; i++) {
308 const aiMaterial &material = *scene->mMaterials[i];
309 materials.push_back(Material(material, *scene, p.progId));
312 AnimMap *animMap = new AnimMap();
313 for (int i = 0; i < scene->mNumAnimations; i++) {
314 const aiAnimation *aiAnim = scene->mAnimations[i];
316 std::map<std::string, std::vector<const aiNodeAnim*>> nodeAnims;
318 for (int j = 0; j < aiAnim->mNumChannels; j++) {
319 const aiNodeAnim *nodeAnim = aiAnim->mChannels[j];
320 std::string nodeName = std::string(nodeAnim->mNodeName.C_Str());
322 if (!nodeAnims.count(nodeName)) nodeAnims[nodeName] = std::vector<const aiNodeAnim*>();
324 nodeAnims[nodeName].push_back(nodeAnim);
327 for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
328 std::string nodeName = pair.first;
330 if (!animMap->count(nodeName)) (*animMap)[nodeName] = std::vector<const Animation>();
331 (*animMap)[nodeName].push_back({ aiAnim->mDuration, pair.second });
335 root = new Node(*(scene->mRootNode), p.progId, animMap);
338 /* void Model::calcBoneTransforms(aiNode &node, glm::mat4 parentTrans = glm::mat4(1), BoneTransforms boneTrans = BoneTransforms()) { */
339 /* glm::mat4 animTrans(1.f); */
340 /* if (animMap->count(std::string(ai.mName.C_Str()))) { */
341 /* for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) { */
342 /* float t = fmod(tick, anim.duration); */
343 /* for (const aiNodeAnim *nodeAnim: anim.nodeAnims) { */
344 /* animTrans *= lerpPosition(nodeAnim, t); */
345 /* animTrans *= lerpRotation(nodeAnim, t); */
346 /* animTrans *= lerpScaling(nodeAnim, t); */
352 /* glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model; */
355 void Model::draw(Skybox skybox, const float tick) const {
356 glUseProgram(program.progId);
360 root->draw(meshes, materials, skybox, tick);
363 Model::Node* Model::find(const std::string &name) {
364 return find(aiString(name));
367 Model::Node* Model::find(const aiString name) {
368 const aiNode *node = root->ai.FindNode(name);
369 Model::Node* res = root->findNode(*node);
373 Model::Node* Model::Node::findNode(const aiNode &aiNode) {
374 if (&ai == &aiNode) return this;
375 for (Model::Node *child: children) {
376 Model::Node *res = child->findNode(aiNode);