AssetDatabase.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. //
  2. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Poco/MD5Engine.h>
  23. #include <Atomic/IO/Log.h>
  24. #include <Atomic/IO/File.h>
  25. #include <Atomic/IO/FileSystem.h>
  26. #include <Atomic/Math/Random.h>
  27. #include <Atomic/Resource/ResourceEvents.h>
  28. #include <Atomic/Resource/ResourceCache.h>
  29. #include "../Import/ImportConfig.h"
  30. #include "../ToolEvents.h"
  31. #include "../ToolSystem.h"
  32. #include "../Project/Project.h"
  33. #include "../Project/ProjectEvents.h"
  34. #include "AssetEvents.h"
  35. #include "AssetDatabase.h"
  36. namespace ToolCore
  37. {
  38. AssetDatabase::AssetDatabase(Context* context) : Object(context),
  39. assetScanDepth_(0),
  40. assetScanImport_(false)
  41. {
  42. SubscribeToEvent(E_LOADFAILED, ATOMIC_HANDLER(AssetDatabase, HandleResourceLoadFailed));
  43. SubscribeToEvent(E_PROJECTLOADED, ATOMIC_HANDLER(AssetDatabase, HandleProjectLoaded));
  44. SubscribeToEvent(E_PROJECTUNLOADED, ATOMIC_HANDLER(AssetDatabase, HandleProjectUnloaded));
  45. }
  46. AssetDatabase::~AssetDatabase()
  47. {
  48. }
  49. String AssetDatabase::GetCachePath()
  50. {
  51. if (project_.Null())
  52. return String::EMPTY;
  53. return project_->GetProjectPath() + "Cache/";
  54. }
  55. String AssetDatabase::GenerateAssetGUID()
  56. {
  57. Time* time = GetSubsystem<Time>();
  58. while (true)
  59. {
  60. Poco::MD5Engine md5;
  61. PODVector<unsigned> data;
  62. for (unsigned i = 0; i < 16; i++)
  63. {
  64. data.Push(time->GetTimeSinceEpoch() + Rand());
  65. }
  66. md5.update(&data[0], data.Size() * sizeof(unsigned));
  67. String guid = Poco::MD5Engine::digestToHex(md5.digest()).c_str();
  68. if (!usedGUID_.Contains(guid))
  69. {
  70. RegisterGUID(guid);
  71. return guid;
  72. }
  73. }
  74. assert(0);
  75. return "";
  76. }
  77. void AssetDatabase::RegisterGUID(const String& guid)
  78. {
  79. if (usedGUID_.Contains(guid))
  80. {
  81. assert(0);
  82. }
  83. usedGUID_.Push(guid);
  84. }
  85. void AssetDatabase::ReadImportConfig()
  86. {
  87. ImportConfig::Clear();
  88. ToolSystem* tsystem = GetSubsystem<ToolSystem>();
  89. Project* project = tsystem->GetProject();
  90. String projectPath = project->GetProjectPath();
  91. String filename = projectPath + "Settings/Import.json";
  92. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  93. if (!fileSystem->FileExists(filename))
  94. return;
  95. ImportConfig::LoadFromFile(context_, filename);
  96. }
  97. void AssetDatabase::Import(const String& path)
  98. {
  99. FileSystem* fs = GetSubsystem<FileSystem>();
  100. // nothing for now
  101. if (fs->DirExists(path))
  102. return;
  103. }
  104. Asset* AssetDatabase::GetAssetByCachePath(const String& cachePath)
  105. {
  106. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  107. // This is the GUID
  108. String cacheFilename = GetFileName(cachePath).ToLower();
  109. while (itr != assets_.End())
  110. {
  111. if ((*itr)->GetGUID().ToLower() == cacheFilename)
  112. return *itr;
  113. itr++;
  114. }
  115. return 0;
  116. }
  117. Asset* AssetDatabase::GetAssetByGUID(const String& guid)
  118. {
  119. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  120. while (itr != assets_.End())
  121. {
  122. if (guid == (*itr)->GetGUID())
  123. return *itr;
  124. itr++;
  125. }
  126. return 0;
  127. }
  128. Asset* AssetDatabase::GetAssetByPath(const String& path)
  129. {
  130. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  131. while (itr != assets_.End())
  132. {
  133. if (path == (*itr)->GetPath())
  134. return *itr;
  135. itr++;
  136. }
  137. return 0;
  138. }
  139. void AssetDatabase::PruneOrphanedDotAssetFiles()
  140. {
  141. if (project_.Null())
  142. {
  143. ATOMIC_LOGDEBUG("AssetDatabase::PruneOrphanedDotAssetFiles - called without project loaded");
  144. return;
  145. }
  146. FileSystem* fs = GetSubsystem<FileSystem>();
  147. const String& resourcePath = project_->GetResourcePath();
  148. Vector<String> allResults;
  149. fs->ScanDir(allResults, resourcePath, "*.asset", SCAN_FILES, true);
  150. for (unsigned i = 0; i < allResults.Size(); i++)
  151. {
  152. String dotAssetFilename = resourcePath + allResults[i];
  153. String assetFilename = ReplaceExtension(dotAssetFilename, "");
  154. // remove orphaned asset files
  155. if (!fs->FileExists(assetFilename) && !fs->DirExists(assetFilename))
  156. {
  157. ATOMIC_LOGINFOF("Removing orphaned asset file: %s", dotAssetFilename.CString());
  158. fs->Delete(dotAssetFilename);
  159. }
  160. }
  161. }
  162. String AssetDatabase::GetDotAssetFilename(const String& path)
  163. {
  164. FileSystem* fs = GetSubsystem<FileSystem>();
  165. String assetFilename = path + ".asset";
  166. if (fs->DirExists(path)) {
  167. assetFilename = RemoveTrailingSlash(path) + ".asset";
  168. }
  169. return assetFilename;
  170. }
  171. void AssetDatabase::AddAsset(SharedPtr<Asset>& asset, bool newAsset)
  172. {
  173. assert(asset->GetGUID().Length());
  174. assert(!GetAssetByGUID(asset->GetGUID()));
  175. assets_.Push(asset);
  176. // set to the current timestamp
  177. asset->UpdateFileTimestamp();
  178. VariantMap eventData;
  179. if (newAsset)
  180. {
  181. eventData[AssetNew::P_GUID] = asset->GetGUID();
  182. SendEvent(E_ASSETNEW, eventData);
  183. }
  184. eventData[ResourceAdded::P_GUID] = asset->GetGUID();
  185. SendEvent(E_RESOURCEADDED, eventData);
  186. }
  187. void AssetDatabase::DeleteAsset(Asset* asset)
  188. {
  189. SharedPtr<Asset> assetPtr(asset);
  190. List<SharedPtr<Asset>>::Iterator itr = assets_.Find(assetPtr);
  191. if (itr == assets_.End())
  192. return;
  193. assets_.Erase(itr);
  194. const String& resourcePath = asset->GetPath();
  195. FileSystem* fs = GetSubsystem<FileSystem>();
  196. if (fs->DirExists(resourcePath))
  197. {
  198. fs->RemoveDir(resourcePath, true);
  199. }
  200. else if (fs->FileExists(resourcePath))
  201. {
  202. fs->Delete(resourcePath);
  203. }
  204. String dotAsset = resourcePath + ".asset";
  205. if (fs->FileExists(dotAsset))
  206. {
  207. fs->Delete(dotAsset);
  208. }
  209. VariantMap eventData;
  210. eventData[ResourceRemoved::P_GUID] = asset->GetGUID();
  211. SendEvent(E_RESOURCEREMOVED, eventData);
  212. }
  213. bool AssetDatabase::ImportDirtyAssets()
  214. {
  215. PODVector<Asset*> assets;
  216. GetDirtyAssets(assets);
  217. for (unsigned i = 0; i < assets.Size(); i++)
  218. {
  219. assetScanImport_ = true;
  220. assets[i]->Import();
  221. assets[i]->Save();
  222. assets[i]->dirty_ = false;
  223. assets[i]->UpdateFileTimestamp();
  224. }
  225. return assets.Size() != 0;
  226. }
  227. void AssetDatabase::PreloadAssets()
  228. {
  229. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  230. while (itr != assets_.End())
  231. {
  232. (*itr)->Preload();
  233. itr++;
  234. }
  235. }
  236. void AssetDatabase::UpdateAssetCacheMap()
  237. {
  238. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  239. if (project_.Null())
  240. return;
  241. bool gen = assetScanImport_;
  242. assetScanImport_ = false;
  243. String cachepath = project_->GetProjectPath() + "Cache/__atomic_ResourceCacheMap.json";
  244. if (!gen && !fileSystem->FileExists(cachepath))
  245. gen = true;
  246. if (!gen)
  247. return;
  248. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  249. HashMap<String, String> assetMap;
  250. JSONValue jAssetMap;
  251. while (itr != assets_.End())
  252. {
  253. assetMap.Clear();
  254. (*itr)->GetAssetCacheMap(assetMap);
  255. HashMap<String, String>::ConstIterator amitr = assetMap.Begin();
  256. while (amitr != assetMap.End())
  257. {
  258. jAssetMap.Set(amitr->first_, amitr->second_);
  259. amitr++;
  260. }
  261. itr++;
  262. }
  263. SharedPtr<File> file(new File(context_, cachepath, FILE_WRITE));
  264. if (!file->IsOpen())
  265. {
  266. ATOMIC_LOGERRORF("Unable to update ResourceCacheMap: %s", cachepath.CString());
  267. return;
  268. }
  269. SharedPtr<JSONFile> jsonFile(new JSONFile(context_));
  270. jsonFile->GetRoot().Set("assetMap", jAssetMap);
  271. jsonFile->Save(*file);
  272. }
  273. void AssetDatabase::Scan()
  274. {
  275. if (!assetScanDepth_)
  276. {
  277. assert(!assetScanImport_);
  278. SendEvent(E_ASSETSCANBEGIN);
  279. }
  280. assetScanDepth_++;
  281. PruneOrphanedDotAssetFiles();
  282. FileSystem* fs = GetSubsystem<FileSystem>();
  283. const String& resourcePath = project_->GetResourcePath();
  284. Vector<String> allResults;
  285. fs->ScanDir(allResults, resourcePath, "", SCAN_FILES | SCAN_DIRS, true);
  286. Vector<String> filteredResults;
  287. filteredResults.Push(RemoveTrailingSlash(resourcePath));
  288. for (unsigned i = 0; i < allResults.Size(); i++)
  289. {
  290. allResults[i] = resourcePath + allResults[i];
  291. const String& path = allResults[i];
  292. if (path.StartsWith(".") || path.EndsWith("."))
  293. continue;
  294. String ext = GetExtension(path);
  295. if (ext == ".asset")
  296. continue;
  297. filteredResults.Push(path);
  298. }
  299. for (unsigned i = 0; i < filteredResults.Size(); i++)
  300. {
  301. const String& path = filteredResults[i];
  302. String dotAssetFilename = GetDotAssetFilename(path);
  303. if (!fs->FileExists(dotAssetFilename))
  304. {
  305. // new asset
  306. SharedPtr<Asset> asset(new Asset(context_));
  307. if (asset->SetPath(path))
  308. {
  309. AddAsset(asset, true);
  310. }
  311. }
  312. else
  313. {
  314. SharedPtr<File> file(new File(context_, dotAssetFilename));
  315. SharedPtr<JSONFile> json(new JSONFile(context_));
  316. json->Load(*file);
  317. file->Close();
  318. JSONValue root = json->GetRoot();
  319. assert(root.Get("version").GetInt() == ASSET_VERSION);
  320. String guid = root.Get("guid").GetString();
  321. if (!GetAssetByGUID(guid))
  322. {
  323. SharedPtr<Asset> asset(new Asset(context_));
  324. asset->SetPath(path);
  325. AddAsset(asset);
  326. }
  327. }
  328. }
  329. PreloadAssets();
  330. if (ImportDirtyAssets())
  331. Scan();
  332. assetScanDepth_--;
  333. if (!assetScanDepth_)
  334. {
  335. UpdateAssetCacheMap();
  336. SendEvent(E_ASSETSCANEND);
  337. }
  338. }
  339. void AssetDatabase::GetFolderAssets(String folder, PODVector<Asset*>& assets) const
  340. {
  341. if (project_.Null())
  342. return;
  343. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  344. if (!folder.Length())
  345. {
  346. folder = project_->GetResourcePath();
  347. }
  348. folder = AddTrailingSlash(folder);
  349. while (itr != assets_.End())
  350. {
  351. String path = GetPath((*itr)->GetPath());
  352. if (path == folder)
  353. assets.Push(*itr);
  354. itr++;
  355. }
  356. }
  357. void AssetDatabase::GetAssetsByImporterType(StringHash type, const String &resourceType, PODVector<Asset*>& assets) const
  358. {
  359. assets.Clear();
  360. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  361. while (itr != assets_.End())
  362. {
  363. Asset* asset = *itr;
  364. if (asset->GetImporterType() == type)
  365. assets.Push(asset);
  366. itr++;
  367. }
  368. }
  369. void AssetDatabase::GetDirtyAssets(PODVector<Asset*>& assets)
  370. {
  371. assets.Clear();
  372. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  373. while (itr != assets_.End())
  374. {
  375. if ((*itr)->IsDirty())
  376. assets.Push(*itr);
  377. itr++;
  378. }
  379. }
  380. void AssetDatabase::HandleProjectLoaded(StringHash eventType, VariantMap& eventData)
  381. {
  382. project_ = GetSubsystem<ToolSystem>()->GetProject();
  383. ReadImportConfig();
  384. FileSystem* fs = GetSubsystem<FileSystem>();
  385. if (!fs->DirExists(GetCachePath()))
  386. fs->CreateDir(GetCachePath());
  387. ResourceCache* cache = GetSubsystem<ResourceCache>();
  388. cache->AddResourceDir(GetCachePath());
  389. Scan();
  390. SubscribeToEvent(E_FILECHANGED, ATOMIC_HANDLER(AssetDatabase, HandleFileChanged));
  391. }
  392. void AssetDatabase::HandleProjectUnloaded(StringHash eventType, VariantMap& eventData)
  393. {
  394. ResourceCache* cache = GetSubsystem<ResourceCache>();
  395. cache->RemoveResourceDir(GetCachePath());
  396. assets_.Clear();
  397. usedGUID_.Clear();
  398. assetImportErrorTimes_.Clear();
  399. project_ = 0;
  400. UnsubscribeFromEvent(E_FILECHANGED);
  401. }
  402. void AssetDatabase::HandleResourceLoadFailed(StringHash eventType, VariantMap& eventData)
  403. {
  404. if (project_.Null())
  405. return;
  406. String path = eventData[LoadFailed::P_RESOURCENAME].GetString();
  407. Asset* asset = GetAssetByPath(path);
  408. if (!asset)
  409. asset = GetAssetByPath(project_->GetResourcePath() + path);
  410. if (!asset)
  411. return;
  412. Time* time = GetSubsystem<Time>();
  413. unsigned ctime = time->GetSystemTime();
  414. // if less than 5 seconds since last report, stifle report
  415. if (assetImportErrorTimes_.Contains(asset->guid_))
  416. if (ctime - assetImportErrorTimes_[asset->guid_] < 5000)
  417. return;
  418. assetImportErrorTimes_[asset->guid_] = ctime;
  419. VariantMap evData;
  420. evData[AssetImportError::P_PATH] = asset->path_;
  421. evData[AssetImportError::P_GUID] = asset->guid_;
  422. evData[AssetImportError::P_ERROR] = ToString("Asset %s Failed to Load", asset->path_.CString());
  423. SendEvent(E_ASSETIMPORTERROR, evData);
  424. }
  425. void AssetDatabase::HandleFileChanged(StringHash eventType, VariantMap& eventData)
  426. {
  427. using namespace FileChanged;
  428. const String& fullPath = eventData[P_FILENAME].GetString();
  429. FileSystem* fs = GetSubsystem<FileSystem>();
  430. String pathName, fileName, ext;
  431. SplitPath(fullPath, pathName, fileName, ext);
  432. // ignore changes in the Cache resource dir
  433. if (fullPath == GetCachePath() || pathName.StartsWith(GetCachePath()))
  434. return;
  435. // don't care about directories and asset file changes
  436. if (fs->DirExists(fullPath) || ext == ".asset")
  437. return;
  438. Asset* asset = GetAssetByPath(fullPath);
  439. if (!asset && fs->FileExists(fullPath))
  440. {
  441. Scan();
  442. return;
  443. }
  444. if (asset)
  445. {
  446. if(!fs->Exists(fullPath))
  447. {
  448. DeleteAsset(asset);
  449. }
  450. else
  451. {
  452. if (asset->GetFileTimestamp() != fs->GetLastModifiedTime(asset->GetPath()))
  453. {
  454. asset->SetDirty(true);
  455. Scan();
  456. }
  457. }
  458. }
  459. }
  460. String AssetDatabase::GetResourceImporterName(const String& resourceTypeName)
  461. {
  462. // TODO: have resource type register themselves
  463. if (resourceTypeToImporterType_.Empty())
  464. {
  465. resourceTypeToImporterType_["Sound"] = "AudioImporter";
  466. resourceTypeToImporterType_["Model"] = "ModelImporter";
  467. resourceTypeToImporterType_["Material"] = "MaterialImporter";
  468. resourceTypeToImporterType_["Texture2D"] = "TextureImporter";
  469. resourceTypeToImporterType_["Sprite2D"] = "TextureImporter";
  470. resourceTypeToImporterType_["Image"] = "TextureImporter";
  471. resourceTypeToImporterType_["AnimatedSprite2D"] = "SpriterImporter";
  472. resourceTypeToImporterType_["JSComponentFile"] = "JavascriptImporter";
  473. resourceTypeToImporterType_["JSONFile"] = "JSONImporter";
  474. resourceTypeToImporterType_["ParticleEffect2D"] = "PEXImporter";
  475. resourceTypeToImporterType_["ParticleEffect"] = "ParticleEffectImporter";
  476. resourceTypeToImporterType_["Animation"] = "ModelImporter";
  477. resourceTypeToImporterType_["CSComponentAssembly"] = "NETAssemblyImporter";
  478. resourceTypeToImporterType_["TmxFile2D"] = "TMXImporter";
  479. }
  480. if (!resourceTypeToImporterType_.Contains(resourceTypeName))
  481. return String::EMPTY;
  482. return resourceTypeToImporterType_[resourceTypeName];
  483. }
  484. void AssetDatabase::ReimportAllAssets()
  485. {
  486. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  487. while (itr != assets_.End())
  488. {
  489. (*itr)->SetDirty(true);
  490. itr++;
  491. }
  492. Scan();
  493. }
  494. void AssetDatabase::ReimportAllAssetsInDirectory(const String& directoryPath)
  495. {
  496. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  497. while (itr != assets_.End())
  498. {
  499. if ((*itr)->GetPath().StartsWith(directoryPath))
  500. {
  501. (*itr)->SetDirty(true);
  502. }
  503. itr++;
  504. }
  505. Scan();
  506. }
  507. }