AssetDatabase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. {
  41. SubscribeToEvent(E_LOADFAILED, ATOMIC_HANDLER(AssetDatabase, HandleResourceLoadFailed));
  42. SubscribeToEvent(E_PROJECTLOADED, ATOMIC_HANDLER(AssetDatabase, HandleProjectLoaded));
  43. SubscribeToEvent(E_PROJECTUNLOADED, ATOMIC_HANDLER(AssetDatabase, HandleProjectUnloaded));
  44. }
  45. AssetDatabase::~AssetDatabase()
  46. {
  47. }
  48. String AssetDatabase::GetCachePath()
  49. {
  50. if (project_.Null())
  51. return String::EMPTY;
  52. return project_->GetProjectPath() + "Cache/";
  53. }
  54. String AssetDatabase::GenerateAssetGUID()
  55. {
  56. Time* time = GetSubsystem<Time>();
  57. while (true)
  58. {
  59. Poco::MD5Engine md5;
  60. PODVector<unsigned> data;
  61. for (unsigned i = 0; i < 16; i++)
  62. {
  63. data.Push(time->GetTimeSinceEpoch() + Rand());
  64. }
  65. md5.update(&data[0], data.Size() * sizeof(unsigned));
  66. String guid = Poco::MD5Engine::digestToHex(md5.digest()).c_str();
  67. if (!usedGUID_.Contains(guid))
  68. {
  69. RegisterGUID(guid);
  70. return guid;
  71. }
  72. }
  73. assert(0);
  74. return "";
  75. }
  76. void AssetDatabase::RegisterGUID(const String& guid)
  77. {
  78. if (usedGUID_.Contains(guid))
  79. {
  80. assert(0);
  81. }
  82. usedGUID_.Push(guid);
  83. }
  84. void AssetDatabase::ReadImportConfig()
  85. {
  86. ImportConfig::Clear();
  87. ToolSystem* tsystem = GetSubsystem<ToolSystem>();
  88. Project* project = tsystem->GetProject();
  89. String projectPath = project->GetProjectPath();
  90. String filename = projectPath + "Settings/Import.json";
  91. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  92. if (!fileSystem->FileExists(filename))
  93. return;
  94. ImportConfig::LoadFromFile(context_, filename);
  95. }
  96. void AssetDatabase::Import(const String& path)
  97. {
  98. FileSystem* fs = GetSubsystem<FileSystem>();
  99. // nothing for now
  100. if (fs->DirExists(path))
  101. return;
  102. }
  103. Asset* AssetDatabase::GetAssetByCachePath(const String& cachePath)
  104. {
  105. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  106. // This is the GUID
  107. String cacheFilename = GetFileName(cachePath).ToLower();
  108. while (itr != assets_.End())
  109. {
  110. if ((*itr)->GetGUID().ToLower() == cacheFilename)
  111. return *itr;
  112. itr++;
  113. }
  114. return 0;
  115. }
  116. Asset* AssetDatabase::GetAssetByGUID(const String& guid)
  117. {
  118. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  119. while (itr != assets_.End())
  120. {
  121. if (guid == (*itr)->GetGUID())
  122. return *itr;
  123. itr++;
  124. }
  125. return 0;
  126. }
  127. Asset* AssetDatabase::GetAssetByPath(const String& path)
  128. {
  129. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  130. while (itr != assets_.End())
  131. {
  132. if (path == (*itr)->GetPath())
  133. return *itr;
  134. itr++;
  135. }
  136. return 0;
  137. }
  138. void AssetDatabase::PruneOrphanedDotAssetFiles()
  139. {
  140. if (project_.Null())
  141. {
  142. ATOMIC_LOGDEBUG("AssetDatabase::PruneOrphanedDotAssetFiles - called without project loaded");
  143. return;
  144. }
  145. FileSystem* fs = GetSubsystem<FileSystem>();
  146. const String& resourcePath = project_->GetResourcePath();
  147. Vector<String> allResults;
  148. fs->ScanDir(allResults, resourcePath, "*.asset", SCAN_FILES, true);
  149. for (unsigned i = 0; i < allResults.Size(); i++)
  150. {
  151. String dotAssetFilename = resourcePath + allResults[i];
  152. String assetFilename = ReplaceExtension(dotAssetFilename, "");
  153. // remove orphaned asset files
  154. if (!fs->FileExists(assetFilename) && !fs->DirExists(assetFilename))
  155. {
  156. ATOMIC_LOGINFOF("Removing orphaned asset file: %s", dotAssetFilename.CString());
  157. fs->Delete(dotAssetFilename);
  158. }
  159. }
  160. }
  161. String AssetDatabase::GetDotAssetFilename(const String& path)
  162. {
  163. FileSystem* fs = GetSubsystem<FileSystem>();
  164. String assetFilename = path + ".asset";
  165. if (fs->DirExists(path)) {
  166. assetFilename = RemoveTrailingSlash(path) + ".asset";
  167. }
  168. return assetFilename;
  169. }
  170. void AssetDatabase::AddAsset(SharedPtr<Asset>& asset, bool newAsset)
  171. {
  172. assert(asset->GetGUID().Length());
  173. assert(!GetAssetByGUID(asset->GetGUID()));
  174. assets_.Push(asset);
  175. // set to the current timestamp
  176. asset->UpdateFileTimestamp();
  177. VariantMap eventData;
  178. if (newAsset)
  179. {
  180. eventData[AssetNew::P_GUID] = asset->GetGUID();
  181. SendEvent(E_ASSETNEW, eventData);
  182. }
  183. eventData[ResourceAdded::P_GUID] = asset->GetGUID();
  184. SendEvent(E_RESOURCEADDED, eventData);
  185. }
  186. void AssetDatabase::DeleteAsset(Asset* asset)
  187. {
  188. SharedPtr<Asset> assetPtr(asset);
  189. List<SharedPtr<Asset>>::Iterator itr = assets_.Find(assetPtr);
  190. if (itr == assets_.End())
  191. return;
  192. assets_.Erase(itr);
  193. const String& resourcePath = asset->GetPath();
  194. FileSystem* fs = GetSubsystem<FileSystem>();
  195. if (fs->DirExists(resourcePath))
  196. {
  197. fs->RemoveDir(resourcePath, true);
  198. }
  199. else if (fs->FileExists(resourcePath))
  200. {
  201. fs->Delete(resourcePath);
  202. }
  203. String dotAsset = resourcePath + ".asset";
  204. if (fs->FileExists(dotAsset))
  205. {
  206. fs->Delete(dotAsset);
  207. }
  208. VariantMap eventData;
  209. eventData[ResourceRemoved::P_GUID] = asset->GetGUID();
  210. SendEvent(E_RESOURCEREMOVED, eventData);
  211. }
  212. bool AssetDatabase::ImportDirtyAssets()
  213. {
  214. PODVector<Asset*> assets;
  215. GetDirtyAssets(assets);
  216. for (unsigned i = 0; i < assets.Size(); i++)
  217. {
  218. assets[i]->Import();
  219. assets[i]->Save();
  220. assets[i]->dirty_ = false;
  221. assets[i]->UpdateFileTimestamp();
  222. }
  223. return assets.Size() != 0;
  224. }
  225. void AssetDatabase::PreloadAssets()
  226. {
  227. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  228. while (itr != assets_.End())
  229. {
  230. (*itr)->Preload();
  231. itr++;
  232. }
  233. }
  234. void AssetDatabase::Scan()
  235. {
  236. if (!assetScanDepth_)
  237. {
  238. SendEvent(E_ASSETSCANBEGIN);
  239. }
  240. assetScanDepth_++;
  241. PruneOrphanedDotAssetFiles();
  242. FileSystem* fs = GetSubsystem<FileSystem>();
  243. const String& resourcePath = project_->GetResourcePath();
  244. Vector<String> allResults;
  245. fs->ScanDir(allResults, resourcePath, "", SCAN_FILES | SCAN_DIRS, true);
  246. Vector<String> filteredResults;
  247. filteredResults.Push(RemoveTrailingSlash(resourcePath));
  248. for (unsigned i = 0; i < allResults.Size(); i++)
  249. {
  250. allResults[i] = resourcePath + allResults[i];
  251. const String& path = allResults[i];
  252. if (path.StartsWith(".") || path.EndsWith("."))
  253. continue;
  254. String ext = GetExtension(path);
  255. if (ext == ".asset")
  256. continue;
  257. filteredResults.Push(path);
  258. }
  259. for (unsigned i = 0; i < filteredResults.Size(); i++)
  260. {
  261. const String& path = filteredResults[i];
  262. String dotAssetFilename = GetDotAssetFilename(path);
  263. if (!fs->FileExists(dotAssetFilename))
  264. {
  265. // new asset
  266. SharedPtr<Asset> asset(new Asset(context_));
  267. if (asset->SetPath(path))
  268. {
  269. AddAsset(asset, true);
  270. }
  271. }
  272. else
  273. {
  274. SharedPtr<File> file(new File(context_, dotAssetFilename));
  275. SharedPtr<JSONFile> json(new JSONFile(context_));
  276. json->Load(*file);
  277. file->Close();
  278. JSONValue root = json->GetRoot();
  279. assert(root.Get("version").GetInt() == ASSET_VERSION);
  280. String guid = root.Get("guid").GetString();
  281. if (!GetAssetByGUID(guid))
  282. {
  283. SharedPtr<Asset> asset(new Asset(context_));
  284. asset->SetPath(path);
  285. AddAsset(asset);
  286. }
  287. }
  288. }
  289. PreloadAssets();
  290. if (ImportDirtyAssets())
  291. Scan();
  292. assetScanDepth_--;
  293. if (!assetScanDepth_)
  294. {
  295. SendEvent(E_ASSETSCANEND);
  296. }
  297. }
  298. void AssetDatabase::GetFolderAssets(String folder, PODVector<Asset*>& assets) const
  299. {
  300. if (project_.Null())
  301. return;
  302. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  303. if (!folder.Length())
  304. {
  305. folder = project_->GetResourcePath();
  306. }
  307. folder = AddTrailingSlash(folder);
  308. while (itr != assets_.End())
  309. {
  310. String path = GetPath((*itr)->GetPath());
  311. if (path == folder)
  312. assets.Push(*itr);
  313. itr++;
  314. }
  315. }
  316. void AssetDatabase::GetAssetsByImporterType(StringHash type, const String &resourceType, PODVector<Asset*>& assets) const
  317. {
  318. assets.Clear();
  319. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  320. while (itr != assets_.End())
  321. {
  322. Asset* asset = *itr;
  323. if (asset->GetImporterType() == type)
  324. assets.Push(asset);
  325. itr++;
  326. }
  327. }
  328. void AssetDatabase::GetDirtyAssets(PODVector<Asset*>& assets)
  329. {
  330. assets.Clear();
  331. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  332. while (itr != assets_.End())
  333. {
  334. if ((*itr)->IsDirty())
  335. assets.Push(*itr);
  336. itr++;
  337. }
  338. }
  339. void AssetDatabase::HandleProjectLoaded(StringHash eventType, VariantMap& eventData)
  340. {
  341. project_ = GetSubsystem<ToolSystem>()->GetProject();
  342. ReadImportConfig();
  343. FileSystem* fs = GetSubsystem<FileSystem>();
  344. if (!fs->DirExists(GetCachePath()))
  345. fs->CreateDir(GetCachePath());
  346. ResourceCache* cache = GetSubsystem<ResourceCache>();
  347. cache->AddResourceDir(GetCachePath());
  348. Scan();
  349. SubscribeToEvent(E_FILECHANGED, ATOMIC_HANDLER(AssetDatabase, HandleFileChanged));
  350. }
  351. void AssetDatabase::HandleProjectUnloaded(StringHash eventType, VariantMap& eventData)
  352. {
  353. ResourceCache* cache = GetSubsystem<ResourceCache>();
  354. cache->RemoveResourceDir(GetCachePath());
  355. assets_.Clear();
  356. usedGUID_.Clear();
  357. assetImportErrorTimes_.Clear();
  358. project_ = 0;
  359. UnsubscribeFromEvent(E_FILECHANGED);
  360. }
  361. void AssetDatabase::HandleResourceLoadFailed(StringHash eventType, VariantMap& eventData)
  362. {
  363. if (project_.Null())
  364. return;
  365. String path = eventData[LoadFailed::P_RESOURCENAME].GetString();
  366. Asset* asset = GetAssetByPath(path);
  367. if (!asset)
  368. asset = GetAssetByPath(project_->GetResourcePath() + path);
  369. if (!asset)
  370. return;
  371. Time* time = GetSubsystem<Time>();
  372. unsigned ctime = time->GetSystemTime();
  373. // if less than 5 seconds since last report, stifle report
  374. if (assetImportErrorTimes_.Contains(asset->guid_))
  375. if (ctime - assetImportErrorTimes_[asset->guid_] < 5000)
  376. return;
  377. assetImportErrorTimes_[asset->guid_] = ctime;
  378. VariantMap evData;
  379. evData[AssetImportError::P_PATH] = asset->path_;
  380. evData[AssetImportError::P_GUID] = asset->guid_;
  381. evData[AssetImportError::P_ERROR] = ToString("Asset %s Failed to Load", asset->path_.CString());
  382. SendEvent(E_ASSETIMPORTERROR, evData);
  383. }
  384. void AssetDatabase::HandleFileChanged(StringHash eventType, VariantMap& eventData)
  385. {
  386. using namespace FileChanged;
  387. const String& fullPath = eventData[P_FILENAME].GetString();
  388. FileSystem* fs = GetSubsystem<FileSystem>();
  389. String pathName, fileName, ext;
  390. SplitPath(fullPath, pathName, fileName, ext);
  391. // ignore changes in the Cache resource dir
  392. if (fullPath == GetCachePath() || pathName.StartsWith(GetCachePath()))
  393. return;
  394. // don't care about directories and asset file changes
  395. if (fs->DirExists(fullPath) || ext == ".asset")
  396. return;
  397. Asset* asset = GetAssetByPath(fullPath);
  398. if (!asset && fs->FileExists(fullPath))
  399. {
  400. Scan();
  401. return;
  402. }
  403. if (asset)
  404. {
  405. if(!fs->Exists(fullPath))
  406. {
  407. DeleteAsset(asset);
  408. }
  409. else
  410. {
  411. if (asset->GetFileTimestamp() != fs->GetLastModifiedTime(asset->GetPath()))
  412. {
  413. asset->SetDirty(true);
  414. Scan();
  415. }
  416. }
  417. }
  418. }
  419. String AssetDatabase::GetResourceImporterName(const String& resourceTypeName)
  420. {
  421. // TODO: have resource type register themselves
  422. if (resourceTypeToImporterType_.Empty())
  423. {
  424. resourceTypeToImporterType_["Sound"] = "AudioImporter";
  425. resourceTypeToImporterType_["Model"] = "ModelImporter";
  426. resourceTypeToImporterType_["Material"] = "MaterialImporter";
  427. resourceTypeToImporterType_["Texture2D"] = "TextureImporter";
  428. resourceTypeToImporterType_["Sprite2D"] = "TextureImporter";
  429. resourceTypeToImporterType_["Image"] = "TextureImporter";
  430. resourceTypeToImporterType_["AnimatedSprite2D"] = "SpriterImporter";
  431. resourceTypeToImporterType_["JSComponentFile"] = "JavascriptImporter";
  432. resourceTypeToImporterType_["JSONFile"] = "JSONImporter";
  433. resourceTypeToImporterType_["ParticleEffect2D"] = "PEXImporter";
  434. resourceTypeToImporterType_["ParticleEffect"] = "ParticleEffectImporter";
  435. resourceTypeToImporterType_["Animation"] = "ModelImporter";
  436. resourceTypeToImporterType_["CSComponentAssembly"] = "NETAssemblyImporter";
  437. }
  438. if (!resourceTypeToImporterType_.Contains(resourceTypeName))
  439. return String::EMPTY;
  440. return resourceTypeToImporterType_[resourceTypeName];
  441. }
  442. void AssetDatabase::ReimportAllAssets()
  443. {
  444. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  445. while (itr != assets_.End())
  446. {
  447. (*itr)->SetDirty(true);
  448. itr++;
  449. }
  450. Scan();
  451. }
  452. void AssetDatabase::ReimportAllAssetsInDirectory(const String& directoryPath)
  453. {
  454. List<SharedPtr<Asset>>::ConstIterator itr = assets_.Begin();
  455. while (itr != assets_.End())
  456. {
  457. if ((*itr)->GetPath().StartsWith(directoryPath))
  458. {
  459. (*itr)->SetDirty(true);
  460. }
  461. itr++;
  462. }
  463. Scan();
  464. }
  465. }