107fda0b321317ab54a145d7e1249c08f340abde
[opengl.git] / model.cpp
1 #include "model.hpp"
2 #include <iostream>
3 #include <assimp/postprocess.h>
4 #include <assimp/quaternion.h>
5 #include <glm/gtc/type_ptr.hpp>
6
7 glm::mat4 aiMatrixToMat4(aiMatrix4x4 from) {
8         glm::mat4 to;
9         for (int i = 0; i < 4; i++)
10                 for (int j = 0; j < 4; j++)
11                         to[i][j] = from[j][i];
12         return to;
13 }
14
15 Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
16
17         std::vector<glm::vec3> vertices, normals, tangents, bitangents;
18         std::vector<glm::vec2> texCoords;
19
20         for (int i = 0; i < aiMesh->mNumVertices; i++) {
21                 if (aiMesh->HasPositions()) {
22                         aiVector3D v = aiMesh->mVertices[i];
23                         vertices.push_back(glm::vec3(v.x, v.y, v.z));
24                 }
25                 if (aiMesh->HasNormals()) {
26                         aiVector3D v = aiMesh->mNormals[i];
27                         normals.push_back(glm::vec3(v.x, v.y, v.z));
28                 } else {
29                         std::cerr << "Missing normals" << std::endl;
30                         exit(1);
31                 }
32                 // check for texture coord set 0
33                 if (aiMesh->HasTextureCoords(0)) {
34                         const aiVector3D v = aiMesh->mTextureCoords[0][i];
35                         texCoords.push_back(glm::vec2(v.x, v.y));
36                 } else {
37                         texCoords.push_back(glm::vec2(0));
38                 }
39                 materialIndex = aiMesh->mMaterialIndex;
40         }
41
42         std::vector<GLuint> indices;
43
44         for (int i = 0; i < aiMesh->mNumFaces; i++) {
45                 const aiFace &face = aiMesh->mFaces[i];
46                 if(face.mNumIndices == 3) {
47                         indices.push_back(face.mIndices[0]);
48                         indices.push_back(face.mIndices[1]);
49                         indices.push_back(face.mIndices[2]);
50                 }
51         } 
52         
53         numIndices = indices.size();
54         
55         glGenVertexArrays(1, &vao);
56         glBindVertexArray(vao);
57         
58         GLuint vbos[6];
59         glGenBuffers(6, vbos);
60         GLuint vertexVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3];
61         GLuint boneVbo = vbos[4];
62         
63         GLuint posLoc = glGetAttribLocation(progId, "pos");
64         glBindBuffer(GL_ARRAY_BUFFER, vertexVbo);
65         glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
66         glEnableVertexAttribArray(posLoc);
67         glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
68         
69         GLuint normalLoc = glGetAttribLocation(progId, "unscaledNormal");
70         glBindBuffer(GL_ARRAY_BUFFER, normalVbo);
71         glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
72         glEnableVertexAttribArray(normalLoc);
73         glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
74
75         GLuint texCoordLoc = glGetAttribLocation(progId, "vTexCoord");
76         glBindBuffer(GL_ARRAY_BUFFER, texCoordVbo);
77         glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(glm::vec2), &texCoords[0], GL_STATIC_DRAW);
78         glEnableVertexAttribArray(texCoordLoc);
79         glVertexAttribPointer(texCoordLoc, 2, GL_FLOAT, GL_FALSE, 0, 0);
80
81         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVbo);
82         glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
83
84         // bones
85         std::vector<VertBones> vertBones(aiMesh->mNumVertices);
86
87         std::map<unsigned int, std::vector<std::pair<unsigned int, float>>> boneWeightMap;
88
89         for (unsigned int i = 0; i < aiMesh->mNumBones; i++) {
90                 aiBone *aiBone = aiMesh->mBones[i];
91
92                 boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiMatrixToMat4(aiBone->mOffsetMatrix));
93
94                 for (int j = 0; j < aiBone->mNumWeights; j++) {
95                         aiVertexWeight vw = aiBone->mWeights[j];
96
97                         if (!boneWeightMap.count(vw.mVertexId)) boneWeightMap[vw.mVertexId] = std::vector<std::pair<unsigned int, float>>();
98                         boneWeightMap[vw.mVertexId].push_back(std::pair(i + 1, vw.mWeight));
99                 }
100         }
101
102         for (auto pair: boneWeightMap) {
103                 unsigned int vertexId = pair.first;
104                 for (int i = 0; i < pair.second.size() && i < 4; i++) {
105                         unsigned int boneId = pair.second[i].first;
106                         float weight = pair.second[i].second;
107                         vertBones[vertexId].ids[i] = boneId;
108                         vertBones[vertexId].weights[i] = weight;
109                 }
110         }
111         
112         glBindBuffer(GL_ARRAY_BUFFER, boneVbo);
113         glBufferData(GL_ARRAY_BUFFER, sizeof(VertBones) * vertBones.size(), &vertBones[0], GL_STATIC_DRAW);
114
115         GLuint boneIdLoc = glGetAttribLocation(progId, "boneIds");
116         glEnableVertexAttribArray(boneIdLoc);
117         glVertexAttribIPointer(boneIdLoc, 4, GL_INT, sizeof(VertBones), 0);
118
119         GLuint boneWeightLoc = glGetAttribLocation(progId, "boneWeights");
120         glEnableVertexAttribArray(boneWeightLoc);
121         glVertexAttribPointer(boneWeightLoc, 4, GL_FLOAT, GL_FALSE, sizeof(VertBones), (const GLvoid *)sizeof(VertBones::ids));
122 }
123
124 Model::Node::Node(const aiNode &node, GLuint progId, AnimMap *am): ai(node), progId(progId), animMap(am) {
125         for (int i = 0; i < node.mNumMeshes; i++) {
126                 meshIndices.push_back(node.mMeshes[i]);
127         }
128         for (int i = 0; i < node.mNumChildren; i++) {
129                 const aiNode *child = node.mChildren[i];
130                 children.push_back(new Node(*child, progId, am));
131         }
132 }
133
134 glm::mat4 lerpPosition(const aiNodeAnim *anim, const float tick) {
135         if (anim->mNumPositionKeys == 0) return glm::mat4(1.f);
136
137         int yIndex = -1;
138         for (int i = 0; i < anim->mNumPositionKeys; i++) {
139                 aiVectorKey vk = anim->mPositionKeys[i];
140                 if (vk.mTime > tick) {
141                         yIndex = i;
142                         break;
143                 }
144         }
145         aiVector3D lerpPos;
146         if (yIndex == 0) {
147                 lerpPos = anim->mPositionKeys[0].mValue;
148         } else if (yIndex == -1) {
149                 lerpPos = anim->mPositionKeys[anim->mNumPositionKeys - 1].mValue;
150         } else {
151                 auto X = anim->mPositionKeys[yIndex - 1];
152                 auto Y = anim->mPositionKeys[yIndex];
153
154                 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
155         }
156         aiMatrix4x4 result;
157         aiMatrix4x4::Translation(lerpPos, result);
158         return aiMatrixToMat4(result);
159 }
160
161 glm::mat4 lerpRotation(const aiNodeAnim *anim, const float tick) {
162         int yIndex = -1;
163         for (int i = 0; i < anim->mNumRotationKeys; i++) {
164                 aiQuatKey vk = anim->mRotationKeys[i];
165                 if (vk.mTime > tick) {
166                         yIndex = i;
167                         break;
168                 }
169         }
170
171         aiQuaternion result;
172         if (yIndex < 1) {
173                 result = anim->mRotationKeys[0].mValue;
174         } else if (yIndex == -1) {
175                 result = anim->mRotationKeys[anim->mNumRotationKeys - 1].mValue;
176         } else {
177
178                 auto X = anim->mRotationKeys[yIndex - 1];
179                 auto Y = anim->mRotationKeys[yIndex];
180
181                 float mix = (tick - X.mTime) / (Y.mTime - X.mTime);
182
183                 aiQuaternion::Interpolate(result, X.mValue, Y.mValue, mix);
184
185         }
186         return aiMatrixToMat4(aiMatrix4x4(result.GetMatrix()));
187 }
188
189 glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) {
190         int yIndex = -1;
191         for (int i = 0; i < anim->mNumScalingKeys; i++) {
192                 aiVectorKey vk = anim->mScalingKeys[i];
193                 if (vk.mTime > tick) {
194                         yIndex = i;
195                         break;
196                 }
197         }
198
199         aiVector3D lerpPos;
200         if (yIndex < 1) {
201                 lerpPos = anim->mScalingKeys[0].mValue;
202         } else {
203                 auto X = anim->mScalingKeys[yIndex - 1];
204                 auto Y = anim->mScalingKeys[yIndex];
205
206                 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
207         }
208         aiMatrix4x4 result;
209         aiMatrix4x4::Scaling(lerpPos, result);
210         return aiMatrixToMat4(result);
211 }
212
213 void Model::Node::draw( const std::vector<Mesh> &meshes,
214                                                 const std::vector<Material> &materials,
215                                                 const Skybox skybox,
216                                                 const float tick,
217                                                 glm::mat4 parentTrans = glm::mat4(1),
218                                                 BoneTransforms boneTransforms = BoneTransforms()) const {
219
220         GLuint modelLoc = glGetUniformLocation(progId, "model");
221
222         glm::mat4 animTrans(1.f);
223         if (animMap->count(std::string(ai.mName.C_Str()))) {
224                 for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) {
225                         float t = fmod(tick, anim.duration);
226                         for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
227                                 animTrans *= lerpPosition(nodeAnim, t);
228                                 animTrans *= lerpRotation(nodeAnim, t);
229                                 animTrans *= lerpScaling(nodeAnim, t);
230                         }
231                 }
232         }
233         
234
235         glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model;
236
237         for (auto child: children) {
238                 boneTransforms[std::string(ai.mName.C_Str())] = m;
239         }
240         
241         for (unsigned int i: meshIndices) {
242                 const Mesh &mesh = meshes[i];
243                 glBindVertexArray(mesh.vao);
244
245                 // bones
246                 std::vector<glm::mat4> idBones(17, glm::mat4(1.f));
247                 glUniformMatrix4fv(glGetUniformLocation(progId, "bones"), 17, GL_FALSE, glm::value_ptr(idBones[0]));
248
249                 for (std::pair<std::string, std::pair<unsigned int, glm::mat4>> pair: mesh.boneMap) {
250
251                         std::string nodeName = pair.first;
252                         unsigned int boneId = pair.second.first;
253                         glm::mat4 boneOffset = pair.second.second;
254
255                         glm::mat4 boneTrans(1.f);
256                         if (boneTransforms.count(nodeName)) {
257                                 std::cerr << "got bone transform from map" << std::endl;
258                                 boneTrans = boneTransforms[nodeName];
259                         }
260                         for (const Animation anim: animMap->at(nodeName)) {
261                                 float t = fmod(tick, anim.duration);
262                                 for (const aiNodeAnim *nodeAnim: anim.nodeAnims) {
263                                         boneTrans = boneTrans * lerpPosition(nodeAnim, t);
264                                         boneTrans = boneTrans * lerpRotation(nodeAnim, t);
265                                         boneTrans = boneTrans * lerpScaling(nodeAnim, t);
266                                 }
267                         }
268
269                         boneTrans = boneTrans * glm::inverse(boneOffset);
270
271
272                         std::string boneLocStr = "bones[" + std::to_string(boneId) + "]";
273                         GLuint boneLoc = glGetUniformLocation(progId, boneLocStr.c_str());
274                         glUniformMatrix4fv(boneLoc, 1, GL_FALSE, glm::value_ptr(boneTrans));
275                 }
276
277                 Material material = materials[mesh.materialIndex];
278                 material.bind();
279
280                 glUniform1i(glGetUniformLocation(progId, "irradianceMap"), 4);
281                 glActiveTexture(GL_TEXTURE4);
282                 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getIrradianceMap());
283
284                 glUniform1i(glGetUniformLocation(progId, "prefilterMap"), 5);
285                 glActiveTexture(GL_TEXTURE5);
286                 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getPrefilterMap());
287
288                 glUniform1i(glGetUniformLocation(progId, "brdfMap"), 6);
289                 glActiveTexture(GL_TEXTURE6);
290                 glBindTexture(GL_TEXTURE_2D, skybox.getBRDFMap());
291                 
292                 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(m));
293
294                 glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
295         }
296         for (Node *child: children) child->draw(meshes, materials, skybox, tick, m, boneTransforms);
297 }
298
299 Model::Model(const std::string &path, Program p): program(p) {
300         glUseProgram(p.progId);
301         
302         const aiScene *scene = importer.ReadFile(path, 
303                         aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenNormals | aiProcess_FlipUVs);
304         if (!scene) {
305                 std::cerr << importer.GetErrorString() << std::endl;
306                 exit(1);
307         }
308
309         for (int i = 0; i < scene->mNumMeshes; i++) {
310                 const aiMesh *mesh = scene->mMeshes[i];
311                 meshes.push_back(Mesh(mesh, p.progId));
312         }
313
314         // TODO: handle default material inserted at the end by assimp
315         for (unsigned int i = 0; i < scene->mNumMaterials - 1; i++) {
316                 const aiMaterial &material = *scene->mMaterials[i];
317                 materials.push_back(Material(material, *scene, p.progId));
318         }
319
320         AnimMap *animMap = new AnimMap();
321         for (int i = 0; i < scene->mNumAnimations; i++) {
322                 const aiAnimation *aiAnim = scene->mAnimations[i];
323
324                 std::map<std::string, std::vector<const aiNodeAnim*>> nodeAnims;
325
326                 for (int j = 0; j < aiAnim->mNumChannels; j++) {
327                         const aiNodeAnim *nodeAnim = aiAnim->mChannels[j];
328                         std::string nodeName = std::string(nodeAnim->mNodeName.C_Str());
329                         
330                         if (!nodeAnims.count(nodeName)) nodeAnims[nodeName] = std::vector<const aiNodeAnim*>();
331
332                         nodeAnims[nodeName].push_back(nodeAnim);
333                 }
334
335                 for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
336                         std::string nodeName = pair.first;
337
338                         if (!animMap->count(nodeName)) (*animMap)[nodeName] = std::vector<const Animation>();
339                         (*animMap)[nodeName].push_back({ aiAnim->mDuration, pair.second });
340                 }
341         }
342
343         root = new Node(*(scene->mRootNode), p.progId, animMap);
344 }
345
346 /* void Model::calcBoneTransforms(aiNode &node, glm::mat4 parentTrans = glm::mat4(1), BoneTransforms boneTrans = BoneTransforms()) { */
347 /*      glm::mat4 animTrans(1.f); */
348 /*      if (animMap->count(std::string(ai.mName.C_Str()))) { */
349 /*              for (const Animation anim: animMap->at(std::string(ai.mName.C_Str()))) { */
350 /*                      float t = fmod(tick, anim.duration); */
351 /*                      for (const aiNodeAnim *nodeAnim: anim.nodeAnims) { */
352 /*                              animTrans *= lerpPosition(nodeAnim, t); */
353 /*                              animTrans *= lerpRotation(nodeAnim, t); */
354 /*                              animTrans *= lerpScaling(nodeAnim, t); */
355 /*                      } */
356 /*              } */
357 /*      } */
358         
359
360 /*      glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model; */
361 /* } */
362
363 void Model::draw(Skybox skybox, const float tick) const {
364         glUseProgram(program.progId);
365
366         
367
368         root->draw(meshes, materials, skybox, tick);
369 }
370
371 Model::Node* Model::find(const std::string &name) {
372         return find(aiString(name));
373 }
374
375 Model::Node* Model::find(const aiString name) {
376         const aiNode *node = root->ai.FindNode(name);
377         Model::Node* res = root->findNode(*node);
378         return res;
379 }
380
381 Model::Node* Model::Node::findNode(const aiNode &aiNode) {
382         if (&ai == &aiNode) return this;
383         for (Model::Node *child: children) {
384                 Model::Node *res = child->findNode(aiNode);
385                 if (res) return res;
386         }
387         return nullptr;
388 }