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