AssetDatabase.cpp 15 KB

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