NoJobEngine 2.0.7
Loading...
Searching...
No Matches
AssetManager.cpp
Go to the documentation of this file.
2#include "Engine/Core/Log.h"
3
10
11#include <assimp/Importer.hpp>
12#include <assimp/scene.h>
13#include <assimp/material.h>
14#include <assimp/postprocess.h>
15
16#include <stdexcept>
17#include <algorithm>
18#include <cctype>
19#include <vector>
20#include <fstream>
21#include <iomanip>
22#include <cmath>
23
24namespace NoJob
25{
26 std::filesystem::path AssetManager::s_ProjectRoot;
27 std::filesystem::path AssetManager::s_AssetsDirectory;
28 std::unordered_map<
29 std::string,
30 std::weak_ptr<Texture2D>> AssetManager::s_TextureCache;
31 std::unordered_map<
32 const Texture2D*,
33 std::filesystem::path> AssetManager::s_TexturePaths;
34 std::unordered_map<std::string,std::weak_ptr<Mesh>> AssetManager::s_MeshCache;
35 std::unordered_map<const Mesh*,std::filesystem::path> AssetManager::s_MeshPaths;
36
37 void AssetManager::Init(const std::filesystem::path& projectRoot)
38 {
39 s_ProjectRoot = std::filesystem::absolute(projectRoot).lexically_normal();
40 s_AssetsDirectory = s_ProjectRoot / "Assets";
41
42 std::filesystem::create_directories(s_AssetsDirectory / "Textures");
43 std::filesystem::create_directories(s_AssetsDirectory / "Models");
44 std::filesystem::create_directories(s_AssetsDirectory / "Materials");
45 std::filesystem::create_directories(s_AssetsDirectory / "Scenes");
46 std::filesystem::create_directories(s_AssetsDirectory / "Prefabs");
47 AssetRegistry registry(s_AssetsDirectory); registry.Load(); registry.Scan();
48 }
49
50 const std::filesystem::path& AssetManager::GetProjectRoot()
51 {
52 return s_ProjectRoot;
53 }
54
55 const std::filesystem::path& AssetManager::GetAssetsDirectory()
56 {
57 return s_AssetsDirectory;
58 }
59
60 std::filesystem::path AssetManager::ResolveProjectPath(
61 const std::filesystem::path& path)
62 {
63 if (path.empty() || path.is_absolute() || s_ProjectRoot.empty())
64 return path.lexically_normal();
65
66 return (s_ProjectRoot / path).lexically_normal();
67 }
68
69 std::filesystem::path AssetManager::MakeUniqueDestination(
70 const std::filesystem::path& directory,
71 const std::filesystem::path& filename)
72 {
73 std::filesystem::path destination = directory / filename;
74
75 if (!std::filesystem::exists(destination))
76 return destination;
77
78 const std::string stem = filename.stem().string();
79 const std::string extension = filename.extension().string();
80
81 for (int index = 1; ; ++index)
82 {
83 destination =
84 directory /
85 (stem + "_" + std::to_string(index) + extension);
86
87 if (!std::filesystem::exists(destination))
88 return destination;
89 }
90 }
91
92 std::filesystem::path AssetManager::ImportTexture(
93 const std::filesystem::path& sourcePath)
94 {
95 if (s_ProjectRoot.empty())
96 throw std::runtime_error("AssetManager has not been initialized.");
97
98 if (!std::filesystem::exists(sourcePath))
99 throw std::runtime_error("Texture source file does not exist.");
100
101 const auto texturesDirectory =
102 s_AssetsDirectory / "Textures";
103
104 std::filesystem::create_directories(texturesDirectory);
105
106 const auto absoluteSource =
107 std::filesystem::absolute(sourcePath).lexically_normal();
108
109 // If it is already inside Assets, do not duplicate it.
110 const auto relativeExisting =
111 ToProjectRelative(absoluteSource);
112
113 if (!relativeExisting.empty()
114 && relativeExisting.native().find(
115 std::filesystem::path("Assets").native()) == 0)
116 {
117 return relativeExisting;
118 }
119
120 const auto destination =
121 MakeUniqueDestination(
122 texturesDirectory,
123 sourcePath.filename());
124
125 std::filesystem::copy_file(
126 sourcePath,
127 destination,
128 std::filesystem::copy_options::none);
129
130 return ToProjectRelative(destination);
131 }
132
133 std::filesystem::path AssetManager::ImportModel(const std::filesystem::path& sourcePath)
134 {
135 if(!std::filesystem::exists(sourcePath))throw std::runtime_error("Model does not exist");
136 std::string ext=sourcePath.extension().string();std::transform(ext.begin(),ext.end(),ext.begin(),[](unsigned char c){return(char)std::tolower(c);});
137 static const std::vector<std::string> supported{
138 ".obj",".fbx",".gltf",".glb",".dae",".stl",".ply",".3ds",".blend"
139 };
140 if(std::find(supported.begin(),supported.end(),ext)==supported.end())
141 throw std::runtime_error("Unsupported model format: "+ext);
142 auto dst=MakeUniqueDestination(s_AssetsDirectory/"Models",sourcePath.filename());
143 std::filesystem::copy_file(sourcePath,dst);
144
145 // Preserve the original import location. Assimp material texture paths
146 // are commonly relative to the source FBX/OBJ/glTF directory.
147 {
148 std::ofstream sidecar(dst.string()+".source",std::ios::trunc);
149 if(sidecar) sidecar<<std::quoted(std::filesystem::absolute(sourcePath).lexically_normal().generic_string())<<"\n";
150 }
151
152 AssetRegistry r(s_AssetsDirectory);
153 r.Load();
155 r.Save();
156 return ToProjectRelative(dst);
157 }
158
159 std::shared_ptr<Material> AssetManager::ImportModelMaterial(
160 const std::filesystem::path& modelPath,
161 const std::shared_ptr<Shader>& shader)
162 {
163 if (!shader)
164 return {};
165
166 std::filesystem::path imported =
167 modelPath.is_absolute() ? modelPath : s_ProjectRoot / modelPath;
168 imported = std::filesystem::absolute(imported).lexically_normal();
169
170 // Prefer the original source when available so relative texture
171 // references still resolve even though the model was copied to Assets.
172 std::filesystem::path source = imported;
173 {
174 std::ifstream sidecar(imported.string() + ".source");
175 std::string original;
176 if (sidecar >> std::quoted(original))
177 {
178 std::filesystem::path candidate(original);
179 if (std::filesystem::exists(candidate))
180 source = candidate;
181 }
182 }
183
184 Assimp::Importer importer;
185 const aiScene* scene = importer.ReadFile(
186 source.string(),
187 aiProcess_Triangulate |
188 aiProcess_GenSmoothNormals |
189 aiProcess_JoinIdenticalVertices);
190
191 if (!scene || scene->mNumMaterials == 0)
192 return {};
193
194 unsigned materialIndex = 0;
195 if (scene->mNumMeshes > 0)
196 materialIndex = scene->mMeshes[0]->mMaterialIndex;
197 if (materialIndex >= scene->mNumMaterials)
198 materialIndex = 0;
199
200 aiMaterial* sourceMaterial = scene->mMaterials[materialIndex];
201 auto material = std::make_shared<Material>(shader);
202
203 aiColor4D color;
204 if (aiGetMaterialColor(
205 sourceMaterial, AI_MATKEY_BASE_COLOR, &color) == AI_SUCCESS ||
206 aiGetMaterialColor(
207 sourceMaterial, AI_MATKEY_COLOR_DIFFUSE, &color) == AI_SUCCESS)
208 {
209 material->GetColor() =
210 glm::vec4(color.r, color.g, color.b, color.a);
211 }
212
213 ai_real value = 0.0f;
214 if (aiGetMaterialFloat(
215 sourceMaterial, AI_MATKEY_METALLIC_FACTOR, &value) == AI_SUCCESS)
216 material->Metallic() = static_cast<float>(value);
217
218 if (aiGetMaterialFloat(
219 sourceMaterial, AI_MATKEY_ROUGHNESS_FACTOR, &value) == AI_SUCCESS)
220 material->Roughness() =
221 std::clamp(static_cast<float>(value), 0.04f, 1.0f);
222
223 aiColor3D emissive(0.0f);
224 if (sourceMaterial->Get(
225 AI_MATKEY_COLOR_EMISSIVE, emissive) == AI_SUCCESS)
226 {
227 material->EmissiveColor() =
228 glm::vec3(emissive.r, emissive.g, emissive.b);
229 const float peak = std::max(
230 emissive.r, std::max(emissive.g, emissive.b));
231 if (peak > 0.0f)
232 material->EmissiveStrength() = 1.0f;
233 }
234
235 const auto textureDirectory = s_AssetsDirectory / "Textures";
236 std::filesystem::create_directories(textureDirectory);
237
238 auto importTextureReference =
239 [&](aiTextureType type) -> std::shared_ptr<Texture2D>
240 {
241 if (sourceMaterial->GetTextureCount(type) == 0)
242 return {};
243
244 aiString textureRef;
245 if (sourceMaterial->GetTexture(type, 0, &textureRef) != AI_SUCCESS)
246 return {};
247
248 const std::string ref = textureRef.C_Str();
249 if (ref.empty())
250 return {};
251
252 try
253 {
254 // Embedded Assimp texture reference, e.g. "*0".
255 if (ref[0] == '*')
256 {
257 const unsigned index =
258 static_cast<unsigned>(std::stoul(ref.substr(1)));
259 if (index >= scene->mNumTextures)
260 return {};
261
262 const aiTexture* embedded = scene->mTextures[index];
263 std::string extension =
264 embedded->achFormatHint[0]
265 ? ("." + std::string(embedded->achFormatHint))
266 : ".png";
267
268 auto destination = MakeUniqueDestination(
269 textureDirectory,
270 source.stem().string() + "_embedded_" +
271 std::to_string(index) + extension);
272
273 if (embedded->mHeight == 0)
274 {
275 std::ofstream out(destination, std::ios::binary);
276 out.write(
277 reinterpret_cast<const char*>(embedded->pcData),
278 static_cast<std::streamsize>(embedded->mWidth));
279 }
280 else
281 {
282 // Raw aiTexel embedded textures are uncommon for FBX.
283 // They require an image encoder, so keep them as a
284 // graceful unsupported case instead of corrupting data.
285 return {};
286 }
287
288 AssetRegistry registry(s_AssetsDirectory);
289 registry.Load();
290 registry.Register(destination, AssetType::Texture2D);
291 registry.Save();
292 return LoadTexture(ToProjectRelative(destination));
293 }
294
295 std::filesystem::path texturePath(ref);
296 if (texturePath.is_relative())
297 texturePath = source.parent_path() / texturePath;
298 texturePath =
299 std::filesystem::absolute(texturePath).lexically_normal();
300
301 if (!std::filesystem::exists(texturePath))
302 return {};
303
304 const auto importedTexture = ImportTexture(texturePath);
305 AssetRegistry registry(s_AssetsDirectory);
306 registry.Load();
307 registry.Register(
308 s_ProjectRoot / importedTexture,
310 registry.Save();
311 return LoadTexture(importedTexture);
312 }
313 catch (...)
314 {
315 Log::Warn("Material texture import failed; texture slot left empty.");
316 return {};
317 }
318 };
319
320 float opacity = 1.0f;
321 if (aiGetMaterialFloat(sourceMaterial, AI_MATKEY_OPACITY, &opacity) == AI_SUCCESS)
322 material->GetColor().a *= std::clamp(opacity, 0.0f, 1.0f);
323 aiString alphaMode;
324 const bool hasAlphaMode =
325 sourceMaterial->Get("$mat.gltf.alphaMode", 0, 0, alphaMode) == AI_SUCCESS;
326 const bool hasOpacityMap =
327 sourceMaterial->GetTextureCount(aiTextureType_OPACITY) > 0;
328 if (hasAlphaMode && std::string(alphaMode.C_Str()) == "BLEND")
329 material->SurfaceMode() = MaterialSurfaceMode::Transparent;
330 else if ((hasAlphaMode && std::string(alphaMode.C_Str()) == "MASK") || hasOpacityMap)
331 material->SurfaceMode() = MaterialSurfaceMode::AlphaClip;
332 else if (material->GetColor().a < 0.999f)
333 material->SurfaceMode() = MaterialSurfaceMode::Transparent;
334
335 auto albedo = importTextureReference(aiTextureType_BASE_COLOR);
336 if (!albedo)
337 albedo = importTextureReference(aiTextureType_DIFFUSE);
338 if (albedo)
339 {
340 material->SetTexture(albedo);
341 material->UseTexture() = true;
342 }
343 else
344 {
345 material->UseTexture() = false;
346 }
347
348 auto normal = importTextureReference(aiTextureType_NORMAL_CAMERA);
349 if (!normal)
350 normal = importTextureReference(aiTextureType_NORMALS);
351 material->SetNormalTexture(normal);
352
353 material->SetMetallicTexture(
354 importTextureReference(aiTextureType_METALNESS));
355 material->SetRoughnessTexture(
356 importTextureReference(aiTextureType_DIFFUSE_ROUGHNESS));
357
358 auto ao = importTextureReference(aiTextureType_AMBIENT_OCCLUSION);
359 if (!ao)
360 ao = importTextureReference(aiTextureType_LIGHTMAP);
361 material->SetAOTexture(ao);
362 material->SetEmissiveTexture(
363 importTextureReference(aiTextureType_EMISSIVE));
364
365 // Persist the generated material next to the rest of the project's
366 // materials so it is visible/reusable in Project.
367 const auto materialPath = MakeUniqueDestination(
368 s_AssetsDirectory / "Materials",
369 imported.stem().string() + ".nojobmat");
370
371 AssetRegistry registry(s_AssetsDirectory);
372 registry.Load();
373 MaterialSerializer::Save(*material, materialPath, registry);
374 registry.Register(materialPath, AssetType::Material);
375 registry.Save();
376
377 return material;
378 }
379
380
381 std::vector<std::shared_ptr<Material>> AssetManager::ImportModelMaterials(
382 const std::filesystem::path& modelPath,
383 const std::shared_ptr<Shader>& shader)
384 {
385 std::vector<std::shared_ptr<Material>> materials;
386 if(!shader) return materials;
387
388 std::filesystem::path imported=modelPath.is_absolute()?modelPath:s_ProjectRoot/modelPath;
389 imported=std::filesystem::absolute(imported).lexically_normal();
390 std::filesystem::path source=imported;
391 {
392 std::ifstream sidecar(imported.string()+".source");
393 std::string original;
394 if(sidecar>>std::quoted(original))
395 {
396 std::filesystem::path candidate(original);
397 if(std::filesystem::exists(candidate)) source=candidate;
398 }
399 }
400
401 Assimp::Importer importer;
402 const aiScene* scene=importer.ReadFile(source.string(),
403 aiProcess_Triangulate|aiProcess_GenSmoothNormals|aiProcess_JoinIdenticalVertices);
404 if(!scene || scene->mNumMaterials==0) return materials;
405
406 const auto textureDirectory=s_AssetsDirectory/"Textures";
407 std::filesystem::create_directories(textureDirectory);
408 std::filesystem::create_directories(s_AssetsDirectory/"Materials");
409
410 auto loadRef=[&](aiMaterial* sm,aiTextureType type)->std::shared_ptr<Texture2D>
411 {
412 if(sm->GetTextureCount(type)==0) return {};
413 aiString ar; if(sm->GetTexture(type,0,&ar)!=AI_SUCCESS) return {};
414 std::string ref=ar.C_Str(); if(ref.empty()) return {};
415 try
416 {
417 // Assimp can expose embedded FBX textures either as "*0" references
418 // or by their embedded filename. Handle both forms.
419 if (const aiTexture* embeddedByName = scene->GetEmbeddedTexture(ref.c_str()))
420 {
421 if (embeddedByName->mHeight == 0)
422 {
423 std::string ext = embeddedByName->achFormatHint[0]
424 ? ("." + std::string(embeddedByName->achFormatHint))
425 : std::filesystem::path(ref).extension().string();
426 if (ext.empty()) ext = ".png";
427 auto dest = MakeUniqueDestination(textureDirectory,
428 source.stem().string() + "_embedded_" +
429 std::filesystem::path(ref).stem().string() + ext);
430 std::ofstream out(dest, std::ios::binary);
431 out.write(reinterpret_cast<const char*>(embeddedByName->pcData),
432 static_cast<std::streamsize>(embeddedByName->mWidth));
433 out.close();
434 AssetRegistry r(s_AssetsDirectory); r.Load();
435 r.Register(dest, AssetType::Texture2D); r.Save();
436 return LoadTexture(ToProjectRelative(dest));
437 }
438 }
439
440 if(ref[0]=='*')
441 {
442 unsigned idx=static_cast<unsigned>(std::stoul(ref.substr(1)));
443 if(idx>=scene->mNumTextures) return {};
444 const aiTexture* e=scene->mTextures[idx];
445 if(e->mHeight!=0) return {};
446 std::string ext=e->achFormatHint[0]?("."+std::string(e->achFormatHint)):".png";
447 auto dest=MakeUniqueDestination(textureDirectory,
448 source.stem().string()+"_embedded_"+std::to_string(idx)+ext);
449 std::ofstream out(dest,std::ios::binary);
450 out.write(reinterpret_cast<const char*>(e->pcData),
451 static_cast<std::streamsize>(e->mWidth));
452 out.close();
453 AssetRegistry r(s_AssetsDirectory);r.Load();
455 return LoadTexture(ToProjectRelative(dest));
456 }
457 std::filesystem::path tp(ref);
458 if(tp.is_relative()) tp=source.parent_path()/tp;
459 tp=std::filesystem::absolute(tp).lexically_normal();
460
461 // FBX files (notably Mixamo exports) often retain an exporter-specific
462 // relative/absolute texture path that no longer exists on this machine.
463 // Recover by filename from the model folder or Assets/Textures.
464 if(!std::filesystem::exists(tp))
465 {
466 const auto wanted=std::filesystem::path(ref).filename();
467 const auto direct=source.parent_path()/wanted;
468 if(std::filesystem::exists(direct))
469 tp=direct;
470 else
471 {
472 std::error_code ec;
473 for(std::filesystem::recursive_directory_iterator it(source.parent_path(),ec),end;
474 !ec && it!=end;++it)
475 {
476 if(it->is_regular_file(ec) && it->path().filename()==wanted)
477 { tp=it->path(); break; }
478 }
479 }
480 if(!std::filesystem::exists(tp))
481 {
482 const auto importedCandidate=textureDirectory/wanted;
483 if(std::filesystem::exists(importedCandidate))
484 return LoadTexture(ToProjectRelative(importedCandidate));
485 }
486 }
487 if(!std::filesystem::exists(tp)) return {};
488 auto rel=ImportTexture(tp);
489 AssetRegistry r(s_AssetsDirectory);r.Load();
490 r.Register(s_ProjectRoot/rel,AssetType::Texture2D);r.Save();
491 return LoadTexture(rel);
492 }catch(...){Log::Warn("Model material texture import failed; texture slot left empty.");return {};}
493 };
494
495 for(unsigned i=0;i<scene->mNumMaterials;++i)
496 {
497 aiMaterial* sm=scene->mMaterials[i];
498 auto m=std::make_shared<Material>(shader);
499 aiColor4D c;
500 if(aiGetMaterialColor(sm,AI_MATKEY_BASE_COLOR,&c)==AI_SUCCESS ||
501 aiGetMaterialColor(sm,AI_MATKEY_COLOR_DIFFUSE,&c)==AI_SUCCESS)
502 m->GetColor()={c.r,c.g,c.b,c.a};
503 ai_real v=0;
504 if(aiGetMaterialFloat(sm,AI_MATKEY_METALLIC_FACTOR,&v)==AI_SUCCESS)m->Metallic()=(float)v;
505 if(aiGetMaterialFloat(sm,AI_MATKEY_ROUGHNESS_FACTOR,&v)==AI_SUCCESS)m->Roughness()=std::clamp((float)v,0.04f,1.0f);
506 aiColor3D ec(0);
507 if(sm->Get(AI_MATKEY_COLOR_EMISSIVE,ec)==AI_SUCCESS)
508 {m->EmissiveColor()={ec.r,ec.g,ec.b};if(std::max(ec.r,std::max(ec.g,ec.b))>0)m->EmissiveStrength()=1;}
509
510 // Import surface/transparency semantics. FBX commonly exposes
511 // foliage masks through aiTextureType_OPACITY; glTF exposes alphaMode.
512 float opacity = 1.0f;
513 if (aiGetMaterialFloat(sm, AI_MATKEY_OPACITY, &opacity) == AI_SUCCESS)
514 m->GetColor().a *= std::clamp(opacity, 0.0f, 1.0f);
515
516 aiString alphaMode;
517 const bool hasAlphaMode =
518 sm->Get("$mat.gltf.alphaMode", 0, 0, alphaMode) == AI_SUCCESS;
519 const bool hasOpacityMap =
520 sm->GetTextureCount(aiTextureType_OPACITY) > 0;
521
522 if (hasAlphaMode && std::string(alphaMode.C_Str()) == "BLEND")
523 m->SurfaceMode() = MaterialSurfaceMode::Transparent;
524 else if (hasAlphaMode && std::string(alphaMode.C_Str()) == "MASK")
525 m->SurfaceMode() = MaterialSurfaceMode::AlphaClip;
526 else if (hasOpacityMap)
527 m->SurfaceMode() = MaterialSurfaceMode::AlphaClip;
528 else if (m->GetColor().a < 0.999f)
529 m->SurfaceMode() = MaterialSurfaceMode::Transparent;
530
531 ai_real cutoff = 0.5f;
532 if (sm->Get("$mat.gltf.alphaCutoff", 0, 0, cutoff) == AI_SUCCESS)
533 m->AlphaCutoff() =
534 std::clamp(static_cast<float>(cutoff), 0.0f, 1.0f);
535
536 auto al=loadRef(sm,aiTextureType_BASE_COLOR);
537 if(!al) al=loadRef(sm,aiTextureType_DIFFUSE);
538 if(al)
539 {
540 m->SetTexture(al);
541 m->UseTexture()=true;
542
543 // FBX/Mixamo diffuse colors are commonly an additional legacy
544 // material tint. Multiplying that tint by an already-authored
545 // diffuse texture makes skin/clothes much too dark.
546 // Keep alpha, but let the texture provide the RGB color.
547 if(source.extension()==".fbx" || source.extension()==".FBX")
548 {
549 const float alpha=m->GetColor().a;
550 m->GetColor()={1.0f,1.0f,1.0f,alpha};
551 }
552 }
553 else m->UseTexture()=false;
554
555 auto normal=loadRef(sm,aiTextureType_NORMAL_CAMERA);
556 if(!normal)normal=loadRef(sm,aiTextureType_NORMALS);
557 m->SetNormalTexture(normal);
558
559 auto metallicMap=loadRef(sm,aiTextureType_METALNESS);
560 auto roughnessMap=loadRef(sm,aiTextureType_DIFFUSE_ROUGHNESS);
561 m->SetMetallicTexture(metallicMap);
562 m->SetRoughnessTexture(roughnessMap);
563
564 const bool isFBX=(source.extension()==".fbx" || source.extension()==".FBX");
565 if(isFBX)
566 {
567 // Mixamo FBX materials are legacy/Phong rather than metallic-
568 // roughness PBR. They should not become metallic simply because
569 // Assimp exposes a converted scalar property.
570 if(!metallicMap) m->Metallic()=0.0f;
571
572 // Convert legacy Phong shininess to a sensible PBR roughness.
573 // If there is no shininess information, use a neutral cloth/skin
574 // default instead of trusting an importer-generated PBR factor.
575 if(!roughnessMap)
576 {
577 ai_real shininess=0.0f;
578 if(aiGetMaterialFloat(sm,AI_MATKEY_SHININESS,&shininess)==AI_SUCCESS &&
579 shininess>0.0f)
580 {
581 m->Roughness()=std::clamp(
582 std::sqrt(2.0f/(static_cast<float>(shininess)+2.0f)),
583 0.18f,0.9f);
584 }
585 else
586 {
587 m->Roughness()=0.65f;
588 }
589 }
590 }
591
592 auto ao=loadRef(sm,aiTextureType_AMBIENT_OCCLUSION);
593 // LIGHTMAP is not a reliable AO semantic for legacy FBX and can
594 // incorrectly blacken Mixamo materials.
595 if(!ao && !isFBX) ao=loadRef(sm,aiTextureType_LIGHTMAP);
596 m->SetAOTexture(ao);
597 m->SetEmissiveTexture(loadRef(sm,aiTextureType_EMISSIVE));
598
599 aiString nm; std::string name="Material_"+std::to_string(i);
600 if(sm->Get(AI_MATKEY_NAME,nm)==AI_SUCCESS && nm.length>0)name=nm.C_Str();
601 for(char& ch:name)if(ch=='/'||ch=='\\'||ch==':'||ch=='*'||ch=='?'||ch=='"'||ch=='<'||ch=='>'||ch=='|')ch='_';
602 auto mp=MakeUniqueDestination(s_AssetsDirectory/"Materials",
603 imported.stem().string()+"_"+name+".nojobmat");
604 AssetRegistry r(s_AssetsDirectory);r.Load();
606 materials.push_back(m);
607 }
608 return materials;
609 }
610
611 std::shared_ptr<Mesh> AssetManager::LoadMesh(const std::filesystem::path& path)
612 {
613 auto a=path.is_absolute()?path:s_ProjectRoot/path;a=std::filesystem::absolute(a).lexically_normal();auto key=a.generic_string();
614 if(auto it=s_MeshCache.find(key);it!=s_MeshCache.end())if(auto m=it->second.lock())return m;
615 auto m=Mesh::LoadModel(a);s_MeshCache[key]=m;s_MeshPaths[m.get()]=ToProjectRelative(a);return m;
616 }
617 std::filesystem::path AssetManager::GetMeshPath(const std::shared_ptr<Mesh>& m){if(!m)return{};auto i=s_MeshPaths.find(m.get());return i==s_MeshPaths.end()?std::filesystem::path{}:i->second;}
618
619 std::shared_ptr<Texture2D> AssetManager::LoadTexture(
620 const std::filesystem::path& path)
621 {
622 std::filesystem::path absolutePath = path;
623
624 if (absolutePath.is_relative())
625 absolutePath = s_ProjectRoot / absolutePath;
626
627 absolutePath =
628 std::filesystem::absolute(absolutePath).lexically_normal();
629
630 const std::string key = absolutePath.generic_string();
631
632 if (const auto found = s_TextureCache.find(key);
633 found != s_TextureCache.end())
634 {
635 if (auto cached = found->second.lock())
636 return cached;
637 }
638
639 auto texture =
640 Texture2D::Create(absolutePath.string());
641
642 s_TextureCache[key] = texture;
643 s_TexturePaths[texture.get()] = ToProjectRelative(absolutePath);
644 return texture;
645 }
646
647
648 std::filesystem::path AssetManager::GetTexturePath(
649 const std::shared_ptr<Texture2D>& texture)
650 {
651 if (!texture)
652 return {};
653
654 const auto found = s_TexturePaths.find(texture.get());
655 if (found == s_TexturePaths.end())
656 return {};
657
658 return found->second;
659 }
660
661 std::filesystem::path AssetManager::ToProjectRelative(
662 const std::filesystem::path& path)
663 {
664 if (s_ProjectRoot.empty())
665 return {};
666
667 std::error_code error;
668 auto relative =
669 std::filesystem::relative(path, s_ProjectRoot, error);
670
671 if (error || relative.empty())
672 return {};
673
674 // Paths outside the project start with "..".
675 const auto text = relative.generic_string();
676 if (text == ".." || text.rfind("../", 0) == 0)
677 return {};
678
679 return relative.lexically_normal();
680 }
681}
AssetManager declarations for the Asset subsystem.
AssetRegistry declarations for the Asset Management subsystem.
Log declarations for the Core subsystem.
Material declarations for the Rendering subsystem.
MaterialSerializer declarations for the Asset Management subsystem.
Mesh declarations for the Rendering subsystem.
Shader declarations for the Rendering subsystem.
Texture declarations for the Rendering subsystem.
static const std::filesystem::path & GetProjectRoot()
static std::filesystem::path ToProjectRelative(const std::filesystem::path &path)
static std::filesystem::path GetTexturePath(const std::shared_ptr< Texture2D > &texture)
static std::filesystem::path ImportTexture(const std::filesystem::path &sourcePath)
static std::shared_ptr< Mesh > LoadMesh(const std::filesystem::path &path)
static std::shared_ptr< Texture2D > LoadTexture(const std::filesystem::path &path)
static const std::filesystem::path & GetAssetsDirectory()
static std::filesystem::path GetMeshPath(const std::shared_ptr< Mesh > &mesh)
static std::vector< std::shared_ptr< Material > > ImportModelMaterials(const std::filesystem::path &modelPath, const std::shared_ptr< Shader > &shader)
static void Init(const std::filesystem::path &projectRoot)
static std::shared_ptr< Material > ImportModelMaterial(const std::filesystem::path &modelPath, const std::shared_ptr< Shader > &shader)
static std::filesystem::path ImportModel(const std::filesystem::path &sourcePath)
static std::filesystem::path ResolveProjectPath(const std::filesystem::path &path)
AssetHandle Register(const std::filesystem::path &path, AssetType type=AssetType::Unknown)
static void Warn(std::string_view message)
Definition Log.h:18
static bool Save(const Material &, const std::filesystem::path &, const AssetRegistry &)
static std::shared_ptr< Mesh > LoadModel(const std::filesystem::path &path)
Definition Mesh.cpp:73
static std::shared_ptr< Texture2D > Create(const std::string &path)
Definition Texture.cpp:12