ResourceCache.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Log.h"
  25. #include "PackageFile.h"
  26. #include "ResourceCache.h"
  27. #include "ResourceFactory.h"
  28. #include "StringUtils.h"
  29. #include "DebugNew.h"
  30. ResourceCache::ResourceCache()
  31. {
  32. LOGINFO("Resource cache created");
  33. }
  34. ResourceCache::~ResourceCache()
  35. {
  36. // At this point factories may be the only thing keeping subsystems alive; remove resources before factories so that
  37. // resources can be released cleanly
  38. mResourceGroups.clear();
  39. mFactories.clear();
  40. LOGINFO("Resource cache shut down");
  41. }
  42. void ResourceCache::addResourceFactory(ResourceFactory* factory)
  43. {
  44. if (!factory)
  45. return;
  46. mFactories.push_back(SharedPtr<ResourceFactory>(factory));
  47. }
  48. void ResourceCache::addResourcePath(const std::string& path)
  49. {
  50. checkDirectoryAccess(path);
  51. std::string fixedPath = fixPath(path);
  52. mResourcePaths.push_back(fixedPath);
  53. // Scan the path for files recursively and add their hash-to-name mappings
  54. std::vector<std::string> fileNames = scanDirectory(fixedPath, "*.*", true);
  55. for (unsigned i = 0; i < fileNames.size(); ++i)
  56. registerHash(fileNames[i]);
  57. LOGINFO("Added resource path " + fixedPath);
  58. }
  59. void ResourceCache::addPackageFile(PackageFile* package, bool addAsFirst)
  60. {
  61. if (!package)
  62. return;
  63. if (addAsFirst)
  64. mPackages.insert(mPackages.begin(), SharedPtr<PackageFile>(package));
  65. else
  66. mPackages.push_back(SharedPtr<PackageFile>(package));
  67. // Scan the package for files and add their hash-to-name mappings
  68. const std::map<std::string, PackageEntry>& entries = package->getEntries();
  69. for (std::map<std::string, PackageEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i)
  70. registerHash(i->first);
  71. LOGINFO("Added resource package " + package->getName());
  72. }
  73. bool ResourceCache::addManualResource(Resource* resource)
  74. {
  75. if (!resource)
  76. {
  77. LOGERROR("Null manual resource");
  78. return false;
  79. }
  80. if (resource->getName().empty())
  81. {
  82. LOGERROR("Manual resource with empty name, can not add");
  83. return false;
  84. }
  85. resource->resetUseTimer();
  86. mResourceGroups[resource->getType()].mResources[resource->getNameHash()] = resource;
  87. updateResourceGroup(resource->getType());
  88. return true;
  89. }
  90. void ResourceCache::removeResourcePath(const std::string& path)
  91. {
  92. for (std::vector<std::string>::iterator i = mResourcePaths.begin(); i != mResourcePaths.end();)
  93. {
  94. if (i->find(path) == 0)
  95. i = mResourcePaths.erase(i);
  96. else
  97. ++i;
  98. }
  99. }
  100. void ResourceCache::removePackageFile(PackageFile* package, bool releaseResources, bool forceRelease)
  101. {
  102. for (std::vector<SharedPtr<PackageFile> >::iterator i = mPackages.begin(); i != mPackages.end(); ++i)
  103. {
  104. if ((*i) == package)
  105. {
  106. if (releaseResources)
  107. releasePackageResources(*i, forceRelease);
  108. mPackages.erase(i);
  109. return;
  110. }
  111. }
  112. }
  113. void ResourceCache::removePackageFile(const std::string& fileName, bool releaseResources, bool forceRelease)
  114. {
  115. for (std::vector<SharedPtr<PackageFile> >::iterator i = mPackages.begin(); i != mPackages.end(); ++i)
  116. {
  117. if ((*i)->getName() == fileName)
  118. {
  119. if (releaseResources)
  120. releasePackageResources(*i, forceRelease);
  121. mPackages.erase(i);
  122. return;
  123. }
  124. }
  125. }
  126. void ResourceCache::releaseResource(ShortStringHash type, const std::string& name, bool force)
  127. {
  128. releaseResource(type, StringHash(name), force);
  129. }
  130. void ResourceCache::releaseResource(ShortStringHash type, StringHash nameHash, bool force)
  131. {
  132. const SharedPtr<Resource>& existingRes = findResource(type, nameHash);
  133. if (!existingRes)
  134. return;
  135. // If other references exist, do not release, unless forced
  136. if ((existingRes.getRefCount() == 1) || (force))
  137. {
  138. mResourceGroups[type].mResources.erase(nameHash);
  139. updateResourceGroup(type);
  140. }
  141. }
  142. void ResourceCache::releaseResources(ShortStringHash type, bool force)
  143. {
  144. bool released = false;
  145. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  146. i != mResourceGroups.end(); ++i)
  147. {
  148. if (i->first == type)
  149. {
  150. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  151. j != i->second.mResources.end();)
  152. {
  153. std::map<StringHash, SharedPtr<Resource> >::iterator current = j++;
  154. // If other references exist, do not release, unless forced
  155. if ((current->second.getRefCount() == 1) || (force))
  156. {
  157. i->second.mResources.erase(current);
  158. released = true;
  159. }
  160. }
  161. }
  162. }
  163. if (released)
  164. updateResourceGroup(type);
  165. }
  166. void ResourceCache::releaseResources(ShortStringHash type, const std::string& partialName, bool force)
  167. {
  168. std::string partialNameLower = toLower(partialName);
  169. bool released = false;
  170. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  171. i != mResourceGroups.end(); ++i)
  172. {
  173. if (i->first == type)
  174. {
  175. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  176. j != i->second.mResources.end();)
  177. {
  178. std::map<StringHash, SharedPtr<Resource> >::iterator current = j++;
  179. if (current->second->getName().find(partialNameLower) != std::string::npos)
  180. {
  181. // If other references exist, do not release, unless forced
  182. if ((current->second.getRefCount() == 1) || (force))
  183. {
  184. i->second.mResources.erase(current);
  185. released = true;
  186. }
  187. }
  188. }
  189. }
  190. }
  191. if (released)
  192. updateResourceGroup(type);
  193. }
  194. bool ResourceCache::reloadResource(Resource* resource)
  195. {
  196. if (!resource)
  197. return false;
  198. try
  199. {
  200. SharedPtr<File> file = getFile(resource->getName());
  201. resource->load(*(file.getPtr()), this);
  202. resource->resetUseTimer();
  203. updateResourceGroup(resource->getType());
  204. return true;
  205. }
  206. catch (...)
  207. {
  208. releaseResource(resource->getType(), resource->getNameHash());
  209. return false;
  210. }
  211. }
  212. void ResourceCache::setMemoryBudget(ShortStringHash type, unsigned budget)
  213. {
  214. mResourceGroups[type].mMemoryBudget = budget;
  215. }
  216. SharedPtr<File> ResourceCache::getFile(const std::string& name)
  217. {
  218. // Check first the packages
  219. for (unsigned i = 0; i < mPackages.size(); ++i)
  220. {
  221. if (mPackages[i]->exists(name))
  222. return SharedPtr<File>(new File(*mPackages[i], name));
  223. }
  224. // Then the filesystem
  225. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  226. {
  227. if (fileExists(mResourcePaths[i] + name))
  228. {
  229. // Construct the file first with full path, then rename it to not contain the resource path,
  230. // so that the file's name can be used in further getFile() calls (for example over the network)
  231. SharedPtr<File> file(new File(mResourcePaths[i] + name));
  232. file->setName(name);
  233. return file;
  234. }
  235. }
  236. EXCEPTION("Could not find resource " + name);
  237. }
  238. Resource* ResourceCache::getResource(ShortStringHash type, const std::string& name)
  239. {
  240. // Add the name to the hash map, so if this is an unknown resource, the error will not be unintelligible
  241. registerHash(name);
  242. return getResource(type, StringHash(name));
  243. }
  244. Resource* ResourceCache::getResource(ShortStringHash type, StringHash nameHash)
  245. {
  246. // If null hash, return null pointer immediately
  247. if (!nameHash)
  248. return 0;
  249. const SharedPtr<Resource>& existing = findResource(type, nameHash);
  250. if (existing)
  251. return existing;
  252. SharedPtr<Resource> resource;
  253. std::string name = hashToString(nameHash);
  254. for (unsigned i = 0; i < mFactories.size(); ++i)
  255. {
  256. resource = mFactories[i]->createResource(type, name);
  257. if (resource)
  258. break;
  259. }
  260. if (!resource)
  261. {
  262. LOGERROR("Could not load unknown resource type " + toString(type));
  263. return 0;
  264. }
  265. LOGDEBUG("Loading resource " + name);
  266. // Attempt to load the resource
  267. try
  268. {
  269. SharedPtr<File> file = getFile(name);
  270. resource->load(*(file.getPtr()), this);
  271. resource->resetUseTimer();
  272. // Store to cache
  273. mResourceGroups[type].mResources[nameHash] = resource;
  274. updateResourceGroup(type);
  275. return mResourceGroups[type].mResources[nameHash];
  276. }
  277. catch (...)
  278. {
  279. return 0;
  280. }
  281. }
  282. std::vector<Resource*> ResourceCache::getResources(ShortStringHash type)
  283. {
  284. std::vector<Resource*> ret;
  285. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  286. if (i != mResourceGroups.end())
  287. {
  288. for (std::map<StringHash, SharedPtr<Resource> >::const_iterator j = i->second.mResources.begin();
  289. j != i->second.mResources.end(); ++j)
  290. ret.push_back(j->second);
  291. }
  292. return ret;
  293. }
  294. bool ResourceCache::exists(const std::string& name) const
  295. {
  296. for (unsigned i = 0; i < mPackages.size(); ++i)
  297. {
  298. if (mPackages[i]->exists(name))
  299. return true;
  300. }
  301. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  302. {
  303. if (fileExists(mResourcePaths[i] + name))
  304. return true;
  305. }
  306. return false;
  307. }
  308. bool ResourceCache::exists(StringHash nameHash) const
  309. {
  310. std::string name = hashToString(nameHash);
  311. return exists(name);
  312. }
  313. unsigned ResourceCache::getMemoryBudget(ShortStringHash type) const
  314. {
  315. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  316. if (i != mResourceGroups.end())
  317. return i->second.mMemoryBudget;
  318. else
  319. return 0;
  320. }
  321. unsigned ResourceCache::getMemoryUse(ShortStringHash type) const
  322. {
  323. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  324. if (i != mResourceGroups.end())
  325. return i->second.mMemoryUse;
  326. else
  327. return 0;
  328. }
  329. unsigned ResourceCache::getTotalMemoryUse() const
  330. {
  331. unsigned total = 0;
  332. for (std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.begin(); i != mResourceGroups.end(); ++i)
  333. total += i->second.mMemoryUse;
  334. return total;
  335. }
  336. const SharedPtr<Resource>& ResourceCache::findResource(ShortStringHash type, StringHash nameHash)
  337. {
  338. static const SharedPtr<Resource> noResource;
  339. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  340. if (i == mResourceGroups.end())
  341. return noResource;
  342. std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.find(nameHash);
  343. if (j == i->second.mResources.end())
  344. return noResource;
  345. return j->second;
  346. }
  347. void ResourceCache::releasePackageResources(PackageFile* package, bool force)
  348. {
  349. std::set<ShortStringHash> affectedGroups;
  350. const std::map<std::string, PackageEntry>& entries = package->getEntries();
  351. for (std::map<std::string, PackageEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i)
  352. {
  353. StringHash nameHash(i->first);
  354. // We do not know the actual resource type, so search all type containers
  355. for (std::map<ShortStringHash, ResourceGroup>::iterator j = mResourceGroups.begin();
  356. j != mResourceGroups.end(); ++j)
  357. {
  358. std::map<StringHash, SharedPtr<Resource> >::iterator k = j->second.mResources.find(nameHash);
  359. if (k != j->second.mResources.end())
  360. {
  361. // If other references exist, do not release, unless forced
  362. if ((k->second.getRefCount() == 1) || (force))
  363. {
  364. j->second.mResources.erase(k);
  365. affectedGroups.insert(j->first);
  366. }
  367. break;
  368. }
  369. }
  370. }
  371. for (std::set<ShortStringHash>::iterator i = affectedGroups.begin(); i != affectedGroups.end(); ++i)
  372. updateResourceGroup(*i);
  373. }
  374. void ResourceCache::updateResourceGroup(ShortStringHash type)
  375. {
  376. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  377. if (i == mResourceGroups.end())
  378. return;
  379. for (;;)
  380. {
  381. unsigned totalSize = 0;
  382. unsigned oldestTimer = 0;
  383. std::map<StringHash, SharedPtr<Resource> >::iterator oldestResource = i->second.mResources.end();
  384. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  385. j != i->second.mResources.end(); ++j)
  386. {
  387. totalSize += j->second->getMemoryUse();
  388. unsigned useTimer = j->second->getUseTimer();
  389. if (useTimer > oldestTimer)
  390. {
  391. oldestTimer = useTimer;
  392. oldestResource = j;
  393. }
  394. }
  395. i->second.mMemoryUse = totalSize;
  396. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  397. // (resources in use always return a zero timer and can not be removed)
  398. if ((i->second.mMemoryBudget) && (i->second.mMemoryUse > i->second.mMemoryBudget) &&
  399. (oldestResource != i->second.mResources.end()))
  400. {
  401. LOGDEBUG("Resource group " + oldestResource->second->getTypeName() + " over memory budget, releasing resource " +
  402. oldestResource->second->getName());
  403. i->second.mResources.erase(oldestResource);
  404. }
  405. else
  406. break;
  407. }
  408. }