ResourceCache.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 " + path);
  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. ++j;
  155. // If other references exist, do not release, unless forced
  156. if ((current->second.getRefCount() == 1) || (force))
  157. {
  158. i->second.mResources.erase(current);
  159. released = true;
  160. }
  161. }
  162. }
  163. }
  164. if (released)
  165. updateResourceGroup(type);
  166. }
  167. void ResourceCache::releaseResources(ShortStringHash type, const std::string& partialName, bool force)
  168. {
  169. std::string partialNameLower = toLower(partialName);
  170. bool released = false;
  171. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  172. i != mResourceGroups.end(); ++i)
  173. {
  174. if (i->first == type)
  175. {
  176. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  177. j != i->second.mResources.end();)
  178. {
  179. std::map<StringHash, SharedPtr<Resource> >::iterator current = j;
  180. ++j;
  181. if (current->second->getName().find(partialNameLower) != std::string::npos)
  182. {
  183. // If other references exist, do not release, unless forced
  184. if ((current->second.getRefCount() == 1) || (force))
  185. {
  186. i->second.mResources.erase(current);
  187. released = true;
  188. }
  189. }
  190. }
  191. }
  192. }
  193. if (released)
  194. updateResourceGroup(type);
  195. }
  196. void ResourceCache::reloadResource(Resource* resource)
  197. {
  198. if (!resource)
  199. return;
  200. SharedPtr<File> file = getFile(resource->getName());
  201. resource->load(*(file.getPtr()), this);
  202. resource->resetUseTimer();
  203. updateResourceGroup(resource->getType());
  204. }
  205. void ResourceCache::setMemoryBudget(ShortStringHash type, unsigned budget)
  206. {
  207. mResourceGroups[type].mMemoryBudget = budget;
  208. }
  209. SharedPtr<File> ResourceCache::getFile(const std::string& name)
  210. {
  211. // Check first the packages
  212. for (unsigned i = 0; i < mPackages.size(); ++i)
  213. {
  214. if (mPackages[i]->exists(name))
  215. {
  216. const PackageEntry& entry = mPackages[i]->getEntry(name);
  217. return SharedPtr<File>(new File(name, &mPackages[i]->getFile(), entry));
  218. }
  219. }
  220. // Then the filesystem
  221. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  222. {
  223. if (fileExists(mResourcePaths[i] + name))
  224. {
  225. // Construct the file first with full path, then rename it to not contain the resource path,
  226. // so that the file's name can be used in further getFile() calls (for example over the network)
  227. SharedPtr<File> file(new File(mResourcePaths[i] + name));
  228. file->setName(name);
  229. return file;
  230. }
  231. }
  232. EXCEPTION("Could not find resource " + name);
  233. }
  234. Resource* ResourceCache::getResource(ShortStringHash type, const std::string& name)
  235. {
  236. // Add the name to the hash map, so if this is an unknown resource, the error will not be unintelligible
  237. registerHash(name);
  238. return getResource(type, StringHash(name));
  239. }
  240. Resource* ResourceCache::getResource(ShortStringHash type, StringHash nameHash)
  241. {
  242. // Special case: null hash is allowed to return null pointer to simplify resource loading code
  243. if (!nameHash)
  244. return 0;
  245. const SharedPtr<Resource>& existing = findResource(type, nameHash);
  246. if (existing)
  247. return existing;
  248. SharedPtr<Resource> resource;
  249. std::string name = hashToString(nameHash);
  250. for (unsigned i = 0; i < mFactories.size(); ++i)
  251. {
  252. resource = mFactories[i]->createResource(type, name);
  253. if (resource)
  254. break;
  255. }
  256. if (!resource)
  257. EXCEPTION("Could not load unknown resource type " + toString(type));
  258. LOGDEBUG("Loading resource " + name);
  259. // Attempt to load the resource
  260. SharedPtr<File> file = getFile(name);
  261. resource->load(*(file.getPtr()), this);
  262. resource->resetUseTimer();
  263. // Store to cache
  264. mResourceGroups[type].mResources[nameHash] = resource;
  265. updateResourceGroup(type);
  266. return mResourceGroups[type].mResources[nameHash];
  267. }
  268. std::vector<Resource*> ResourceCache::getResources(ShortStringHash type)
  269. {
  270. std::vector<Resource*> ret;
  271. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  272. if (i != mResourceGroups.end())
  273. {
  274. for (std::map<StringHash, SharedPtr<Resource> >::const_iterator j = i->second.mResources.begin();
  275. j != i->second.mResources.end(); ++j)
  276. ret.push_back(j->second);
  277. }
  278. return ret;
  279. }
  280. bool ResourceCache::exists(const std::string& name) const
  281. {
  282. for (unsigned i = 0; i < mPackages.size(); ++i)
  283. {
  284. if (mPackages[i]->exists(name))
  285. return true;
  286. }
  287. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  288. {
  289. if (fileExists(mResourcePaths[i] + name))
  290. return true;
  291. }
  292. return false;
  293. }
  294. bool ResourceCache::exists(StringHash nameHash) const
  295. {
  296. std::string name = hashToString(nameHash);
  297. return exists(name);
  298. }
  299. unsigned ResourceCache::getMemoryBudget(ShortStringHash type) const
  300. {
  301. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  302. if (i != mResourceGroups.end())
  303. return i->second.mMemoryBudget;
  304. else
  305. return 0;
  306. }
  307. unsigned ResourceCache::getMemoryUse(ShortStringHash type) const
  308. {
  309. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  310. if (i != mResourceGroups.end())
  311. return i->second.mMemoryUse;
  312. else
  313. return 0;
  314. }
  315. unsigned ResourceCache::getTotalMemoryUse() const
  316. {
  317. unsigned total = 0;
  318. for (std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.begin(); i != mResourceGroups.end(); ++i)
  319. total += i->second.mMemoryUse;
  320. return total;
  321. }
  322. const SharedPtr<Resource>& ResourceCache::findResource(ShortStringHash type, StringHash nameHash)
  323. {
  324. static const SharedPtr<Resource> noResource;
  325. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  326. if (i == mResourceGroups.end())
  327. return noResource;
  328. std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.find(nameHash);
  329. if (j == i->second.mResources.end())
  330. return noResource;
  331. return j->second;
  332. }
  333. void ResourceCache::releasePackageResources(PackageFile* package, bool force)
  334. {
  335. std::set<ShortStringHash> affectedGroups;
  336. const std::map<std::string, PackageEntry>& entries = package->getEntries();
  337. for (std::map<std::string, PackageEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i)
  338. {
  339. StringHash nameHash(i->first);
  340. // We do not know the actual resource type, so search all type containers
  341. for (std::map<ShortStringHash, ResourceGroup>::iterator j = mResourceGroups.begin();
  342. j != mResourceGroups.end(); ++j)
  343. {
  344. std::map<StringHash, SharedPtr<Resource> >::iterator k = j->second.mResources.find(nameHash);
  345. if (k != j->second.mResources.end())
  346. {
  347. // If other references exist, do not release, unless forced
  348. if ((k->second.getRefCount() == 1) || (force))
  349. {
  350. j->second.mResources.erase(k);
  351. affectedGroups.insert(j->first);
  352. }
  353. break;
  354. }
  355. }
  356. }
  357. for (std::set<ShortStringHash>::iterator i = affectedGroups.begin(); i != affectedGroups.end(); ++i)
  358. updateResourceGroup(*i);
  359. }
  360. void ResourceCache::updateResourceGroup(ShortStringHash type)
  361. {
  362. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  363. if (i == mResourceGroups.end())
  364. return;
  365. for (;;)
  366. {
  367. unsigned totalSize = 0;
  368. unsigned oldestTimer = 0;
  369. std::map<StringHash, SharedPtr<Resource> >::iterator oldestResource = i->second.mResources.end();
  370. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  371. j != i->second.mResources.end(); ++j)
  372. {
  373. totalSize += j->second->getMemoryUse();
  374. unsigned useTimer = j->second->getUseTimer();
  375. if (useTimer > oldestTimer)
  376. {
  377. oldestTimer = useTimer;
  378. oldestResource = j;
  379. }
  380. }
  381. i->second.mMemoryUse = totalSize;
  382. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  383. // (resources in use always return a zero timer and can not be removed)
  384. if ((i->second.mMemoryBudget) && (i->second.mMemoryUse > i->second.mMemoryBudget) &&
  385. (oldestResource != i->second.mResources.end()))
  386. {
  387. LOGDEBUG("Resource group " + oldestResource->second->getTypeName() + " over memory budget, releasing resource " +
  388. oldestResource->second->getName());
  389. i->second.mResources.erase(oldestResource);
  390. }
  391. else
  392. break;
  393. }
  394. }