-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmodel.cpp
More file actions
569 lines (487 loc) · 25.3 KB
/
Copy pathmodel.cpp
File metadata and controls
569 lines (487 loc) · 25.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
#include "model.hpp"
#include <assimp/GltfMaterial.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <algorithm>
#include <asset-loader.hpp>
#include <assimp/Importer.hpp>
#include <iostream>
#include <unordered_map>
#include "ai-glm-utils.hpp"
#include "asset-loader.hpp"
#include "texture/texture-utils.hpp"
namespace our {
int Model::getAssetsCount(const std::string& path, bool countAnimations) {
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(
path, aiProcess_Triangulate | aiProcess_CalcTangentSpace | aiProcess_GenSmoothNormals |
aiProcess_JoinIdenticalVertices | aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph |
aiProcess_ImproveCacheLocality | aiProcess_LimitBoneWeights | aiProcess_PopulateArmatureData |
aiProcess_GlobalScale | aiProcess_GenUVCoords | aiProcess_TransformUVCoords |
aiProcess_SortByPType);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
std::cerr << "ERROR::ASSIMP::" << importer.GetErrorString() << std::endl;
return 0;
}
int count = 2; // for the combined mesh and model itself
if (scene->HasAnimations() && countAnimations) {
count += scene->mNumAnimations;
}
count += scene->mNumMeshes;
count += scene->mNumMaterials * 2; // each material have a sampler too
return count;
}
void Model::loadFromFile(const std::string& path, const std::unordered_set<std::string>& animationNames) {
std::cout << "Loading model from file: " << path << std::endl;
Assimp::Importer importer;
const aiScene* scene =
importer.ReadFile(path,
// Geometry
aiProcess_Triangulate | // convert quads/polygons to triangles
aiProcess_CalcTangentSpace | // needed for normal mapping
aiProcess_GenSmoothNormals | // better than GenNormals, uses smoothing angles
// Optimization
aiProcess_JoinIdenticalVertices | // combine vertices that are identical in position,
// normal, tex coords, and color
aiProcess_OptimizeMeshes | // reduce draw calls
aiProcess_OptimizeGraph | // optimize node hierarchy
aiProcess_ImproveCacheLocality | // better GPU cache usage
// Skeletal
aiProcess_LimitBoneWeights | // limit to 4 weights per vertex (GPU standard)
aiProcess_PopulateArmatureData | // fills aiBone with proper armature/node data
aiProcess_GlobalScale | // fixes scale differences between formats (FBX vs GLTF)
// Correctness
aiProcess_GenUVCoords | aiProcess_TransformUVCoords | // convert to proper UV range
aiProcess_SortByPType);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
std::cerr << "ERROR::ASSIMP::" << importer.GetErrorString() << std::endl;
return;
}
this->modelDirectory = path.substr(0, path.find_last_of('/'));
glm::mat4 identity(1.0f);
loadMaterialsFromScene(scene);
if (scene->HasAnimations()) {
skeleton = new Skeleton();
skeleton->setGlobalInverseTransform(glm::inverse(aiToGlm(scene->mRootNode->mTransformation)));
loadAnimationsFromScene(scene, animationNames);
processNode(scene->mRootNode, scene, identity, &skeleton->getNodes());
} else {
processNode(scene->mRootNode, scene, identity, nullptr);
}
generateCombinedMesh();
}
void Model::processNode(aiNode* node, const aiScene* scene, glm::mat4& parentTransform,
std::vector<SkeletonNode>* skeletonNodes, int parentIndex) {
// process all the node's meshes (if any)
aiMatrix4x4 t = node->mTransformation;
glm::mat4 nodeTransform = aiToGlm(t);
glm::mat4 globalTransform = parentTransform * nodeTransform;
int currentIndex = -1;
if (skeletonNodes) {
currentIndex = static_cast<int>(skeletonNodes->size());
SkeletonNode skeletonNode;
skeletonNode.name = node->mName.C_Str();
skeletonNode.localTransform = nodeTransform;
skeletonNode.parentIndex = parentIndex;
skeletonNodes->push_back(skeletonNode);
}
for (unsigned int i = 0; i < node->mNumMeshes; i++) {
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
MeshRendererComponent* submesh = processMesh(mesh, scene);
submesh->transform = globalTransform;
// this is a fix for model that is exported for directX where the coordinate system is left-handed, we can
// detect that by checking if the transform has a negative scale (which is equivalent to a negative
// determinant) and if so we flip the winding order of the triangles by applying a negative scale on the X
// axis and also update the face culling mode to front face = CW instead of CCW
if (glm::determinant(globalTransform) < 0.0f) {
submesh->material->pipelineState.faceCulling.frontFace = GL_CW;
submesh->transform = globalTransform * glm::scale(glm::mat4(1.0f), glm::vec3(-1.0f, 1.0f, 1.0f));
}
submesh->nodeName = node->mName.C_Str();
submeshes.push_back(submesh);
AssetLoaderStats::loadingCount++; // count the mesh as an asset for loading progress purposes
}
for (unsigned int i = 0; i < node->mNumChildren; i++) {
processNode(node->mChildren[i], scene, globalTransform, skeletonNodes, currentIndex);
}
}
MeshRendererComponent* Model::processMesh(aiMesh* mesh, const aiScene* scene) {
std::vector<Vertex> vertices(mesh->mNumVertices);
std::vector<unsigned int> indices;
// process vertices
for (unsigned int i = 0; i < mesh->mNumVertices; ++i) {
Vertex v;
v.position = aiToGlm(mesh->mVertices[i]);
if (mesh->mNormals) v.normal = aiToGlm(mesh->mNormals[i]);
auto uv = mesh->mTextureCoords[0] ? &mesh->mTextureCoords[0][i] : nullptr;
if (uv) v.tex_coord = aiToGlm(*uv);
aiColor4D* vertexColor = mesh->mColors[0] ? &mesh->mColors[0][i] : nullptr;
if (vertexColor)
v.color = our::Color(vertexColor->r, vertexColor->g, vertexColor->b, vertexColor->a);
else
v.color = our::Color(255, 255, 255, 255);
// Tangents and bitangents are needed for normal mapping, but not all models have them. If they don't
// exist we will set them to zero and the shader will handle it as if the surface is flat (facing up)
if (mesh->mTangents && mesh->mBitangents) {
glm::vec3 T = aiToGlm(mesh->mTangents[i]);
glm::vec3 B = aiToGlm(mesh->mBitangents[i]);
glm::vec3 N = aiToGlm(mesh->mNormals[i]);
// Determine handedness sign
float sign = (glm::dot(glm::cross(N, T), B) < 0.0f) ? -1.0f : 1.0f;
v.tangent = glm::vec4(T, sign);
} else {
v.tangent = glm::vec4(0.0f);
}
// bone data
for (int j = 0; j < MAX_BONE_INFLUENCE; ++j) {
v.bone_ids[j] = -1;
v.weights[j] = 0.0f;
}
vertices[i] = v;
}
if (mesh->HasBones()) processVertexBoneData(vertices, mesh);
// process indices
for (unsigned int i = 0; i < mesh->mNumFaces; ++i) {
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; ++j) indices.push_back(face.mIndices[j]);
}
our::Mesh* ourMesh = new our::Mesh(vertices, indices);
std::string name = this->name + "_" + std::to_string(mesh->mMaterialIndex);
Material* material = AssetLoader<Material>::get(name);
if (!material) {
std::cerr << "\033[31mFailed to load material for mesh " << mesh->mName.C_Str() << "\033[0m" << std::endl;
delete ourMesh;
return nullptr;
}
MeshRendererComponent* meshComponent = new MeshRendererComponent();
meshComponent->mesh = ourMesh;
meshComponent->material = material;
meshComponent->hasBones = mesh->HasBones();
return meshComponent;
}
void Model::loadMaterialsFromScene(const aiScene* scene) {
for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
aiMaterial* mat = scene->mMaterials[i];
LitMaterial* material = loadMaterial(scene, mat);
std::string name = this->name + "_" + std::to_string(i);
if (material) {
AssetLoader<Material>::add(name, material);
AssetLoader<Sampler>::add(name, material->sampler);
}
}
}
void Model::loadAnimationsFromScene(const aiScene* scene) {
for (unsigned int i = 0; i < scene->mNumAnimations; ++i) {
std::string animName = scene->mAnimations[i]->mName.C_Str();
if (animName.empty()) {
animName = "Anim_" + std::to_string(i);
}
animations.emplace(animName, Animation(scene->mAnimations[i], *skeleton));
std::cout << "Loaded animation: \"" << animName << "\"" << std::endl;
AssetLoaderStats::loadingCount++;
}
}
void Model::loadAnimationsFromScene(const aiScene* scene, const std::unordered_set<std::string>& nameFilter) {
// if none specified, load all animations
const bool isEmpty = nameFilter.empty();
for (unsigned int i = 0; i < scene->mNumAnimations; ++i) {
aiAnimation* aiAnim = scene->mAnimations[i];
std::string animName = aiAnim->mName.C_Str();
if (animName.empty()) animName = "Anim_" + std::to_string(i);
if (isEmpty || nameFilter.count(animName)) {
auto [it, inserted] = animations.emplace(animName, Animation(aiAnim, *skeleton));
if (!inserted)
std::cerr << "[Model] Duplicate animation skipped: \"" << animName << "\"\n";
else
std::cout << "Loaded animation: \"" << animName << "\"\n";
AssetLoaderStats::loadingCount++;
}
}
}
LitMaterial* Model::loadMaterial(const aiScene* scene, const aiMaterial* mat) {
LitMaterial* material = new LitMaterial();
material->transparent = false;
material->metallic = 0.0f;
material->roughness = 0.5f;
Sampler* sampler = new Sampler();
material->sampler = sampler;
aiString matName;
mat->Get(AI_MATKEY_NAME, matName);
// Check shading mode first
int shadingMode = 0;
mat->Get(AI_MATKEY_SHADING_MODEL, shadingMode);
material->shader = AssetLoader<ShaderProgram>::get(
(shadingMode == aiShadingMode_PBR_BRDF || shadingMode == aiShadingMode_CookTorrance) ? "pbr" : "lit");
if (!material->shader) {
std::cerr << "\033[31mFailed to load shader for material " << matName.C_Str() << "\033[0m" << std::endl;
delete material;
material = nullptr;
return nullptr;
}
// albedo factor
aiColor4D color;
material->tint = glm::vec4(1.0f); // default tint is white (no tint)
if (AI_SUCCESS == mat->Get(AI_MATKEY_BASE_COLOR, color)) {
material->albedo = aiToGlm(color);
material->tint.a = color.a;
} else if (AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_DIFFUSE, color)) {
material->albedo = aiToGlm(color);
material->tint.a = color.a;
std::cout << "\033[33m[Warning] Material " << matName.C_Str() << " using diffuse color as albedo.\033[0m\n";
} else {
material->albedo = glm::vec3(1.0f, 1.0f, 1.0f);
material->tint.a = 1.0f;
}
// metallic factor
if (AI_SUCCESS == mat->Get(AI_MATKEY_METALLIC_FACTOR, material->metallic)) {
material->metallic = std::clamp(material->metallic, 0.0f, 1.0f);
} else {
material->metallic = 0.0f;
}
// roughness factor
if (AI_SUCCESS == mat->Get(AI_MATKEY_ROUGHNESS_FACTOR, material->roughness)) {
material->roughness = std::clamp(material->roughness, 0.0f, 1.0f);
} else {
material->roughness = 0.1f;
}
// emission factor
if (AI_SUCCESS == mat->Get(AI_MATKEY_COLOR_EMISSIVE, color)) {
material->emission = aiToGlm(color);
float intensity = 1.0f;
mat->Get(AI_MATKEY_EMISSIVE_INTENSITY, intensity);
material->emission *= intensity;
}
// set default ambient occlusion
material->ambientOcclusion = 1.0f;
auto toGLWrap = [](int v, int fallback) -> int {
switch (v) {
case aiTextureMapMode_Wrap:
return GL_REPEAT;
case aiTextureMapMode_Clamp:
return GL_CLAMP_TO_EDGE;
case aiTextureMapMode_Mirror:
return GL_MIRRORED_REPEAT;
case aiTextureMapMode_Decal:
return GL_CLAMP_TO_BORDER;
default:
return fallback;
}
};
// Query sampler from BASE_COLOR slot, fall back to DIFFUSE
auto querySlot = [&](aiTextureType type) {
int v;
if (mat->Get("$tex.mappingfiltermin", type, 0, v) == AI_SUCCESS) sampler->set(GL_TEXTURE_MIN_FILTER, v);
if (mat->Get("$tex.mappingfiltermag", type, 0, v) == AI_SUCCESS) sampler->set(GL_TEXTURE_MAG_FILTER, v);
if (mat->Get(AI_MATKEY_MAPPINGMODE_U(type, 0), v) == AI_SUCCESS)
sampler->set(GL_TEXTURE_WRAP_S, toGLWrap(v, GL_REPEAT));
if (mat->Get(AI_MATKEY_MAPPINGMODE_V(type, 0), v) == AI_SUCCESS)
sampler->set(GL_TEXTURE_WRAP_T, toGLWrap(v, GL_REPEAT));
};
// Try BASE_COLOR slot first, fall back to DIFFUSE
unsigned int texCount = mat->GetTextureCount(aiTextureType_BASE_COLOR);
if (texCount > 0)
querySlot(aiTextureType_BASE_COLOR);
else
querySlot(aiTextureType_DIFFUSE);
// Textures
material->textureAlbedo = loadTextureFromMaterial(scene, mat, aiTextureType_BASE_COLOR);
if (!material->textureAlbedo) {
material->textureAlbedo = loadTextureFromMaterial(scene, mat, aiTextureType_DIFFUSE);
}
material->mask.hasAlbedo = material->textureAlbedo != nullptr;
// set normal texture, if not found try height texture
material->textureNormal = loadTextureFromMaterial(scene, mat, aiTextureType_NORMALS);
if (!material->textureNormal) {
material->textureNormal = loadTextureFromMaterial(scene, mat, aiTextureType_HEIGHT);
}
material->mask.hasNormal = material->textureNormal != nullptr;
// set metallic and roughness textures, some models pack them in the same texture so we check for that first
Texture2D* metallicRoughness = loadTextureFromMaterial(scene, mat, aiTextureType_GLTF_METALLIC_ROUGHNESS);
if (metallicRoughness) {
material->textureMetalnessRoughness = metallicRoughness;
material->mask.hasMetalnessRoughness = true;
} else {
material->textureMetallic = loadTextureFromMaterial(scene, mat, aiTextureType_METALNESS);
material->mask.hasMetallic = material->textureMetallic != nullptr;
material->textureRoughness = loadTextureFromMaterial(scene, mat, aiTextureType_DIFFUSE_ROUGHNESS);
material->mask.hasRoughness = material->textureRoughness != nullptr;
}
// set ambient occlusion texture, if not found try lightmap texture
material->textureAmbientOcclusion = loadTextureFromMaterial(scene, mat, aiTextureType_AMBIENT_OCCLUSION);
if (!material->textureAmbientOcclusion) {
material->textureAmbientOcclusion = loadTextureFromMaterial(scene, mat, aiTextureType_LIGHTMAP);
}
material->mask.hasAmbientOcclusion = material->textureAmbientOcclusion != nullptr;
// set emissive texture
material->textureEmissive = loadTextureFromMaterial(scene, mat, aiTextureType_EMISSIVE);
material->mask.hasEmissive = material->textureEmissive != nullptr;
// setting pipeline state
int twoSided = 0;
if (AI_SUCCESS == mat->Get(AI_MATKEY_TWOSIDED, twoSided)) {
material->pipelineState.faceCulling.enabled = !twoSided;
material->pipelineState.faceCulling.culledFace = GL_BACK;
material->pipelineState.faceCulling.frontFace = GL_CCW;
}
// Modulate by opacity
float opacity = 1.0f;
if (AI_SUCCESS == mat->Get(AI_MATKEY_OPACITY, opacity)) {
material->tint.a *= opacity;
}
// Modulate by transparency factor
float transparency = 0.0f;
if (AI_SUCCESS == mat->Get(AI_MATKEY_TRANSPARENCYFACTOR, transparency)) {
material->tint.a *= (1.0f - transparency);
}
// check for alpha mode and alpha cutoff for GLTF models, we only check for alpha mode if the material has an
// albedo texture as it's the only case where it matters
if (material->textureAlbedo) {
aiString alphaMode;
if (mat->Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode) == AI_SUCCESS &&
alphaMode.C_Str() == std::string("MASK")) {
float alphaCutoff = 0.0f;
if (AI_SUCCESS == mat->Get(AI_MATKEY_GLTF_ALPHACUTOFF, alphaCutoff)) {
material->alphaThreshold = alphaCutoff;
}
}
}
material->transparent = material->tint.a < 0.999f;
if (material->transparent) {
material->pipelineState.depthTesting.enabled = GL_TRUE; // disable depth writing for transparent materials
material->pipelineState.depthMask = false;
material->pipelineState.blending.enabled = true;
material->pipelineState.blending.sourceFactor = GL_SRC_ALPHA;
int blendFunc = 0;
if (AI_SUCCESS == mat->Get(AI_MATKEY_BLEND_FUNC, blendFunc)) {
if (blendFunc == aiBlendMode_Additive) {
material->pipelineState.blending.sourceFactor = GL_SRC_ALPHA;
material->pipelineState.blending.destinationFactor = GL_ONE;
} else {
material->pipelineState.blending.sourceFactor = GL_SRC_ALPHA;
material->pipelineState.blending.destinationFactor = GL_ONE_MINUS_SRC_ALPHA;
}
}
} else {
material->pipelineState.depthTesting.enabled = GL_TRUE; // enable depth writing for opaque materials
material->pipelineState.depthTesting.function = GL_LEQUAL;
material->pipelineState.blending.enabled = false;
}
return material;
}
Texture2D* Model::loadTextureFromMaterial(const aiScene* scene, const aiMaterial* mat, aiTextureType type) {
aiString path;
if (mat->GetTextureCount(type) == 0) return nullptr;
if (mat->GetTexture(type, 0, &path) != AI_SUCCESS) return nullptr;
std::string cacheKey = this->name + "_" + path.C_Str();
Texture2D* texture = AssetLoader<Texture2D>::get(cacheKey);
if (texture) return texture;
bool isSrgb = false;
if (type == aiTextureType_BASE_COLOR || type == aiTextureType_DIFFUSE || type == aiTextureType_EMISSIVE) {
isSrgb = true;
}
if (path.length > 0 && path.data[0] == '*') {
// this is an embedded texture, we can load it directly from memory
const aiTexture* embeddedTexture = scene->GetEmbeddedTexture(path.C_Str());
if (!embeddedTexture) {
std::cerr << "Failed to find embedded texture: " << path.C_Str() << std::endl;
return nullptr;
}
if (embeddedTexture->mHeight == 0) {
texture = texture_utils::loadImageFromMemory(
reinterpret_cast<const unsigned char*>(embeddedTexture->pcData), embeddedTexture->mWidth, isSrgb);
} else {
// note that this is not handled properly as it assumes the embedded texture is in RGBA format which
// might not always be the case
texture = new Texture2D();
texture->bind();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, embeddedTexture->mWidth, embeddedTexture->mHeight, 0, GL_RGBA,
GL_UNSIGNED_BYTE, embeddedTexture->pcData);
glGenerateMipmap(GL_TEXTURE_2D);
texture->unbind();
}
} else {
std::string filePath = path.C_Str();
texture = texture_utils::loadImage(modelDirectory + "/" + filePath, isSrgb);
}
if (!texture) return nullptr;
AssetLoader<Texture2D>::add(cacheKey, texture);
AssetLoaderStats::totalCount++;
return texture;
}
void Model::setVertexBoneData(Vertex& vertex, BoneID boneID, float weight) {
for (int i = 0; i < MAX_BONE_INFLUENCE; ++i) {
if (vertex.bone_ids[i] < 0) {
vertex.bone_ids[i] = boneID;
vertex.weights[i] = weight;
return;
}
}
// If we reach here, it means we have more than MAX_BONE_INFLUENCE bones affecting this vertex
// We will ignore the extra bones and just print a warning
std::cerr << "Warning: Vertex has more than " << MAX_BONE_INFLUENCE
<< " bone influences. Extra influences will be ignored." << std::endl;
}
void Model::processVertexBoneData(std::vector<Vertex>& vertices, aiMesh* mesh) {
if (!skeleton) return; // if the model has no animations, we won't have a skeleton to store the bone data in
for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; ++boneIndex) {
aiBone* bone = mesh->mBones[boneIndex];
std::string boneName(bone->mName.C_Str());
BoneID boneID = skeleton->findOrCreateBone(boneName, bone->mOffsetMatrix);
for (unsigned int j = 0; j < bone->mNumWeights; ++j) {
auto boneWeight = bone->mWeights[j];
unsigned int vertexID = boneWeight.mVertexId;
float weight = boneWeight.mWeight;
setVertexBoneData(vertices[vertexID], boneID, weight);
}
}
for (Vertex& vertex : vertices) {
float weightSum = 0.0f;
for (int i = 0; i < MAX_BONE_INFLUENCE; ++i) {
if (vertex.bone_ids[i] >= 0) {
weightSum += vertex.weights[i];
}
}
if (weightSum > 0.0f) {
float invSum = 1.0f / weightSum;
for (int i = 0; i < MAX_BONE_INFLUENCE; ++i) {
if (vertex.bone_ids[i] >= 0) {
vertex.weights[i] *= invSum;
}
}
}
}
}
void Model::generateCombinedMesh() {
std::vector<Vertex> combinedVertices;
std::vector<unsigned int> combinedIndices;
for (const auto& submesh : submeshes) {
unsigned int indexOffset = static_cast<unsigned int>(combinedVertices.size());
// Transform each vertex into model space using the submesh's local transform
for (const Vertex& v : submesh->mesh->getVertices()) {
Vertex transformed = v;
// Apply the submesh transform to position
glm::vec4 worldPos = submesh->transform * glm::vec4(v.position, 1.0f);
transformed.position = glm::vec3(worldPos);
// Transform normal using the normal matrix (inverse transpose)
glm::mat3 normalMatrix = glm::mat3(glm::transpose(glm::inverse(submesh->transform)));
glm::vec3 t = glm::normalize(normalMatrix * glm::vec3(v.tangent));
transformed.tangent = glm::vec4(t, v.tangent.w); // keep handedness unchanged
combinedVertices.push_back(transformed);
}
// Re-base indices so they point into the combined vertex buffer
for (unsigned int idx : submesh->mesh->getIndices()) {
combinedIndices.push_back(idx + indexOffset);
}
}
combinedMesh = new Mesh(combinedVertices, combinedIndices);
AssetLoaderStats::loadingCount++; // count the combined mesh as an asset for loading progress purposes
}
Model::~Model() {
for (auto& submesh : submeshes) {
delete submesh->mesh;
delete submesh;
}
if (skeleton) delete skeleton;
if (combinedMesh) delete combinedMesh;
combinedMesh = nullptr;
}
} // namespace our