Load cameras and shuffle about model stuff
[opengl.git] / model.cpp
1 #include "model.hpp"
2 #include <iostream>
3 #include <assimp/quaternion.h>
4 #include <glm/gtc/type_ptr.hpp>
5
6
7 Model::Mesh::Mesh(const aiMesh *aiMesh, GLuint progId) {
8
9         std::vector<glm::vec3> vertices, normals, tangents, bitangents;
10         std::vector<glm::vec2> texCoords;
11
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));
16                 }
17                 if (aiMesh->HasNormals()) {
18                         aiVector3D v = aiMesh->mNormals[i];
19                         normals.push_back(glm::vec3(v.x, v.y, v.z));
20                 } else {
21                         std::cerr << "Missing normals" << std::endl;
22                         exit(1);
23                 }
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));
28                 } else {
29                         texCoords.push_back(glm::vec2(0));
30                 }
31                 materialIndex = aiMesh->mMaterialIndex;
32         }
33
34         std::vector<GLuint> indices;
35
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]);
42                 }
43         } 
44         
45         numIndices = indices.size();
46         
47         glGenVertexArrays(1, &vao);
48         glBindVertexArray(vao);
49         
50         GLuint vbos[6];
51         glGenBuffers(6, vbos);
52         GLuint vertexVbo = vbos[0], normalVbo = vbos[1], texCoordVbo = vbos[2], indicesVbo = vbos[3];
53         GLuint boneVbo = vbos[4];
54         
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);
60         
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);
66
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);
72
73         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVbo);
74         glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
75
76         // bones
77         std::vector<VertBones> vertBones(aiMesh->mNumVertices);
78
79         std::map<unsigned int, std::vector<std::pair<unsigned int, float>>> boneWeightMap;
80
81         for (unsigned int i = 0; i < aiMesh->mNumBones; i++) {
82                 aiBone *aiBone = aiMesh->mBones[i];
83
84                 boneMap[std::string(aiBone->mName.C_Str())] = std::pair(i + 1, aiMatrixToMat4(aiBone->mOffsetMatrix));
85
86                 for (int j = 0; j < aiBone->mNumWeights; j++) {
87                         aiVertexWeight vw = aiBone->mWeights[j];
88
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));
91                 }
92         }
93
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;
101                 }
102         }
103         
104         glBindBuffer(GL_ARRAY_BUFFER, boneVbo);
105         glBufferData(GL_ARRAY_BUFFER, sizeof(VertBones) * vertBones.size(), &vertBones[0], GL_STATIC_DRAW);
106
107         GLuint boneIdLoc = glGetAttribLocation(progId, "boneIds");
108         glEnableVertexAttribArray(boneIdLoc);
109         glVertexAttribIPointer(boneIdLoc, 4, GL_INT, sizeof(VertBones), 0);
110
111         GLuint boneWeightLoc = glGetAttribLocation(progId, "boneWeights");
112         glEnableVertexAttribArray(boneWeightLoc);
113         glVertexAttribPointer(boneWeightLoc, 4, GL_FLOAT, GL_FALSE, sizeof(VertBones), (const GLvoid *)sizeof(VertBones::ids));
114 }
115
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]);
119         }
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));
123         }
124 }
125
126 glm::mat4 lerpPosition(const aiNodeAnim *anim, const float tick) {
127         if (anim->mNumPositionKeys == 0) return glm::mat4(1.f);
128
129         int yIndex = -1;
130         for (int i = 0; i < anim->mNumPositionKeys; i++) {
131                 aiVectorKey vk = anim->mPositionKeys[i];
132                 if (vk.mTime > tick) {
133                         yIndex = i;
134                         break;
135                 }
136         }
137         aiVector3D lerpPos;
138         if (yIndex == 0) {
139                 lerpPos = anim->mPositionKeys[0].mValue;
140         } else if (yIndex == -1) {
141                 lerpPos = anim->mPositionKeys[anim->mNumPositionKeys - 1].mValue;
142         } else {
143                 auto X = anim->mPositionKeys[yIndex - 1];
144                 auto Y = anim->mPositionKeys[yIndex];
145
146                 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
147         }
148         aiMatrix4x4 result;
149         aiMatrix4x4::Translation(lerpPos, result);
150         return aiMatrixToMat4(result);
151 }
152
153 glm::mat4 lerpRotation(const aiNodeAnim *anim, const float tick) {
154         int yIndex = -1;
155         for (int i = 0; i < anim->mNumRotationKeys; i++) {
156                 aiQuatKey vk = anim->mRotationKeys[i];
157                 if (vk.mTime > tick) {
158                         yIndex = i;
159                         break;
160                 }
161         }
162
163         aiQuaternion result;
164         if (yIndex < 1) {
165                 result = anim->mRotationKeys[0].mValue;
166         } else if (yIndex == -1) {
167                 result = anim->mRotationKeys[anim->mNumRotationKeys - 1].mValue;
168         } else {
169
170                 auto X = anim->mRotationKeys[yIndex - 1];
171                 auto Y = anim->mRotationKeys[yIndex];
172
173                 float mix = (tick - X.mTime) / (Y.mTime - X.mTime);
174
175                 aiQuaternion::Interpolate(result, X.mValue, Y.mValue, mix);
176
177         }
178         return aiMatrixToMat4(aiMatrix4x4(result.GetMatrix()));
179 }
180
181 glm::mat4 lerpScaling(const aiNodeAnim *anim, const float tick) {
182         int yIndex = -1;
183         for (int i = 0; i < anim->mNumScalingKeys; i++) {
184                 aiVectorKey vk = anim->mScalingKeys[i];
185                 if (vk.mTime > tick) {
186                         yIndex = i;
187                         break;
188                 }
189         }
190
191         aiVector3D lerpPos;
192         if (yIndex < 1) {
193                 lerpPos = anim->mScalingKeys[0].mValue;
194         } else {
195                 auto X = anim->mScalingKeys[yIndex - 1];
196                 auto Y = anim->mScalingKeys[yIndex];
197
198                 lerpPos = (X.mValue * (float)(Y.mTime - tick) + Y.mValue * (float)(tick - X.mTime)) / (float)(Y.mTime - X.mTime);
199         }
200         aiMatrix4x4 result;
201         aiMatrix4x4::Scaling(lerpPos, result);
202         return aiMatrixToMat4(result);
203 }
204
205 void Model::Node::draw( const std::vector<Mesh> &meshes,
206                                                 const std::vector<Material> &materials,
207                                                 const Skybox skybox,
208                                                 const float tick,
209                                                 glm::mat4 parentTrans = glm::mat4(1),
210                                                 BoneTransforms boneTransforms = BoneTransforms()) const {
211
212         GLuint modelLoc = glGetUniformLocation(progId, "model");
213
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);
222                         }
223                 }
224         }
225         
226
227         glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation);
228
229         /* for (auto child: children) { */
230         /*      boneTransforms[std::string(ai.mName.C_Str())] = m; */
231         /* } */
232         
233         for (unsigned int i: meshIndices) {
234                 const Mesh &mesh = meshes[i];
235                 glBindVertexArray(mesh.vao);
236
237                 // bones
238                 std::vector<glm::mat4> idBones(17, glm::mat4(1.f));
239                 glUniformMatrix4fv(glGetUniformLocation(progId, "bones"), 17, GL_FALSE, glm::value_ptr(idBones[0]));
240
241                 for (std::pair<std::string, std::pair<unsigned int, glm::mat4>> pair: mesh.boneMap) {
242
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;
250
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]; */
255                         /* } */
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);
262                                 }
263                         }
264
265                         boneTrans = boneTrans * boneOffset;
266
267
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));
271                 }
272
273                 Material material = materials[mesh.materialIndex];
274                 material.bind();
275
276                 glUniform1i(glGetUniformLocation(progId, "irradianceMap"), 4);
277                 glActiveTexture(GL_TEXTURE4);
278                 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getIrradianceMap());
279
280                 glUniform1i(glGetUniformLocation(progId, "prefilterMap"), 5);
281                 glActiveTexture(GL_TEXTURE5);
282                 glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getPrefilterMap());
283
284                 glUniform1i(glGetUniformLocation(progId, "brdfMap"), 6);
285                 glActiveTexture(GL_TEXTURE6);
286                 glBindTexture(GL_TEXTURE_2D, skybox.getBRDFMap());
287                 
288                 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(m));
289
290                 glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
291         }
292         for (Node *child: children) child->draw(meshes, materials, skybox, tick, m, boneTransforms);
293 }
294
295 Model::Model(const aiScene *scene, Program p): program(p) {
296         glUseProgram(p.progId);
297
298         for (int i = 0; i < scene->mNumMeshes; i++) {
299                 const aiMesh *mesh = scene->mMeshes[i];
300                 meshes.push_back(Mesh(mesh, p.progId));
301         }
302
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));
307         }
308
309         AnimMap *animMap = new AnimMap();
310         for (int i = 0; i < scene->mNumAnimations; i++) {
311                 const aiAnimation *aiAnim = scene->mAnimations[i];
312
313                 std::map<std::string, std::vector<const aiNodeAnim*>> nodeAnims;
314
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());
318                         
319                         if (!nodeAnims.count(nodeName)) nodeAnims[nodeName] = std::vector<const aiNodeAnim*>();
320
321                         nodeAnims[nodeName].push_back(nodeAnim);
322                 }
323
324                 for (std::pair<std::string, std::vector<const aiNodeAnim*>> pair: nodeAnims) {
325                         std::string nodeName = pair.first;
326
327                         if (!animMap->count(nodeName)) (*animMap)[nodeName] = std::vector<const Animation>();
328                         (*animMap)[nodeName].push_back({ aiAnim->mDuration, pair.second });
329                 }
330         }
331
332         root = new Node(*(scene->mRootNode), p.progId, animMap);
333 }
334
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); */
344 /*                      } */
345 /*              } */
346 /*      } */
347         
348
349 /*      glm::mat4 m = parentTrans * animTrans * aiMatrixToMat4(ai.mTransformation) * model; */
350 /* } */
351
352 void Model::draw(Skybox skybox, const float tick) const {
353         glUseProgram(program.progId);
354
355         
356
357         root->draw(meshes, materials, skybox, tick);
358 }
359
360 Model::Node* Model::find(const std::string &name) {
361         return find(aiString(name));
362 }
363
364 Model::Node* Model::find(const aiString name) {
365         const aiNode *node = root->ai.FindNode(name);
366         Model::Node* res = root->findNode(*node);
367         return res;
368 }
369
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);
374                 if (res) return res;
375         }
376         return nullptr;
377 }