ResourceCache.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 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 "Context.h"
  25. #include "FileSystem.h"
  26. #include "Image.h"
  27. #include "Log.h"
  28. #include "PackageFile.h"
  29. #include "ResourceCache.h"
  30. #include "ResourceEvents.h"
  31. #include "XMLFile.h"
  32. #include "DebugNew.h"
  33. static const String checkDirs[] = {
  34. "Fonts",
  35. "Materials",
  36. "Models",
  37. "Music",
  38. "Objects",
  39. "Particle",
  40. "PostProcess",
  41. "Scenes",
  42. "Scripts",
  43. "Sounds",
  44. "Shaders",
  45. "Techniques",
  46. "Textures",
  47. "UI",
  48. ""
  49. };
  50. static const String noName;
  51. static const SharedPtr<Resource> noResource;
  52. OBJECTTYPESTATIC(ResourceCache);
  53. ResourceCache::ResourceCache(Context* context) :
  54. Object(context)
  55. {
  56. }
  57. ResourceCache::~ResourceCache()
  58. {
  59. }
  60. bool ResourceCache::AddResourceDir(const String& pathName)
  61. {
  62. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  63. if (!fileSystem || !fileSystem->DirExists(pathName))
  64. {
  65. LOGERROR("Could not open directory " + pathName);
  66. return false;
  67. }
  68. String fixedPath = AddTrailingSlash(pathName);
  69. // Check that the same path does not already exist
  70. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  71. {
  72. if (!resourceDirs_[i].Compare(fixedPath, false))
  73. return true;
  74. }
  75. resourceDirs_.Push(fixedPath);
  76. // Scan the path for files recursively and add their hash-to-name mappings
  77. Vector<String> fileNames;
  78. fileSystem->ScanDir(fileNames, fixedPath, "*.*", SCAN_FILES, true);
  79. for (unsigned i = 0; i < fileNames.Size(); ++i)
  80. StoreNameHash(fileNames[i]);
  81. LOGINFO("Added resource path " + fixedPath);
  82. return true;
  83. }
  84. void ResourceCache::AddPackageFile(PackageFile* package, bool addAsFirst)
  85. {
  86. // Do not add packages that failed to load
  87. if (!package || !package->GetNumFiles())
  88. return;
  89. if (addAsFirst)
  90. packages_.Insert(packages_.Begin(), SharedPtr<PackageFile>(package));
  91. else
  92. packages_.Push(SharedPtr<PackageFile>(package));
  93. // Scan the package for files and add their hash-to-name mappings
  94. const Map<String, PackageEntry>& entries = package->GetEntries();
  95. for (Map<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i)
  96. StoreNameHash(i->first_);
  97. LOGINFO("Added resource package " + package->GetName());
  98. }
  99. bool ResourceCache::AddManualResource(Resource* resource)
  100. {
  101. if (!resource)
  102. {
  103. LOGERROR("Null manual resource");
  104. return false;
  105. }
  106. const String& name = resource->GetName();
  107. if (name.Empty())
  108. {
  109. LOGERROR("Manual resource with empty name, can not add");
  110. return false;
  111. }
  112. StoreNameHash(name);
  113. resource->ResetUseTimer();
  114. resourceGroups_[resource->GetType()].resources_[resource->GetNameHash()] = resource;
  115. UpdateResourceGroup(resource->GetType());
  116. return true;
  117. }
  118. void ResourceCache::RemoveResourceDir(const String& path)
  119. {
  120. String fixedPath = AddTrailingSlash(path);
  121. for (Vector<String>::Iterator i = resourceDirs_.Begin(); i != resourceDirs_.End(); ++i)
  122. {
  123. if (!i->Compare(path, false))
  124. {
  125. resourceDirs_.Erase(i);
  126. LOGINFO("Removed resource path " + fixedPath);
  127. return;
  128. }
  129. }
  130. }
  131. void ResourceCache::RemovePackageFile(PackageFile* package, bool releaseResources, bool forceRelease)
  132. {
  133. for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i)
  134. {
  135. if (*i == package)
  136. {
  137. if (releaseResources)
  138. ReleasePackageResources(*i, forceRelease);
  139. LOGINFO("Removed resource package " + (*i)->GetName());
  140. packages_.Erase(i);
  141. return;
  142. }
  143. }
  144. }
  145. void ResourceCache::RemovePackageFile(const String& fileName, bool releaseResources, bool forceRelease)
  146. {
  147. // Compare the name and extension only, not the path
  148. String fileNameNoPath = GetFileNameAndExtension(fileName);
  149. for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i)
  150. {
  151. if (!GetFileNameAndExtension((*i)->GetName()).Compare(fileNameNoPath, false))
  152. {
  153. if (releaseResources)
  154. ReleasePackageResources(*i, forceRelease);
  155. LOGINFO("Removed resource package " + (*i)->GetName());
  156. packages_.Erase(i);
  157. return;
  158. }
  159. }
  160. }
  161. void ResourceCache::ReleaseResource(ShortStringHash type, const String& name, bool force)
  162. {
  163. ReleaseResource(type, StringHash(name), force);
  164. }
  165. void ResourceCache::ReleaseResource(ShortStringHash type, StringHash nameHash, bool force)
  166. {
  167. const SharedPtr<Resource>& existingRes = FindResource(type, nameHash);
  168. if (!existingRes)
  169. return;
  170. // If other references exist, do not release, unless forced
  171. if (existingRes.Refs() == 1 || force)
  172. {
  173. resourceGroups_[type].resources_.Erase(nameHash);
  174. UpdateResourceGroup(type);
  175. }
  176. }
  177. void ResourceCache::ReleaseResources(ShortStringHash type, bool force)
  178. {
  179. bool released = false;
  180. for (Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin();
  181. i != resourceGroups_.End(); ++i)
  182. {
  183. if (i->first_ == type)
  184. {
  185. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  186. j != i->second_.resources_.End();)
  187. {
  188. Map<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  189. // If other references exist, do not release, unless forced
  190. if (current->second_.Refs() == 1 || force)
  191. {
  192. i->second_.resources_.Erase(current);
  193. released = true;
  194. }
  195. }
  196. }
  197. }
  198. if (released)
  199. UpdateResourceGroup(type);
  200. }
  201. void ResourceCache::ReleaseResources(ShortStringHash type, const String& partialName, bool force)
  202. {
  203. bool released = false;
  204. for (Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin();
  205. i != resourceGroups_.End(); ++i)
  206. {
  207. if (i->first_ == type)
  208. {
  209. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  210. j != i->second_.resources_.End();)
  211. {
  212. Map<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  213. if (current->second_->GetName().Find(partialName) != String::NPOS)
  214. {
  215. // If other references exist, do not release, unless forced
  216. if (current->second_.Refs() == 1 || force)
  217. {
  218. i->second_.resources_.Erase(current);
  219. released = true;
  220. }
  221. }
  222. }
  223. }
  224. }
  225. if (released)
  226. UpdateResourceGroup(type);
  227. }
  228. void ResourceCache::ReleaseAllResources(bool force)
  229. {
  230. for (Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin();
  231. i != resourceGroups_.End(); ++i)
  232. {
  233. bool released = false;
  234. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  235. j != i->second_.resources_.End();)
  236. {
  237. Map<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  238. // If other references exist, do not release, unless forced
  239. if (current->second_.Refs() == 1 || force)
  240. {
  241. i->second_.resources_.Erase(current);
  242. released = true;
  243. }
  244. }
  245. if (released)
  246. UpdateResourceGroup(i->first_);
  247. }
  248. }
  249. bool ResourceCache::ReloadResource(Resource* resource)
  250. {
  251. if (!resource)
  252. return false;
  253. resource->SendEvent(E_RELOADSTARTED);
  254. bool success = false;
  255. SharedPtr<File> file = GetFile(resource->GetName());
  256. if (file)
  257. success = resource->Load(*(file.Get()));
  258. if (success)
  259. {
  260. resource->ResetUseTimer();
  261. UpdateResourceGroup(resource->GetType());
  262. resource->SendEvent(E_RELOADFINISHED);
  263. return true;
  264. }
  265. // If reloading failed, remove the resource from cache
  266. resource->SendEvent(E_RELOADFAILED);
  267. ReleaseResource(resource->GetType(), resource->GetNameHash());
  268. return false;
  269. }
  270. void ResourceCache::SetMemoryBudget(ShortStringHash type, unsigned budget)
  271. {
  272. resourceGroups_[type].memoryBudget_ = budget;
  273. }
  274. SharedPtr<File> ResourceCache::GetFile(const String& nameIn)
  275. {
  276. String name = SanitateResourceName(nameIn);
  277. // Check first the packages
  278. for (unsigned i = 0; i < packages_.Size(); ++i)
  279. {
  280. if (packages_[i]->Exists(name))
  281. return SharedPtr<File>(new File(context_, packages_[i], name));
  282. }
  283. // Then the filesystem
  284. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  285. if (fileSystem)
  286. {
  287. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  288. {
  289. if (fileSystem->FileExists(resourceDirs_[i] + name))
  290. {
  291. // Construct the file first with full path, then rename it to not contain the resource path,
  292. // so that the file's name can be used in further GetFile() calls (for example over the network)
  293. SharedPtr<File> file(new File(context_, resourceDirs_[i] + name));
  294. file->SetName(name);
  295. return file;
  296. }
  297. }
  298. }
  299. LOGERROR("Could not find resource " + name);
  300. return SharedPtr<File>();
  301. }
  302. Resource* ResourceCache::GetResource(ShortStringHash type, const String& nameIn)
  303. {
  304. String name = SanitateResourceName(nameIn);
  305. // Add the name to the hash map, so if this is an unknown resource, the error will not be unintelligible
  306. StoreNameHash(name);
  307. return GetResource(type, StringHash(name));
  308. }
  309. Resource* ResourceCache::GetResource(ShortStringHash type, StringHash nameHash)
  310. {
  311. // If null hash, return null pointer immediately
  312. if (!nameHash)
  313. return 0;
  314. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  315. if (existing)
  316. return existing;
  317. SharedPtr<Resource> resource;
  318. const String& name = GetResourceName(nameHash);
  319. if (name.Empty())
  320. {
  321. LOGERROR("Could not load unknown resource " + String(nameHash));
  322. return 0;
  323. }
  324. // Make sure the pointer is non-null and is a Resource subclass
  325. resource = DynamicCast<Resource>(context_->CreateObject(type));
  326. if (!resource)
  327. {
  328. LOGERROR("Could not load unknown resource type " + String(type));
  329. return 0;
  330. }
  331. // Attempt to load the resource
  332. SharedPtr<File> file = GetFile(name);
  333. if (!file)
  334. return 0;
  335. LOGDEBUG("Loading resource " + name);
  336. resource->SetName(file->GetName());
  337. if (!resource->Load(*(file.Get())))
  338. return 0;
  339. // Store to cache
  340. resource->ResetUseTimer();
  341. resourceGroups_[type].resources_[nameHash] = resource;
  342. UpdateResourceGroup(type);
  343. return resource;
  344. }
  345. void ResourceCache::GetResources(PODVector<Resource*>& result, ShortStringHash type) const
  346. {
  347. result.Clear();
  348. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  349. if (i != resourceGroups_.End())
  350. {
  351. for (Map<StringHash, SharedPtr<Resource> >::ConstIterator j = i->second_.resources_.Begin();
  352. j != i->second_.resources_.End(); ++j)
  353. result.Push(j->second_);
  354. }
  355. }
  356. bool ResourceCache::Exists(const String& name) const
  357. {
  358. for (unsigned i = 0; i < packages_.Size(); ++i)
  359. {
  360. if (packages_[i]->Exists(name))
  361. return true;
  362. }
  363. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  364. if (fileSystem)
  365. {
  366. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  367. {
  368. if (fileSystem->FileExists(resourceDirs_[i] + name))
  369. return true;
  370. }
  371. }
  372. return false;
  373. }
  374. bool ResourceCache::Exists(StringHash nameHash) const
  375. {
  376. return Exists(GetResourceName(nameHash));
  377. }
  378. unsigned ResourceCache::GetMemoryBudget(ShortStringHash type) const
  379. {
  380. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  381. if (i != resourceGroups_.End())
  382. return i->second_.memoryBudget_;
  383. else
  384. return 0;
  385. }
  386. unsigned ResourceCache::GetMemoryUse(ShortStringHash type) const
  387. {
  388. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  389. if (i != resourceGroups_.End())
  390. return i->second_.memoryUse_;
  391. else
  392. return 0;
  393. }
  394. unsigned ResourceCache::GetTotalMemoryUse() const
  395. {
  396. unsigned total = 0;
  397. for (Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  398. total += i->second_.memoryUse_;
  399. return total;
  400. }
  401. const String& ResourceCache::GetResourceName(StringHash nameHash) const
  402. {
  403. Map<StringHash, String>::ConstIterator i = hashToName_.Find(nameHash);
  404. if (i == hashToName_.End())
  405. return noName;
  406. else
  407. return i->second_;
  408. }
  409. String ResourceCache::GetPreferredResourceDir(const String& path)
  410. {
  411. String fixedPath = AddTrailingSlash(path);
  412. bool pathHasKnownDirs = false;
  413. bool parentHasKnownDirs = false;
  414. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  415. // If no filesystem, can not check directory existence, so just return the original path
  416. if (!fileSystem)
  417. return fixedPath;
  418. for (unsigned i = 0; !checkDirs[i].Empty(); ++i)
  419. {
  420. if (fileSystem->DirExists(fixedPath + checkDirs[i]))
  421. {
  422. pathHasKnownDirs = true;
  423. break;
  424. }
  425. }
  426. if (!pathHasKnownDirs)
  427. {
  428. String parentPath = GetParentPath(fixedPath);
  429. for (unsigned i = 0; !checkDirs[i].Empty(); ++i)
  430. {
  431. if (fileSystem->DirExists(parentPath + checkDirs[i]))
  432. {
  433. parentHasKnownDirs = true;
  434. break;
  435. }
  436. }
  437. // If path does not have known subdirectories, but the parent path has, use the parent instead
  438. if (parentHasKnownDirs)
  439. fixedPath = parentPath;
  440. }
  441. return fixedPath;
  442. }
  443. String ResourceCache::SanitateResourceName(const String& nameIn)
  444. {
  445. // Sanitate unsupported constructs from the resource name
  446. String name = GetInternalPath(nameIn);
  447. name.Replace("../", "");
  448. name.Replace("./", "");
  449. return name;
  450. }
  451. void ResourceCache::StoreNameHash(const String& name)
  452. {
  453. if (name.Empty())
  454. return;
  455. StringHash hash(name);
  456. // If entry exists, check for difference (collision)
  457. Map<StringHash, String>::Iterator i = hashToName_.Find(hash);
  458. if (i != hashToName_.End())
  459. {
  460. if (i->second_.Compare(name, false))
  461. LOGERROR("Resource hash collision " + i->second_ + " vs " + name);
  462. i->second_ = name;
  463. }
  464. else
  465. hashToName_[hash] = name;
  466. }
  467. const SharedPtr<Resource>& ResourceCache::FindResource(ShortStringHash type, StringHash nameHash)
  468. {
  469. Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  470. if (i == resourceGroups_.End())
  471. return noResource;
  472. Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  473. if (j == i->second_.resources_.End())
  474. return noResource;
  475. return j->second_;
  476. }
  477. void ResourceCache::ReleasePackageResources(PackageFile* package, bool force)
  478. {
  479. HashSet<ShortStringHash> affectedGroups;
  480. const Map<String, PackageEntry>& entries = package->GetEntries();
  481. for (Map<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i)
  482. {
  483. StringHash nameHash(i->first_);
  484. // We do not know the actual resource type, so search all type containers
  485. for (Map<ShortStringHash, ResourceGroup>::Iterator j = resourceGroups_.Begin();
  486. j != resourceGroups_.End(); ++j)
  487. {
  488. Map<StringHash, SharedPtr<Resource> >::Iterator k = j->second_.resources_.Find(nameHash);
  489. if (k != j->second_.resources_.End())
  490. {
  491. // If other references exist, do not release, unless forced
  492. if (k->second_.Refs() == 1 || force)
  493. {
  494. j->second_.resources_.Erase(k);
  495. affectedGroups.Insert(j->first_);
  496. }
  497. break;
  498. }
  499. }
  500. }
  501. for (HashSet<ShortStringHash>::Iterator i = affectedGroups.Begin(); i != affectedGroups.End(); ++i)
  502. UpdateResourceGroup(*i);
  503. }
  504. void ResourceCache::UpdateResourceGroup(ShortStringHash type)
  505. {
  506. Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  507. if (i == resourceGroups_.End())
  508. return;
  509. for (;;)
  510. {
  511. unsigned totalSize = 0;
  512. unsigned oldestTimer = 0;
  513. Map<StringHash, SharedPtr<Resource> >::Iterator oldestResource = i->second_.resources_.End();
  514. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  515. j != i->second_.resources_.End(); ++j)
  516. {
  517. totalSize += j->second_->GetMemoryUse();
  518. unsigned useTimer = j->second_->GetUseTimer();
  519. if (useTimer > oldestTimer)
  520. {
  521. oldestTimer = useTimer;
  522. oldestResource = j;
  523. }
  524. }
  525. i->second_.memoryUse_ = totalSize;
  526. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  527. // (resources in use always return a zero timer and can not be removed)
  528. if (i->second_.memoryBudget_ && i->second_.memoryUse_ > i->second_.memoryBudget_ &&
  529. oldestResource != i->second_.resources_.End())
  530. {
  531. LOGDEBUG("Resource group " + oldestResource->second_->GetTypeName() + " over memory budget, releasing resource " +
  532. oldestResource->second_->GetName());
  533. i->second_.resources_.Erase(oldestResource);
  534. }
  535. else
  536. break;
  537. }
  538. }
  539. void RegisterResourceLibrary(Context* context)
  540. {
  541. Image::RegisterObject(context);
  542. XMLFile::RegisterObject(context);
  543. }