ResourceCache.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  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 "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Core/WorkQueue.h"
  27. #include "../IO/FileSystem.h"
  28. #include "../IO/FileWatcher.h"
  29. #include "../IO/Log.h"
  30. #include "../IO/PackageFile.h"
  31. #include "../Resource/BackgroundLoader.h"
  32. #include "../Resource/Image.h"
  33. #include "../Resource/JSONFile.h"
  34. #include "../Resource/PListFile.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/ResourceEvents.h"
  37. #include "../Resource/XMLFile.h"
  38. #include "../DebugNew.h"
  39. #include <cstdio>
  40. namespace Atomic
  41. {
  42. // ATOMIC BEGIN
  43. const char* PAK_EXTENSION = ".pak";
  44. // ATOMIC END
  45. static const char* checkDirs[] =
  46. {
  47. "Fonts",
  48. "Materials",
  49. "Models",
  50. "Music",
  51. "Objects",
  52. "Particle",
  53. "PostProcess",
  54. "RenderPaths",
  55. "Scenes",
  56. "Scripts",
  57. "Sounds",
  58. "Shaders",
  59. "Techniques",
  60. "Textures",
  61. "UI",
  62. 0
  63. };
  64. static const SharedPtr<Resource> noResource;
  65. ResourceCache::ResourceCache(Context* context) :
  66. Object(context),
  67. autoReloadResources_(false),
  68. returnFailedResources_(false),
  69. searchPackagesFirst_(true),
  70. isRouting_(false),
  71. finishBackgroundResourcesMs_(5)
  72. {
  73. // Register Resource library object factories
  74. RegisterResourceLibrary(context_);
  75. #ifdef ATOMIC_THREADING
  76. // Create resource background loader. Its thread will start on the first background request
  77. backgroundLoader_ = new BackgroundLoader(this);
  78. #endif
  79. // Subscribe BeginFrame for handling directory watchers and background loaded resource finalization
  80. SubscribeToEvent(E_BEGINFRAME, ATOMIC_HANDLER(ResourceCache, HandleBeginFrame));
  81. }
  82. ResourceCache::~ResourceCache()
  83. {
  84. #ifdef ATOMIC_THREADING
  85. // Shut down the background loader first
  86. backgroundLoader_.Reset();
  87. #endif
  88. }
  89. bool ResourceCache::AddResourceDir(const String& pathName, unsigned priority)
  90. {
  91. MutexLock lock(resourceMutex_);
  92. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  93. if (!fileSystem || !fileSystem->DirExists(pathName))
  94. {
  95. ATOMIC_LOGERROR("Could not open directory " + pathName);
  96. return false;
  97. }
  98. // Convert path to absolute
  99. String fixedPath = SanitateResourceDirName(pathName);
  100. // Check that the same path does not already exist
  101. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  102. {
  103. if (!resourceDirs_[i].Compare(fixedPath, false))
  104. return true;
  105. }
  106. if (priority < resourceDirs_.Size())
  107. resourceDirs_.Insert(priority, fixedPath);
  108. else
  109. resourceDirs_.Push(fixedPath);
  110. // If resource auto-reloading active, create a file watcher for the directory
  111. if (autoReloadResources_)
  112. {
  113. SharedPtr<FileWatcher> watcher(new FileWatcher(context_));
  114. watcher->StartWatching(fixedPath, true);
  115. fileWatchers_.Push(watcher);
  116. }
  117. ATOMIC_LOGINFO("Added resource path " + fixedPath);
  118. return true;
  119. }
  120. bool ResourceCache::AddPackageFile(PackageFile* package, unsigned priority)
  121. {
  122. MutexLock lock(resourceMutex_);
  123. // Do not add packages that failed to load
  124. if (!package || !package->GetNumFiles())
  125. {
  126. ATOMIC_LOGERRORF("Could not add package file %s due to load failure", package->GetName().CString());
  127. return false;
  128. }
  129. if (priority < packages_.Size())
  130. packages_.Insert(priority, SharedPtr<PackageFile>(package));
  131. else
  132. packages_.Push(SharedPtr<PackageFile>(package));
  133. ATOMIC_LOGINFO("Added resource package " + package->GetName());
  134. return true;
  135. }
  136. bool ResourceCache::AddPackageFile(const String& fileName, unsigned priority)
  137. {
  138. SharedPtr<PackageFile> package(new PackageFile(context_));
  139. return package->Open(fileName) && AddPackageFile(package);
  140. }
  141. bool ResourceCache::AddManualResource(Resource* resource)
  142. {
  143. if (!resource)
  144. {
  145. ATOMIC_LOGERROR("Null manual resource");
  146. return false;
  147. }
  148. const String& name = resource->GetName();
  149. if (name.Empty())
  150. {
  151. ATOMIC_LOGERROR("Manual resource with empty name, can not add");
  152. return false;
  153. }
  154. resource->ResetUseTimer();
  155. resourceGroups_[resource->GetType()].resources_[resource->GetNameHash()] = resource;
  156. UpdateResourceGroup(resource->GetType());
  157. return true;
  158. }
  159. void ResourceCache::RemoveResourceDir(const String& pathName)
  160. {
  161. MutexLock lock(resourceMutex_);
  162. String fixedPath = SanitateResourceDirName(pathName);
  163. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  164. {
  165. if (!resourceDirs_[i].Compare(fixedPath, false))
  166. {
  167. resourceDirs_.Erase(i);
  168. // Remove the filewatcher with the matching path
  169. for (unsigned j = 0; j < fileWatchers_.Size(); ++j)
  170. {
  171. if (!fileWatchers_[j]->GetPath().Compare(fixedPath, false))
  172. {
  173. fileWatchers_.Erase(j);
  174. break;
  175. }
  176. }
  177. ATOMIC_LOGINFO("Removed resource path " + fixedPath);
  178. return;
  179. }
  180. }
  181. }
  182. void ResourceCache::RemovePackageFile(PackageFile* package, bool releaseResources, bool forceRelease)
  183. {
  184. MutexLock lock(resourceMutex_);
  185. for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i)
  186. {
  187. if (*i == package)
  188. {
  189. if (releaseResources)
  190. ReleasePackageResources(*i, forceRelease);
  191. ATOMIC_LOGINFO("Removed resource package " + (*i)->GetName());
  192. packages_.Erase(i);
  193. return;
  194. }
  195. }
  196. }
  197. void ResourceCache::RemovePackageFile(const String& fileName, bool releaseResources, bool forceRelease)
  198. {
  199. MutexLock lock(resourceMutex_);
  200. // Compare the name and extension only, not the path
  201. String fileNameNoPath = GetFileNameAndExtension(fileName);
  202. for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i)
  203. {
  204. if (!GetFileNameAndExtension((*i)->GetName()).Compare(fileNameNoPath, false))
  205. {
  206. if (releaseResources)
  207. ReleasePackageResources(*i, forceRelease);
  208. ATOMIC_LOGINFO("Removed resource package " + (*i)->GetName());
  209. packages_.Erase(i);
  210. return;
  211. }
  212. }
  213. }
  214. void ResourceCache::ReleaseResource(StringHash type, const String& name, bool force)
  215. {
  216. StringHash nameHash(name);
  217. const SharedPtr<Resource>& existingRes = FindResource(type, nameHash);
  218. if (!existingRes)
  219. return;
  220. // If other references exist, do not release, unless forced
  221. if ((existingRes.Refs() == 1 && existingRes.WeakRefs() == 0) || force)
  222. {
  223. resourceGroups_[type].resources_.Erase(nameHash);
  224. UpdateResourceGroup(type);
  225. }
  226. }
  227. void ResourceCache::ReleaseResources(StringHash type, bool force)
  228. {
  229. bool released = false;
  230. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  231. if (i != resourceGroups_.End())
  232. {
  233. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  234. j != i->second_.resources_.End();)
  235. {
  236. HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  237. // If other references exist, do not release, unless forced
  238. if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force)
  239. {
  240. i->second_.resources_.Erase(current);
  241. released = true;
  242. }
  243. }
  244. }
  245. if (released)
  246. UpdateResourceGroup(type);
  247. }
  248. void ResourceCache::ReleaseResources(StringHash type, const String& partialName, bool force)
  249. {
  250. bool released = false;
  251. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  252. if (i != resourceGroups_.End())
  253. {
  254. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  255. j != i->second_.resources_.End();)
  256. {
  257. HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  258. if (current->second_->GetName().Contains(partialName))
  259. {
  260. // If other references exist, do not release, unless forced
  261. if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force)
  262. {
  263. i->second_.resources_.Erase(current);
  264. released = true;
  265. }
  266. }
  267. }
  268. }
  269. if (released)
  270. UpdateResourceGroup(type);
  271. }
  272. void ResourceCache::ReleaseResources(const String& partialName, bool force)
  273. {
  274. // Some resources refer to others, like materials to textures. Release twice to ensure these get released.
  275. // This is not necessary if forcing release
  276. unsigned repeat = force ? 1 : 2;
  277. while (repeat--)
  278. {
  279. for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  280. {
  281. bool released = false;
  282. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  283. j != i->second_.resources_.End();)
  284. {
  285. HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  286. if (current->second_->GetName().Contains(partialName))
  287. {
  288. // If other references exist, do not release, unless forced
  289. if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force)
  290. {
  291. i->second_.resources_.Erase(current);
  292. released = true;
  293. }
  294. }
  295. }
  296. if (released)
  297. UpdateResourceGroup(i->first_);
  298. }
  299. }
  300. }
  301. void ResourceCache::ReleaseAllResources(bool force)
  302. {
  303. unsigned repeat = force ? 1 : 2;
  304. while (repeat--)
  305. {
  306. for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin();
  307. i != resourceGroups_.End(); ++i)
  308. {
  309. bool released = false;
  310. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  311. j != i->second_.resources_.End();)
  312. {
  313. HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  314. // If other references exist, do not release, unless forced
  315. if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force)
  316. {
  317. i->second_.resources_.Erase(current);
  318. released = true;
  319. }
  320. }
  321. if (released)
  322. UpdateResourceGroup(i->first_);
  323. }
  324. }
  325. }
  326. bool ResourceCache::ReloadResource(Resource* resource)
  327. {
  328. if (!resource)
  329. return false;
  330. resource->SendEvent(E_RELOADSTARTED);
  331. // ATOMIC BEGIN
  332. bool success = false;
  333. SharedPtr<File> file = GetFile(resource->GetName(), true, resource->GetType());
  334. if (file)
  335. {
  336. #ifdef ATOMIC_PLATFORM_DESKTOP
  337. String ext = GetExtension(resource->GetName());
  338. if (ext == ".jpg" || ext == ".png" || ext == ".tga")
  339. {
  340. String ddsName = "DDS/" + resource->GetName() + ".dds";
  341. SharedPtr<File> ddsFile = GetFile(ddsName, false);
  342. if (ddsFile != NULL)
  343. success = resource->Load(*(ddsFile.Get()));
  344. else
  345. success = resource->Load(*(file.Get()));
  346. }
  347. else
  348. {
  349. success = resource->Load(*(file.Get()));
  350. }
  351. #else
  352. success = resource->Load(*(file.Get()));
  353. #endif
  354. }
  355. // ATOMIC END
  356. if (success)
  357. {
  358. resource->ResetUseTimer();
  359. UpdateResourceGroup(resource->GetType());
  360. resource->SendEvent(E_RELOADFINISHED);
  361. return true;
  362. }
  363. // If reloading failed, do not remove the resource from cache, to allow for a new live edit to
  364. // attempt loading again
  365. resource->SendEvent(E_RELOADFAILED);
  366. return false;
  367. }
  368. void ResourceCache::ReloadResourceWithDependencies(const String& fileName)
  369. {
  370. StringHash fileNameHash(fileName);
  371. // If the filename is a resource we keep track of, reload it
  372. const SharedPtr<Resource>& resource = FindResource(fileNameHash);
  373. if (resource)
  374. {
  375. ATOMIC_LOGDEBUG("Reloading changed resource " + fileName);
  376. ReloadResource(resource);
  377. }
  378. // Always perform dependency resource check for resource loaded from XML file as it could be used in inheritance
  379. if (!resource || GetExtension(resource->GetName()) == ".xml")
  380. {
  381. // Check if this is a dependency resource, reload dependents
  382. HashMap<StringHash, HashSet<StringHash> >::ConstIterator j = dependentResources_.Find(fileNameHash);
  383. if (j != dependentResources_.End())
  384. {
  385. // Reloading a resource may modify the dependency tracking structure. Therefore collect the
  386. // resources we need to reload first
  387. Vector<SharedPtr<Resource> > dependents;
  388. dependents.Reserve(j->second_.Size());
  389. for (HashSet<StringHash>::ConstIterator k = j->second_.Begin(); k != j->second_.End(); ++k)
  390. {
  391. const SharedPtr<Resource>& dependent = FindResource(*k);
  392. if (dependent)
  393. dependents.Push(dependent);
  394. }
  395. for (unsigned k = 0; k < dependents.Size(); ++k)
  396. {
  397. ATOMIC_LOGDEBUG("Reloading resource " + dependents[k]->GetName() + " depending on " + fileName);
  398. ReloadResource(dependents[k]);
  399. }
  400. }
  401. }
  402. }
  403. void ResourceCache::SetMemoryBudget(StringHash type, unsigned long long budget)
  404. {
  405. resourceGroups_[type].memoryBudget_ = budget;
  406. }
  407. void ResourceCache::SetAutoReloadResources(bool enable)
  408. {
  409. if (enable != autoReloadResources_)
  410. {
  411. if (enable)
  412. {
  413. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  414. {
  415. SharedPtr<FileWatcher> watcher(new FileWatcher(context_));
  416. watcher->StartWatching(resourceDirs_[i], true);
  417. fileWatchers_.Push(watcher);
  418. }
  419. }
  420. else
  421. fileWatchers_.Clear();
  422. autoReloadResources_ = enable;
  423. }
  424. }
  425. void ResourceCache::AddResourceRouter(ResourceRouter* router, bool addAsFirst)
  426. {
  427. // Check for duplicate
  428. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  429. {
  430. if (resourceRouters_[i] == router)
  431. return;
  432. }
  433. if (addAsFirst)
  434. resourceRouters_.Insert(0, SharedPtr<ResourceRouter>(router));
  435. else
  436. resourceRouters_.Push(SharedPtr<ResourceRouter>(router));
  437. }
  438. void ResourceCache::RemoveResourceRouter(ResourceRouter* router)
  439. {
  440. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  441. {
  442. if (resourceRouters_[i] == router)
  443. {
  444. resourceRouters_.Erase(i);
  445. return;
  446. }
  447. }
  448. }
  449. // ATOMIC BEGIN
  450. SharedPtr<File> ResourceCache::GetFile(const String& nameIn, bool sendEventOnFailure, StringHash type)
  451. {
  452. MutexLock lock(resourceMutex_);
  453. String name = SanitateResourceName(nameIn);
  454. if (!isRouting_)
  455. {
  456. isRouting_ = true;
  457. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  458. resourceRouters_[i]->Route(name, type, RESOURCE_GETFILE);
  459. isRouting_ = false;
  460. }
  461. if (name.Length())
  462. {
  463. File* file = 0;
  464. if (searchPackagesFirst_)
  465. {
  466. file = SearchPackages(name);
  467. if (!file)
  468. file = SearchResourceDirs(name);
  469. }
  470. else
  471. {
  472. file = SearchResourceDirs(name);
  473. if (!file)
  474. file = SearchPackages(name);
  475. }
  476. if (file)
  477. return SharedPtr<File>(file);
  478. }
  479. if (sendEventOnFailure)
  480. {
  481. if (resourceRouters_.Size() && name.Empty() && !nameIn.Empty())
  482. ATOMIC_LOGERROR("Resource request " + nameIn + " was blocked");
  483. else
  484. ATOMIC_LOGERROR("Could not find resource " + name);
  485. if (Thread::IsMainThread())
  486. {
  487. using namespace ResourceNotFound;
  488. VariantMap& eventData = GetEventDataMap();
  489. eventData[P_RESOURCENAME] = name.Length() ? name : nameIn;
  490. SendEvent(E_RESOURCENOTFOUND, eventData);
  491. }
  492. }
  493. return SharedPtr<File>();
  494. }
  495. // ATOMIC END
  496. Resource* ResourceCache::GetExistingResource(StringHash type, const String& nameIn)
  497. {
  498. String name = SanitateResourceName(nameIn);
  499. if (!Thread::IsMainThread())
  500. {
  501. ATOMIC_LOGERROR("Attempted to get resource " + name + " from outside the main thread");
  502. return 0;
  503. }
  504. // If empty name, return null pointer immediately
  505. if (name.Empty())
  506. return 0;
  507. StringHash nameHash(name);
  508. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  509. return existing;
  510. }
  511. Resource* ResourceCache::GetResource(StringHash type, const String& nameIn, bool sendEventOnFailure)
  512. {
  513. String name = SanitateResourceName(nameIn);
  514. if (!Thread::IsMainThread())
  515. {
  516. ATOMIC_LOGERROR("Attempted to get resource " + name + " from outside the main thread");
  517. return 0;
  518. }
  519. // If empty name, return null pointer immediately
  520. if (name.Empty())
  521. return 0;
  522. StringHash nameHash(name);
  523. #ifdef ATOMIC_THREADING
  524. // Check if the resource is being background loaded but is now needed immediately
  525. backgroundLoader_->WaitForResource(type, nameHash);
  526. #endif
  527. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  528. if (existing)
  529. return existing;
  530. SharedPtr<Resource> resource;
  531. // Make sure the pointer is non-null and is a Resource subclass
  532. resource = DynamicCast<Resource>(context_->CreateObject(type));
  533. if (!resource)
  534. {
  535. ATOMIC_LOGERROR("Could not load unknown resource type " + String(type));
  536. if (sendEventOnFailure)
  537. {
  538. using namespace UnknownResourceType;
  539. VariantMap& eventData = GetEventDataMap();
  540. eventData[P_RESOURCETYPE] = type;
  541. SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  542. }
  543. return 0;
  544. }
  545. // ATOMIC BEGIN
  546. // Attempt to load the resource
  547. SharedPtr<File> file = GetFile(name, sendEventOnFailure, type);
  548. if (!file)
  549. return 0; // Error is already logged
  550. // ATOMIC END
  551. ATOMIC_LOGDEBUG("Loading resource " + name);
  552. resource->SetName(name);
  553. if (!resource->Load(*(file.Get())))
  554. {
  555. // Error should already been logged by corresponding resource descendant class
  556. if (sendEventOnFailure)
  557. {
  558. using namespace LoadFailed;
  559. VariantMap& eventData = GetEventDataMap();
  560. eventData[P_RESOURCENAME] = name;
  561. SendEvent(E_LOADFAILED, eventData);
  562. }
  563. if (!returnFailedResources_)
  564. return 0;
  565. }
  566. // Store to cache
  567. resource->ResetUseTimer();
  568. resourceGroups_[type].resources_[nameHash] = resource;
  569. UpdateResourceGroup(type);
  570. return resource;
  571. }
  572. bool ResourceCache::BackgroundLoadResource(StringHash type, const String& nameIn, bool sendEventOnFailure, Resource* caller)
  573. {
  574. #ifdef ATOMIC_THREADING
  575. // If empty name, fail immediately
  576. String name = SanitateResourceName(nameIn);
  577. if (name.Empty())
  578. return false;
  579. // First check if already exists as a loaded resource
  580. StringHash nameHash(name);
  581. if (FindResource(type, nameHash) != noResource)
  582. return false;
  583. return backgroundLoader_->QueueResource(type, name, sendEventOnFailure, caller);
  584. #else
  585. // When threading not supported, fall back to synchronous loading
  586. return GetResource(type, nameIn, sendEventOnFailure);
  587. #endif
  588. }
  589. SharedPtr<Resource> ResourceCache::GetTempResource(StringHash type, const String& nameIn, bool sendEventOnFailure)
  590. {
  591. String name = SanitateResourceName(nameIn);
  592. // If empty name, return null pointer immediately
  593. if (name.Empty())
  594. return SharedPtr<Resource>();
  595. SharedPtr<Resource> resource;
  596. // Make sure the pointer is non-null and is a Resource subclass
  597. resource = DynamicCast<Resource>(context_->CreateObject(type));
  598. if (!resource)
  599. {
  600. ATOMIC_LOGERROR("Could not load unknown resource type " + String(type));
  601. if (sendEventOnFailure)
  602. {
  603. using namespace UnknownResourceType;
  604. VariantMap& eventData = GetEventDataMap();
  605. eventData[P_RESOURCETYPE] = type;
  606. SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  607. }
  608. return SharedPtr<Resource>();
  609. }
  610. // ATOMIC BEGIN
  611. // Attempt to load the resource
  612. SharedPtr<File> file;
  613. // #623 BEGIN TODO: For now try to get DDS version of textures from /DDS cache sub directory,
  614. // ultimately should have per platform compressed versions saved in cache
  615. #ifdef ATOMIC_PLATFORM_DESKTOP
  616. String ext = Atomic::GetExtension(name);
  617. if (ext == ".jpg" || ext == ".png" || ext == ".tga")
  618. {
  619. String ddsName = "DDS/" + name + ".dds";
  620. file = GetFile(ddsName, false);
  621. if (file)
  622. ATOMIC_LOGDEBUG("Loaded cached DDS " + name + ".dds");
  623. }
  624. if (!file)
  625. file = GetFile(name, sendEventOnFailure);
  626. #else
  627. // #623 END TODO
  628. file = GetFile(name, sendEventOnFailure);
  629. #endif
  630. // ATOMIC END
  631. if (!file)
  632. return SharedPtr<Resource>(); // Error is already logged
  633. ATOMIC_LOGDEBUG("Loading temporary resource " + name);
  634. resource->SetName(file->GetName());
  635. if (!resource->Load(*(file.Get())))
  636. {
  637. // Error should already been logged by corresponding resource descendant class
  638. if (sendEventOnFailure)
  639. {
  640. using namespace LoadFailed;
  641. VariantMap& eventData = GetEventDataMap();
  642. eventData[P_RESOURCENAME] = name;
  643. SendEvent(E_LOADFAILED, eventData);
  644. }
  645. return SharedPtr<Resource>();
  646. }
  647. return resource;
  648. }
  649. unsigned ResourceCache::GetNumBackgroundLoadResources() const
  650. {
  651. #ifdef ATOMIC_THREADING
  652. return backgroundLoader_->GetNumQueuedResources();
  653. #else
  654. return 0;
  655. #endif
  656. }
  657. void ResourceCache::GetResources(PODVector<Resource*>& result, StringHash type) const
  658. {
  659. result.Clear();
  660. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  661. if (i != resourceGroups_.End())
  662. {
  663. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = i->second_.resources_.Begin();
  664. j != i->second_.resources_.End(); ++j)
  665. result.Push(j->second_);
  666. }
  667. }
  668. bool ResourceCache::Exists(const String& nameIn) const
  669. {
  670. MutexLock lock(resourceMutex_);
  671. // ATOMIC BEGIN
  672. String name = SanitateResourceName(nameIn);
  673. if (!isRouting_)
  674. {
  675. isRouting_ = true;
  676. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  677. resourceRouters_[i]->Route(name, StringHash::ZERO, RESOURCE_CHECKEXISTS);
  678. isRouting_ = false;
  679. }
  680. // ATOMIC END
  681. if (name.Empty())
  682. return false;
  683. for (unsigned i = 0; i < packages_.Size(); ++i)
  684. {
  685. if (packages_[i]->Exists(name))
  686. return true;
  687. }
  688. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  689. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  690. {
  691. if (fileSystem->FileExists(resourceDirs_[i] + name))
  692. return true;
  693. }
  694. // Fallback using absolute path
  695. return fileSystem->FileExists(name);
  696. }
  697. unsigned long long ResourceCache::GetMemoryBudget(StringHash type) const
  698. {
  699. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  700. return i != resourceGroups_.End() ? i->second_.memoryBudget_ : 0;
  701. }
  702. unsigned long long ResourceCache::GetMemoryUse(StringHash type) const
  703. {
  704. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  705. return i != resourceGroups_.End() ? i->second_.memoryUse_ : 0;
  706. }
  707. unsigned long long ResourceCache::GetTotalMemoryUse() const
  708. {
  709. unsigned long long total = 0;
  710. for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  711. total += i->second_.memoryUse_;
  712. return total;
  713. }
  714. String ResourceCache::GetResourceFileName(const String& name) const
  715. {
  716. MutexLock lock(resourceMutex_);
  717. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  718. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  719. {
  720. if (fileSystem->FileExists(resourceDirs_[i] + name))
  721. return resourceDirs_[i] + name;
  722. }
  723. return String();
  724. }
  725. ResourceRouter* ResourceCache::GetResourceRouter(unsigned index) const
  726. {
  727. return index < resourceRouters_.Size() ? resourceRouters_[index] : (ResourceRouter*)0;
  728. }
  729. String ResourceCache::GetPreferredResourceDir(const String& path) const
  730. {
  731. String fixedPath = AddTrailingSlash(path);
  732. bool pathHasKnownDirs = false;
  733. bool parentHasKnownDirs = false;
  734. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  735. for (unsigned i = 0; checkDirs[i] != 0; ++i)
  736. {
  737. if (fileSystem->DirExists(fixedPath + checkDirs[i]))
  738. {
  739. pathHasKnownDirs = true;
  740. break;
  741. }
  742. }
  743. if (!pathHasKnownDirs)
  744. {
  745. String parentPath = GetParentPath(fixedPath);
  746. for (unsigned i = 0; checkDirs[i] != 0; ++i)
  747. {
  748. if (fileSystem->DirExists(parentPath + checkDirs[i]))
  749. {
  750. parentHasKnownDirs = true;
  751. break;
  752. }
  753. }
  754. // If path does not have known subdirectories, but the parent path has, use the parent instead
  755. if (parentHasKnownDirs)
  756. fixedPath = parentPath;
  757. }
  758. return fixedPath;
  759. }
  760. String ResourceCache::SanitateResourceName(const String& nameIn) const
  761. {
  762. // Sanitate unsupported constructs from the resource name
  763. String name = GetInternalPath(nameIn);
  764. name.Replace("../", "");
  765. name.Replace("./", "");
  766. // If the path refers to one of the resource directories, normalize the resource name
  767. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  768. if (resourceDirs_.Size())
  769. {
  770. String namePath = GetPath(name);
  771. String exePath = fileSystem->GetProgramDir();
  772. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  773. {
  774. String relativeResourcePath = resourceDirs_[i];
  775. if (relativeResourcePath.StartsWith(exePath))
  776. relativeResourcePath = relativeResourcePath.Substring(exePath.Length());
  777. if (namePath.StartsWith(resourceDirs_[i], false))
  778. namePath = namePath.Substring(resourceDirs_[i].Length());
  779. else if (namePath.StartsWith(relativeResourcePath, false))
  780. namePath = namePath.Substring(relativeResourcePath.Length());
  781. }
  782. name = namePath + GetFileNameAndExtension(name);
  783. }
  784. return name.Trimmed();
  785. }
  786. String ResourceCache::SanitateResourceDirName(const String& nameIn) const
  787. {
  788. String fixedPath = AddTrailingSlash(nameIn);
  789. if (!IsAbsolutePath(fixedPath))
  790. fixedPath = GetSubsystem<FileSystem>()->GetCurrentDir() + fixedPath;
  791. // Sanitate away /./ construct
  792. fixedPath.Replace("/./", "/");
  793. return fixedPath.Trimmed();
  794. }
  795. void ResourceCache::StoreResourceDependency(Resource* resource, const String& dependency)
  796. {
  797. if (!resource)
  798. return;
  799. MutexLock lock(resourceMutex_);
  800. StringHash nameHash(resource->GetName());
  801. HashSet<StringHash>& dependents = dependentResources_[dependency];
  802. dependents.Insert(nameHash);
  803. }
  804. void ResourceCache::ResetDependencies(Resource* resource)
  805. {
  806. if (!resource)
  807. return;
  808. MutexLock lock(resourceMutex_);
  809. StringHash nameHash(resource->GetName());
  810. for (HashMap<StringHash, HashSet<StringHash> >::Iterator i = dependentResources_.Begin(); i != dependentResources_.End();)
  811. {
  812. HashSet<StringHash>& dependents = i->second_;
  813. dependents.Erase(nameHash);
  814. if (dependents.Empty())
  815. i = dependentResources_.Erase(i);
  816. else
  817. ++i;
  818. }
  819. }
  820. String ResourceCache::PrintMemoryUsage() const
  821. {
  822. String output = "Resource Type Cnt Avg Max Budget Total\n\n";
  823. char outputLine[256];
  824. unsigned totalResourceCt = 0;
  825. unsigned long long totalLargest = 0;
  826. unsigned long long totalAverage = 0;
  827. unsigned long long totalUse = GetTotalMemoryUse();
  828. for (HashMap<StringHash, ResourceGroup>::ConstIterator cit = resourceGroups_.Begin(); cit != resourceGroups_.End(); ++cit)
  829. {
  830. const unsigned resourceCt = cit->second_.resources_.Size();
  831. unsigned long long average = 0;
  832. if (resourceCt > 0)
  833. average = cit->second_.memoryUse_ / resourceCt;
  834. else
  835. average = 0;
  836. unsigned long long largest = 0;
  837. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator resIt = cit->second_.resources_.Begin(); resIt != cit->second_.resources_.End(); ++resIt)
  838. {
  839. if (resIt->second_->GetMemoryUse() > largest)
  840. largest = resIt->second_->GetMemoryUse();
  841. if (largest > totalLargest)
  842. totalLargest = largest;
  843. }
  844. totalResourceCt += resourceCt;
  845. const String countString(cit->second_.resources_.Size());
  846. const String memUseString = GetFileSizeString(average);
  847. const String memMaxString = GetFileSizeString(largest);
  848. const String memBudgetString = GetFileSizeString(cit->second_.memoryBudget_);
  849. const String memTotalString = GetFileSizeString(cit->second_.memoryUse_);
  850. const String resTypeName = context_->GetTypeName(cit->first_);
  851. memset(outputLine, ' ', 256);
  852. outputLine[255] = 0;
  853. sprintf(outputLine, "%-28s %4s %9s %9s %9s %9s\n", resTypeName.CString(), countString.CString(), memUseString.CString(), memMaxString.CString(), memBudgetString.CString(), memTotalString.CString());
  854. output += ((const char*)outputLine);
  855. }
  856. if (totalResourceCt > 0)
  857. totalAverage = totalUse / totalResourceCt;
  858. const String countString(totalResourceCt);
  859. const String memUseString = GetFileSizeString(totalAverage);
  860. const String memMaxString = GetFileSizeString(totalLargest);
  861. const String memTotalString = GetFileSizeString(totalUse);
  862. memset(outputLine, ' ', 256);
  863. outputLine[255] = 0;
  864. sprintf(outputLine, "%-28s %4s %9s %9s %9s %9s\n", "All", countString.CString(), memUseString.CString(), memMaxString.CString(), "-", memTotalString.CString());
  865. output += ((const char*)outputLine);
  866. return output;
  867. }
  868. const SharedPtr<Resource>& ResourceCache::FindResource(StringHash type, StringHash nameHash)
  869. {
  870. MutexLock lock(resourceMutex_);
  871. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  872. if (i == resourceGroups_.End())
  873. return noResource;
  874. HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  875. if (j == i->second_.resources_.End())
  876. return noResource;
  877. return j->second_;
  878. }
  879. const SharedPtr<Resource>& ResourceCache::FindResource(StringHash nameHash)
  880. {
  881. MutexLock lock(resourceMutex_);
  882. for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  883. {
  884. HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  885. if (j != i->second_.resources_.End())
  886. return j->second_;
  887. }
  888. return noResource;
  889. }
  890. void ResourceCache::ReleasePackageResources(PackageFile* package, bool force)
  891. {
  892. HashSet<StringHash> affectedGroups;
  893. const HashMap<String, PackageEntry>& entries = package->GetEntries();
  894. for (HashMap<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i)
  895. {
  896. StringHash nameHash(i->first_);
  897. // We do not know the actual resource type, so search all type containers
  898. for (HashMap<StringHash, ResourceGroup>::Iterator j = resourceGroups_.Begin(); j != resourceGroups_.End(); ++j)
  899. {
  900. HashMap<StringHash, SharedPtr<Resource> >::Iterator k = j->second_.resources_.Find(nameHash);
  901. if (k != j->second_.resources_.End())
  902. {
  903. // If other references exist, do not release, unless forced
  904. if ((k->second_.Refs() == 1 && k->second_.WeakRefs() == 0) || force)
  905. {
  906. j->second_.resources_.Erase(k);
  907. affectedGroups.Insert(j->first_);
  908. }
  909. break;
  910. }
  911. }
  912. }
  913. for (HashSet<StringHash>::Iterator i = affectedGroups.Begin(); i != affectedGroups.End(); ++i)
  914. UpdateResourceGroup(*i);
  915. }
  916. void ResourceCache::UpdateResourceGroup(StringHash type)
  917. {
  918. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  919. if (i == resourceGroups_.End())
  920. return;
  921. for (;;)
  922. {
  923. unsigned totalSize = 0;
  924. unsigned oldestTimer = 0;
  925. HashMap<StringHash, SharedPtr<Resource> >::Iterator oldestResource = i->second_.resources_.End();
  926. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  927. j != i->second_.resources_.End(); ++j)
  928. {
  929. totalSize += j->second_->GetMemoryUse();
  930. unsigned useTimer = j->second_->GetUseTimer();
  931. if (useTimer > oldestTimer)
  932. {
  933. oldestTimer = useTimer;
  934. oldestResource = j;
  935. }
  936. }
  937. i->second_.memoryUse_ = totalSize;
  938. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  939. // (resources in use always return a zero timer and can not be removed)
  940. if (i->second_.memoryBudget_ && i->second_.memoryUse_ > i->second_.memoryBudget_ &&
  941. oldestResource != i->second_.resources_.End())
  942. {
  943. ATOMIC_LOGDEBUG("Resource group " + oldestResource->second_->GetTypeName() + " over memory budget, releasing resource " +
  944. oldestResource->second_->GetName());
  945. i->second_.resources_.Erase(oldestResource);
  946. }
  947. else
  948. break;
  949. }
  950. }
  951. void ResourceCache::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  952. {
  953. for (unsigned i = 0; i < fileWatchers_.Size(); ++i)
  954. {
  955. String fileName;
  956. while (fileWatchers_[i]->GetNextChange(fileName))
  957. {
  958. ReloadResourceWithDependencies(fileName);
  959. // Finally send a general file changed event even if the file was not a tracked resource
  960. using namespace FileChanged;
  961. VariantMap& eventData = GetEventDataMap();
  962. eventData[P_FILENAME] = fileWatchers_[i]->GetPath() + fileName;
  963. eventData[P_RESOURCENAME] = fileName;
  964. SendEvent(E_FILECHANGED, eventData);
  965. }
  966. }
  967. // Check for background loaded resources that can be finished
  968. #ifdef ATOMIC_THREADING
  969. {
  970. ATOMIC_PROFILE(FinishBackgroundResources);
  971. backgroundLoader_->FinishResources(finishBackgroundResourcesMs_);
  972. }
  973. #endif
  974. }
  975. File* ResourceCache::SearchResourceDirs(const String& nameIn)
  976. {
  977. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  978. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  979. {
  980. if (fileSystem->FileExists(resourceDirs_[i] + nameIn))
  981. {
  982. // Construct the file first with full path, then rename it to not contain the resource path,
  983. // so that the file's name can be used in further GetFile() calls (for example over the network)
  984. File* file(new File(context_, resourceDirs_[i] + nameIn));
  985. file->SetName(nameIn);
  986. return file;
  987. }
  988. }
  989. // Fallback using absolute path
  990. if (fileSystem->FileExists(nameIn))
  991. return new File(context_, nameIn);
  992. return 0;
  993. }
  994. File* ResourceCache::SearchPackages(const String& nameIn)
  995. {
  996. for (unsigned i = 0; i < packages_.Size(); ++i)
  997. {
  998. if (packages_[i]->Exists(nameIn))
  999. return new File(context_, packages_[i], nameIn);
  1000. }
  1001. return 0;
  1002. }
  1003. void RegisterResourceLibrary(Context* context)
  1004. {
  1005. Image::RegisterObject(context);
  1006. JSONFile::RegisterObject(context);
  1007. PListFile::RegisterObject(context);
  1008. XMLFile::RegisterObject(context);
  1009. }
  1010. // ATOMIC BEGIN
  1011. ResourceNameIterator::ResourceNameIterator()
  1012. {
  1013. Reset();
  1014. }
  1015. const String& ResourceNameIterator::GetCurrent()
  1016. {
  1017. return (index_ < filenames_.Size()) ?
  1018. filenames_[index_] :
  1019. String::EMPTY;
  1020. }
  1021. bool ResourceNameIterator::MoveNext()
  1022. {
  1023. return ++index_ < filenames_.Size();
  1024. }
  1025. void ResourceNameIterator::Reset()
  1026. {
  1027. index_ = -1;
  1028. }
  1029. void ResourceCache::Scan(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive) const
  1030. {
  1031. Vector<String> interimResult;
  1032. for (unsigned i = 0; i < packages_.Size(); ++i)
  1033. {
  1034. packages_[i]->Scan(interimResult, pathName, filter, recursive);
  1035. result.Insert(result.End(), interimResult);
  1036. }
  1037. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  1038. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  1039. {
  1040. fileSystem->ScanDir(interimResult, resourceDirs_[i] + pathName, filter, flags, recursive);
  1041. result.Insert(result.End(), interimResult);
  1042. }
  1043. }
  1044. SharedPtr<ResourceNameIterator> ResourceCache::Scan(const String& pathName, const String& filter, unsigned flags, bool recursive) const
  1045. {
  1046. SharedPtr<ResourceNameIterator> enumerator(new ResourceNameIterator());
  1047. Scan(enumerator->filenames_, pathName, filter, flags, recursive);
  1048. return enumerator;
  1049. }
  1050. // ATOMIC END
  1051. }