SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
ModelLoader.cpp
Go to the documentation of this file.
2
3#include <Core/GameObject.hpp>
9#include <Runtime/Texture.hpp>
10#include <Runtime/Skeleton.hpp>
14#include <Memory/RefPtr.hpp>
15#include <Core/Logger.hpp>
16
17#include <Runtime/MeshData.hpp>
19
20#include <assimp/Importer.hpp>
21#include <assimp/scene.h>
22#include <assimp/postprocess.h>
23
24#include <stb_image.h>
25
26#include <filesystem>
27
28namespace Sleak {
29
30Math::Matrix4 ModelLoader::ConvertMatrix(const void* aiMatPtr) {
31 const auto& m = *static_cast<const aiMatrix4x4*>(
32 static_cast<const void*>(aiMatPtr));
33 Math::Matrix4 result;
34 // Assimp stores column-convention (translation at col 3: a4, b4, c4).
35 // Engine uses row-convention (translation at row 3: (3,0), (3,1), (3,2)).
36 // Transpose during conversion so bone matrices match engine convention.
37 result(0, 0) = m.a1; result(0, 1) = m.b1; result(0, 2) = m.c1; result(0, 3) = m.d1;
38 result(1, 0) = m.a2; result(1, 1) = m.b2; result(1, 2) = m.c2; result(1, 3) = m.d2;
39 result(2, 0) = m.a3; result(2, 1) = m.b3; result(2, 2) = m.c3; result(2, 3) = m.d3;
40 result(3, 0) = m.a4; result(3, 1) = m.b4; result(3, 2) = m.c4; result(3, 3) = m.d4;
41 return result;
42}
43
44GameObject* ModelLoader::Load(const std::string& filePath,
45 const ModelLoadOptions& options) {
46 Assimp::Importer importer;
47
48 unsigned int baseFlags = aiProcess_Triangulate
49 | aiProcess_GenSmoothNormals
50 | aiProcess_CalcTangentSpace
51 | aiProcess_JoinIdenticalVertices
52 | aiProcess_OptimizeMeshes;
53
54 if (options.flipUVs)
55 baseFlags |= aiProcess_FlipUVs;
56
57 // Parse once without post-processing to learn whether it is animated
58 constexpr unsigned int rawImportFlags = 0;
59 const aiScene* scene = importer.ReadFile(filePath, rawImportFlags);
60
61 if (!scene || (scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) || !scene->mRootNode) {
62 SLEAK_ERROR("Assimp: Failed to load model '{}': {}", filePath,
63 importer.GetErrorString());
64 return nullptr;
65 }
66
67 bool hasAnimations = scene->HasAnimations();
68
69 // Static models also get PreTransformVertices, in the same pipeline order
70 unsigned int postFlags = baseFlags;
71 if (!hasAnimations) postFlags |= aiProcess_PreTransformVertices;
72 scene = importer.ApplyPostProcessing(postFlags);
73
74 if (!scene || (scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) ||
75 !scene->mRootNode) {
76 SLEAK_ERROR("Assimp: Failed to post-process model '{}': {}", filePath,
77 importer.GetErrorString());
78 return nullptr;
79 }
80
81 SLEAK_INFO("Model loaded: {} ({} meshes, {} materials, {} textures, {} animations)",
82 filePath, scene->mNumMeshes, scene->mNumMaterials,
83 scene->mNumTextures, scene->mNumAnimations);
84
85 std::string directory = std::filesystem::path(filePath).parent_path().string();
86 auto* root = new GameObject(std::filesystem::path(filePath).stem().string());
87 TextureCache textureCache;
88 MaterialCache materialCache;
89
90 if (!hasAnimations) {
91 ProcessNode(scene->mRootNode, scene, root, directory, options,
92 textureCache, materialCache);
93 } else {
94 // Animated model: extract skeleton and animations
95 Skeleton* skeleton = ExtractSkeleton(scene);
96 std::vector<AnimationClip*> clips = ExtractAnimations(scene, skeleton);
97
98 SLEAK_INFO(" Skeleton: {} bones, {} animation clips",
99 skeleton->GetBoneCount(), clips.size());
100
101 ProcessNodeAnimated(scene->mRootNode, scene, root, directory, options,
102 textureCache, materialCache, skeleton, clips);
103 }
104
105 root->Initialize();
106 return root;
107}
108
109Skeleton* ModelLoader::ExtractSkeleton(const aiScene* scene) {
110 auto* skeleton = new Skeleton();
111
112 // First, collect all bones from all meshes
113 for (unsigned int m = 0; m < scene->mNumMeshes; ++m) {
114 aiMesh* mesh = scene->mMeshes[m];
115 if (!mesh->HasBones()) continue;
116
117 for (unsigned int b = 0; b < mesh->mNumBones; ++b) {
118 aiBone* bone = mesh->mBones[b];
119 std::string boneName = bone->mName.C_Str();
120
121 if (skeleton->FindBoneId(boneName) == -1) {
122 Bone newBone;
123 newBone.name = boneName;
124 newBone.offsetMatrix = ConvertMatrix(&bone->mOffsetMatrix);
125 skeleton->AddBone(newBone);
126 }
127 }
128 }
129
130 // Build parent-child hierarchy from scene node tree
131 BuildBoneHierarchy(scene->mRootNode, skeleton, -1);
132
133 // Build full node tree (includes non-bone nodes for correct hierarchy traversal)
134 BuildNodeTree(scene->mRootNode, skeleton);
135
136 // Compute global inverse transform from root node
137 aiMatrix4x4 rootTransform = scene->mRootNode->mTransformation;
138 rootTransform.Inverse();
139 skeleton->SetGlobalInverseTransform(ConvertMatrix(&rootTransform));
140
141 return skeleton;
142}
143
144int ModelLoader::BuildNodeTree(const aiNode* node, Skeleton* skeleton) {
145 NodeData nodeData;
146 nodeData.name = node->mName.C_Str();
147 nodeData.defaultTransform = ConvertMatrix(&node->mTransformation);
148 nodeData.boneIndex = skeleton->FindBoneId(nodeData.name);
149
150 int nodeIdx = skeleton->AddNode(nodeData);
151
152 for (unsigned int i = 0; i < node->mNumChildren; ++i) {
153 int childIdx = BuildNodeTree(node->mChildren[i], skeleton);
154 skeleton->AddNodeChild(nodeIdx, childIdx);
155 }
156
157 return nodeIdx;
158}
159
160void ModelLoader::BuildBoneHierarchy(const aiNode* node, Skeleton* skeleton,
161 int parentId) {
162 std::string nodeName = node->mName.C_Str();
163 int boneId = skeleton->FindBoneId(nodeName);
164
165 // If this node is a bone, set its parent
166 int nextParent = parentId;
167 if (boneId != -1) {
168 skeleton->SetBoneParent(boneId, parentId);
169 nextParent = boneId;
170 }
171
172 for (unsigned int i = 0; i < node->mNumChildren; ++i) {
173 BuildBoneHierarchy(node->mChildren[i], skeleton, nextParent);
174 }
175}
176
177std::vector<AnimationClip*> ModelLoader::ExtractAnimations(
178 const aiScene* scene, Skeleton* skeleton) {
179 std::vector<AnimationClip*> clips;
180
181 for (unsigned int i = 0; i < scene->mNumAnimations; ++i) {
182 aiAnimation* anim = scene->mAnimations[i];
183 auto* clip = new AnimationClip();
184
185 clip->name = anim->mName.C_Str();
186 if (clip->name.empty())
187 clip->name = "Animation_" + std::to_string(i);
188
189 clip->duration = static_cast<float>(anim->mDuration);
190 clip->ticksPerSecond = anim->mTicksPerSecond > 0
191 ? static_cast<float>(anim->mTicksPerSecond)
192 : 25.0f;
193
194 for (unsigned int c = 0; c < anim->mNumChannels; ++c) {
195 aiNodeAnim* nodeAnim = anim->mChannels[c];
196 AnimationChannel channel;
197
198 channel.boneName = nodeAnim->mNodeName.C_Str();
199 channel.boneId = skeleton->FindBoneId(channel.boneName);
200
201 // Position keyframes
202 for (unsigned int k = 0; k < nodeAnim->mNumPositionKeys; ++k) {
203 auto& key = nodeAnim->mPositionKeys[k];
204 channel.positionKeys.push_back({
205 static_cast<float>(key.mTime),
206 Math::Vector3D(key.mValue.x, key.mValue.y, key.mValue.z)
207 });
208 }
209
210 // Rotation keyframes
211 for (unsigned int k = 0; k < nodeAnim->mNumRotationKeys; ++k) {
212 auto& key = nodeAnim->mRotationKeys[k];
213 channel.rotationKeys.push_back({
214 static_cast<float>(key.mTime),
215 Math::Quaternion(key.mValue.w, key.mValue.x,
216 key.mValue.y, key.mValue.z)
217 });
218 }
219
220 // Scale keyframes
221 for (unsigned int k = 0; k < nodeAnim->mNumScalingKeys; ++k) {
222 auto& key = nodeAnim->mScalingKeys[k];
223 channel.scaleKeys.push_back({
224 static_cast<float>(key.mTime),
225 Math::Vector3D(key.mValue.x, key.mValue.y, key.mValue.z)
226 });
227 }
228
229 clip->channels.push_back(std::move(channel));
230 }
231
232 clip->BuildLookup();
233
234 SLEAK_INFO(" Animation '{}': {} channels, {:.1f}s",
235 clip->name, clip->channels.size(),
236 clip->GetDurationInSeconds());
237
238 clips.push_back(clip);
239 }
240
241 return clips;
242}
243
244void ModelLoader::ProcessNode(aiNode* node, const aiScene* scene,
245 GameObject* parent, const std::string& directory,
246 const ModelLoadOptions& options,
247 TextureCache& textureCache,
248 MaterialCache& materialCache) {
249 std::string nodeName = node->mName.C_Str();
250 if (nodeName.empty()) nodeName = "Node";
251
252 for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
253 aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
254
255 std::string meshName = mesh->mName.C_Str();
256 if (meshName.empty()) meshName = nodeName + "_Mesh" + std::to_string(i);
257
258 auto* meshObj = new GameObject(meshName);
259
260 float sf = options.scaleFactor;
261 meshObj->AddComponent<TransformComponent>(
262 options.position,
263 options.rotation,
264 Math::Vector3D(sf, sf, sf));
265
266 if (mesh->mMaterialIndex < scene->mNumMaterials) {
267 auto& material = materialCache[uint64_t(mesh->mMaterialIndex) << 1];
268 if (!material)
269 material =
270 ProcessMaterial(scene->mMaterials[mesh->mMaterialIndex],
271 scene, directory, textureCache);
272 meshObj->AddComponent<MaterialComponent>(material);
273 }
274
275 MeshData meshData = ProcessMesh(mesh, options);
276 meshObj->AddComponent<ColliderComponent>(meshData, Physics::ColliderType::AABB);
277 meshObj->AddComponent<RigidbodyComponent>(BodyType::Static);
278 meshObj->AddComponent<MeshComponent>(std::move(meshData));
279
280 meshObj->SetParent(parent);
281 }
282
283 for (unsigned int i = 0; i < node->mNumChildren; ++i) {
284 ProcessNode(node->mChildren[i], scene, parent, directory, options,
285 textureCache, materialCache);
286 }
287}
288
289void ModelLoader::ProcessNodeAnimated(
290 aiNode* node, const aiScene* scene, GameObject* parent,
291 const std::string& directory, const ModelLoadOptions& options,
292 TextureCache& textureCache, MaterialCache& materialCache,
293 Skeleton* skeleton, std::vector<AnimationClip*>& clips) {
294 std::string nodeName = node->mName.C_Str();
295 if (nodeName.empty()) nodeName = "Node";
296
297 for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
298 aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
299
300 std::string meshName = mesh->mName.C_Str();
301 if (meshName.empty()) meshName = nodeName + "_Mesh" + std::to_string(i);
302
303 auto* meshObj = new GameObject(meshName);
304
305 float sf = options.scaleFactor;
306 meshObj->AddComponent<TransformComponent>(
307 options.position,
308 options.rotation,
309 Math::Vector3D(sf, sf, sf));
310
311 // Use skinned shader for animated models
312 bool hasBones = mesh->HasBones();
313 if (mesh->mMaterialIndex < scene->mNumMaterials) {
314 uint64_t key =
315 (uint64_t(mesh->mMaterialIndex) << 1) | (hasBones ? 1u : 0u);
316 auto& material = materialCache[key];
317 if (!material)
318 material =
319 ProcessMaterial(scene->mMaterials[mesh->mMaterialIndex],
320 scene, directory, textureCache, hasBones);
321 meshObj->AddComponent<MaterialComponent>(material);
322 }
323
324 // Process mesh with bone data extraction
325 MeshData meshData = ProcessMesh(mesh, options, skeleton);
326 meshObj->AddComponent<ColliderComponent>(meshData, Physics::ColliderType::AABB);
327 meshObj->AddComponent<RigidbodyComponent>(BodyType::Static);
328 meshObj->AddComponent<MeshComponent>(std::move(meshData));
329
330 // Add AnimatorComponent if mesh has bones
331 if (hasBones && skeleton->GetBoneCount() > 0 && !clips.empty()) {
332 meshObj->AddComponent<AnimatorComponent>(skeleton, clips);
333 }
334
335 meshObj->SetParent(parent);
336 }
337
338 for (unsigned int i = 0; i < node->mNumChildren; ++i) {
339 ProcessNodeAnimated(node->mChildren[i], scene, parent, directory,
340 options, textureCache, materialCache, skeleton,
341 clips);
342 }
343}
344
345MeshData ModelLoader::ProcessMesh(aiMesh* mesh, const ModelLoadOptions& options,
346 Skeleton* skeleton) {
347 MeshData data;
348 float nSign = options.flipNormals ? -1.0f : 1.0f;
349
350 // Vertices
351 for (unsigned int i = 0; i < mesh->mNumVertices; ++i) {
352 Vertex v{};
353
354 v.px = mesh->mVertices[i].x;
355 v.py = mesh->mVertices[i].y;
356 v.pz = mesh->mVertices[i].z;
357
358 if (mesh->HasNormals()) {
359 v.nx = nSign * mesh->mNormals[i].x;
360 v.ny = nSign * mesh->mNormals[i].y;
361 v.nz = nSign * mesh->mNormals[i].z;
362 }
363
364 if (mesh->HasTangentsAndBitangents()) {
365 v.tx = mesh->mTangents[i].x;
366 v.ty = mesh->mTangents[i].y;
367 v.tz = mesh->mTangents[i].z;
368 v.tw = 1.0f;
369 }
370
371 if (mesh->HasVertexColors(0)) {
372 v.r = mesh->mColors[0][i].r;
373 v.g = mesh->mColors[0][i].g;
374 v.b = mesh->mColors[0][i].b;
375 v.a = mesh->mColors[0][i].a;
376 } else {
377 v.r = 1.0f; v.g = 1.0f; v.b = 1.0f; v.a = 1.0f;
378 }
379
380 if (mesh->HasTextureCoords(0)) {
381 v.u = mesh->mTextureCoords[0][i].x;
382 v.v = mesh->mTextureCoords[0][i].y;
383 }
384
385 // Bone data defaults already set (-1 IDs, 0 weights)
386 data.vertices.AddVertex(v);
387 }
388
389 // Extract bone weights for vertices
390 if (mesh->HasBones() && skeleton) {
391 for (unsigned int b = 0; b < mesh->mNumBones; ++b) {
392 aiBone* bone = mesh->mBones[b];
393 std::string boneName = bone->mName.C_Str();
394 int boneId = skeleton->FindBoneId(boneName);
395
396 if (boneId == -1) {
397 // Bone not in skeleton yet — add it
398 Bone newBone;
399 newBone.name = boneName;
400 newBone.offsetMatrix = ConvertMatrix(&bone->mOffsetMatrix);
401 boneId = skeleton->AddBone(newBone);
402 }
403
404 for (unsigned int w = 0; w < bone->mNumWeights; ++w) {
405 unsigned int vertexId = bone->mWeights[w].mVertexId;
406 float weight = bone->mWeights[w].mWeight;
407
408 if (vertexId >= data.vertices.GetSize()) continue;
409
410 Vertex* vPtr = data.vertices.GetMutableData() + vertexId;
411
412 // Find first empty bone slot
413 for (int s = 0; s < MAX_BONE_INFLUENCE; ++s) {
414 if (vPtr->boneIDs[s] < 0) {
415 vPtr->boneIDs[s] = boneId;
416 vPtr->boneWeights[s] = weight;
417 break;
418 }
419 }
420 }
421 }
422 }
423
424 // Indices
425 for (unsigned int i = 0; i < mesh->mNumFaces; ++i) {
426 const aiFace& face = mesh->mFaces[i];
427 if (options.flipWinding && face.mNumIndices == 3) {
428 data.indices.add(static_cast<IndexType>(face.mIndices[0]));
429 data.indices.add(static_cast<IndexType>(face.mIndices[2]));
430 data.indices.add(static_cast<IndexType>(face.mIndices[1]));
431 } else {
432 for (unsigned int j = 0; j < face.mNumIndices; ++j) {
433 data.indices.add(static_cast<IndexType>(face.mIndices[j]));
434 }
435 }
436 }
437
438 SLEAK_INFO(" Mesh '{}': {} vertices, {} indices{}",
439 mesh->mName.C_Str(), mesh->mNumVertices,
440 data.indices.GetSize(),
441 mesh->HasBones() ? " (skinned)" : "");
442
443 return data;
444}
445
446RefPtr<Material> ModelLoader::ProcessMaterial(aiMaterial* mat,
447 const aiScene* scene,
448 const std::string& directory,
449 TextureCache& textureCache,
450 bool skinned) {
451 auto* material = new Material();
452 material->SetShader(skinned ? "assets/shaders/skinned_shader.hlsl"
453 : "assets/shaders/default_shader.hlsl");
454
455 aiColor4D color;
456 if (mat->Get(AI_MATKEY_COLOR_DIFFUSE, color) == AI_SUCCESS) {
457 material->SetDiffuseColor(color.r, color.g, color.b, color.a);
458 }
459 if (mat->Get(AI_MATKEY_COLOR_SPECULAR, color) == AI_SUCCESS) {
460 material->SetSpecularColor(Math::Color(
461 static_cast<uint8_t>(color.r * 255),
462 static_cast<uint8_t>(color.g * 255),
463 static_cast<uint8_t>(color.b * 255)));
464 }
465 if (mat->Get(AI_MATKEY_COLOR_EMISSIVE, color) == AI_SUCCESS) {
466 material->SetEmissiveColor(color.r, color.g, color.b);
467 }
468
469 float val;
470 if (mat->Get(AI_MATKEY_SHININESS, val) == AI_SUCCESS)
471 material->SetShininess(val);
472 if (mat->Get(AI_MATKEY_OPACITY, val) == AI_SUCCESS)
473 material->SetOpacity(val);
474 if (mat->Get(AI_MATKEY_METALLIC_FACTOR, val) == AI_SUCCESS)
475 material->SetMetallic(val);
476 if (mat->Get(AI_MATKEY_ROUGHNESS_FACTOR, val) == AI_SUCCESS)
477 material->SetRoughness(val);
478
479 RefPtr<Texture> tex;
480
481 tex = LoadMaterialTexture(mat, aiTextureType_DIFFUSE, scene, directory, textureCache);
482 if (!tex) tex = LoadMaterialTexture(mat, aiTextureType_BASE_COLOR, scene, directory, textureCache);
483 if (tex) material->SetDiffuseTexture(tex);
484
485 tex = LoadMaterialTexture(mat, aiTextureType_NORMALS, scene, directory, textureCache);
486 if (tex) material->SetNormalTexture(tex);
487
488 tex = LoadMaterialTexture(mat, aiTextureType_SPECULAR, scene, directory, textureCache);
489 if (tex) material->SetSpecularTexture(tex);
490
491 tex = LoadMaterialTexture(mat, aiTextureType_EMISSIVE, scene, directory, textureCache);
492 if (tex) material->SetEmissiveTexture(tex);
493
494 tex = LoadMaterialTexture(mat, aiTextureType_METALNESS, scene, directory, textureCache);
495 if (tex) material->SetMetallicTexture(tex);
496
497 tex = LoadMaterialTexture(mat, aiTextureType_DIFFUSE_ROUGHNESS, scene, directory, textureCache);
498 if (tex) material->SetRoughnessTexture(tex);
499
500 return RefPtr<Material>(material);
501}
502
503RefPtr<::Sleak::Texture> ModelLoader::LoadMaterialTexture(
504 aiMaterial* mat, int type, const aiScene* scene,
505 const std::string& directory, TextureCache& textureCache) {
506 auto texType = static_cast<aiTextureType>(type);
507
508 if (mat->GetTextureCount(texType) == 0) return RefPtr<Texture>();
509
510 aiString aiPath;
511 mat->GetTexture(texType, 0, &aiPath);
512 std::string texPath = aiPath.C_Str();
513
514 // Check cache first (keyed by texture path + type to avoid conflicts)
515 std::string cacheKey = texPath + ":" + std::to_string(type);
516 auto it = textureCache.find(cacheKey);
517 if (it != textureCache.end())
518 return it->second;
519
520 // Check for embedded texture
521 const aiTexture* embedded = scene->GetEmbeddedTexture(texPath.c_str());
522 if (embedded) {
523 ::Sleak::Texture* tex = nullptr;
524 if (embedded->mHeight == 0) {
525 // Compressed embedded texture (PNG/JPG stored as blob)
526 int w, h, channels;
527 unsigned char* pixels = stbi_load_from_memory(
528 reinterpret_cast<const unsigned char*>(embedded->pcData),
529 static_cast<int>(embedded->mWidth),
530 &w, &h, &channels, 4); // Force RGBA
531
532 if (!pixels) {
533 SLEAK_ERROR(" Failed to decode embedded texture: {}", texPath);
534 return RefPtr<Texture>();
535 }
536
538 pixels, static_cast<uint32_t>(w), static_cast<uint32_t>(h),
540
541 stbi_image_free(pixels);
542
543 if (tex) {
544 SLEAK_INFO(" Loaded embedded texture: {} ({}x{})", texPath, w, h);
545 }
546 } else {
547 // Raw uncompressed ARGB8888 data
548 uint32_t w = embedded->mWidth;
549 uint32_t h = embedded->mHeight;
550
551 // Convert ARGB to RGBA
552 std::vector<uint8_t> rgba(w * h * 4);
553 const auto* src = reinterpret_cast<const uint8_t*>(embedded->pcData);
554 for (uint32_t i = 0; i < w * h; ++i) {
555 rgba[i * 4 + 0] = src[i * 4 + 1]; // R
556 rgba[i * 4 + 1] = src[i * 4 + 2]; // G
557 rgba[i * 4 + 2] = src[i * 4 + 3]; // B
558 rgba[i * 4 + 3] = src[i * 4 + 0]; // A
559 }
560
562 rgba.data(), w, h, TextureFormat::RGBA8);
563
564 if (tex) {
565 SLEAK_INFO(" Loaded embedded raw texture: {} ({}x{})", texPath, w, h);
566 }
567 }
568
569 RefPtr<Texture> owned(tex);
570 if (owned) textureCache[cacheKey] = owned;
571 return owned;
572 }
573
574 // External texture file
575 std::string fullPath = directory + "/" + texPath;
576
577 // Normalize path separators
578 std::replace(fullPath.begin(), fullPath.end(), '\\', '/');
579
580 if (!std::filesystem::exists(fullPath)) {
581 SLEAK_WARN(" Texture file not found: {}", fullPath);
582 return RefPtr<Texture>();
583 }
584
585 RefPtr<Texture> tex(RenderEngine::ResourceManager::CreateTexture(fullPath));
586 if (tex) {
587 SLEAK_INFO(" Loaded texture: {}", fullPath);
588 textureCache[cacheKey] = tex;
589 }
590 return tex;
591}
592
593std::vector<AnimationClip*> ModelLoader::LoadAnimationsOnly(
594 const std::string& filePath, Skeleton* skeleton) {
595 std::vector<AnimationClip*> result;
596
597 if (!skeleton) {
598 SLEAK_ERROR("LoadAnimationsOnly: null skeleton");
599 return result;
600 }
601
602 Assimp::Importer importer;
603 unsigned int flags = aiProcess_Triangulate;
604
605 const aiScene* scene = importer.ReadFile(filePath, flags);
606 if (!scene || !scene->HasAnimations()) {
607 SLEAK_ERROR("LoadAnimationsOnly: failed to load or no animations in '{}'",
608 filePath);
609 return result;
610 }
611
612 result = ExtractAnimations(scene, skeleton);
613
614 // Rename clips to filename stem if they have generic names
615 std::string stem = std::filesystem::path(filePath).stem().string();
616 for (auto* clip : result) {
617 if (clip->name.empty() || clip->name.find("Armature") != std::string::npos
618 || clip->name.find("mixamo") != std::string::npos
619 || clip->name.find("Animation") != std::string::npos) {
620 clip->name = stem;
621 clip->BuildLookup();
622 }
623 }
624
625 SLEAK_INFO("LoadAnimationsOnly: '{}' -> {} clips", filePath, result.size());
626 return result;
627}
628
629} // namespace Sleak
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
GameObject(const std::string &name="GameObject")
static GameObject * Load(const std::string &filePath, const ModelLoadOptions &options={})
Imports a model file and returns the root of the resulting GameObject hierarchy.
static std::vector< AnimationClip * > LoadAnimationsOnly(const std::string &filePath, Skeleton *skeleton)
Load only animations from an FBX, reusing an existing skeleton.
friend class RefPtr
Definition RefPtr.hpp:65
static Sleak::Texture * CreateTexture(const std::string &TexturePath)
Loads a texture via the currently registered backend factory.
static Sleak::Texture * CreateTextureFromMemory(const void *data, uint32_t width, uint32_t height, TextureFormat format, uint32_t maxMipLevels=0)
Creates a texture from raw pixel data via the currently registered backend factory.
int GetBoneCount() const
Definition Skeleton.hpp:40
Matrix< float, 4, 4 > Matrix4
Definition Matrix.hpp:404
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
std::unordered_map< std::string, RefPtr<::Sleak::Texture > > TextureCache
Per-load texture cache to avoid loading the same texture file multiple times.
uint32_t IndexType
Definition MeshData.hpp:11
std::unordered_map< uint64_t, RefPtr< Material > > MaterialCache
Per-load cache so meshes sharing an Assimp material share one Material.
std::string name
Definition Skeleton.hpp:18
Math::Matrix4 offsetMatrix
Definition Skeleton.hpp:21