AssetDatabase.cpp 14 KB

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