ResourceCache.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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 "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& name)
  275. {
  276. // Check first the packages
  277. for (unsigned i = 0; i < packages_.Size(); ++i)
  278. {
  279. if (packages_[i]->Exists(name))
  280. return SharedPtr<File>(new File(context_, packages_[i], name));
  281. }
  282. // Then the filesystem
  283. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  284. if (fileSystem)
  285. {
  286. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  287. {
  288. if (fileSystem->FileExists(resourceDirs_[i] + name))
  289. {
  290. // Construct the file first with full path, then rename it to not contain the resource path,
  291. // so that the file's name can be used in further GetFile() calls (for example over the network)
  292. SharedPtr<File> file(new File(context_, resourceDirs_[i] + name));
  293. file->SetName(name);
  294. return file;
  295. }
  296. }
  297. }
  298. LOGERROR("Could not find resource " + name);
  299. return SharedPtr<File>();
  300. }
  301. Resource* ResourceCache::GetResource(ShortStringHash type, const String& name)
  302. {
  303. // Add the name to the hash map, so if this is an unknown resource, the error will not be unintelligible
  304. StoreNameHash(name);
  305. return GetResource(type, StringHash(name));
  306. }
  307. Resource* ResourceCache::GetResource(ShortStringHash type, StringHash nameHash)
  308. {
  309. // If null hash, return null pointer immediately
  310. if (!nameHash)
  311. return 0;
  312. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  313. if (existing)
  314. return existing;
  315. SharedPtr<Resource> resource;
  316. const String& name = GetResourceName(nameHash);
  317. if (name.Empty())
  318. {
  319. LOGERROR("Could not load unknown resource " + String(nameHash));
  320. return 0;
  321. }
  322. // Make sure the pointer is non-null and is a Resource subclass
  323. resource = DynamicCast<Resource>(context_->CreateObject(type));
  324. if (!resource)
  325. {
  326. LOGERROR("Could not load unknown resource type " + String(type));
  327. return 0;
  328. }
  329. // Attempt to load the resource
  330. SharedPtr<File> file = GetFile(name);
  331. if (!file)
  332. return 0;
  333. LOGDEBUG("Loading resource " + name);
  334. resource->SetName(file->GetName());
  335. if (!resource->Load(*(file.Get())))
  336. return 0;
  337. // Store to cache
  338. resource->ResetUseTimer();
  339. resourceGroups_[type].resources_[nameHash] = resource;
  340. UpdateResourceGroup(type);
  341. return resource;
  342. }
  343. void ResourceCache::GetResources(PODVector<Resource*>& result, ShortStringHash type) const
  344. {
  345. result.Clear();
  346. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  347. if (i != resourceGroups_.End())
  348. {
  349. for (Map<StringHash, SharedPtr<Resource> >::ConstIterator j = i->second_.resources_.Begin();
  350. j != i->second_.resources_.End(); ++j)
  351. result.Push(j->second_);
  352. }
  353. }
  354. bool ResourceCache::Exists(const String& name) const
  355. {
  356. for (unsigned i = 0; i < packages_.Size(); ++i)
  357. {
  358. if (packages_[i]->Exists(name))
  359. return true;
  360. }
  361. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  362. if (fileSystem)
  363. {
  364. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  365. {
  366. if (fileSystem->FileExists(resourceDirs_[i] + name))
  367. return true;
  368. }
  369. }
  370. return false;
  371. }
  372. bool ResourceCache::Exists(StringHash nameHash) const
  373. {
  374. return Exists(GetResourceName(nameHash));
  375. }
  376. unsigned ResourceCache::GetMemoryBudget(ShortStringHash type) const
  377. {
  378. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  379. if (i != resourceGroups_.End())
  380. return i->second_.memoryBudget_;
  381. else
  382. return 0;
  383. }
  384. unsigned ResourceCache::GetMemoryUse(ShortStringHash type) const
  385. {
  386. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  387. if (i != resourceGroups_.End())
  388. return i->second_.memoryUse_;
  389. else
  390. return 0;
  391. }
  392. unsigned ResourceCache::GetTotalMemoryUse() const
  393. {
  394. unsigned total = 0;
  395. for (Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  396. total += i->second_.memoryUse_;
  397. return total;
  398. }
  399. const String& ResourceCache::GetResourceName(StringHash nameHash) const
  400. {
  401. Map<StringHash, String>::ConstIterator i = hashToName_.Find(nameHash);
  402. if (i == hashToName_.End())
  403. return noName;
  404. else
  405. return i->second_;
  406. }
  407. String ResourceCache::GetPreferredResourceDir(const String& path)
  408. {
  409. String fixedPath = AddTrailingSlash(path);
  410. bool pathHasKnownDirs = false;
  411. bool parentHasKnownDirs = false;
  412. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  413. // If no filesystem, can not check directory existence, so just return the original path
  414. if (!fileSystem)
  415. return fixedPath;
  416. for (unsigned i = 0; !checkDirs[i].Empty(); ++i)
  417. {
  418. if (fileSystem->DirExists(fixedPath + checkDirs[i]))
  419. {
  420. pathHasKnownDirs = true;
  421. break;
  422. }
  423. }
  424. if (!pathHasKnownDirs)
  425. {
  426. String parentPath = GetParentPath(fixedPath);
  427. for (unsigned i = 0; !checkDirs[i].Empty(); ++i)
  428. {
  429. if (fileSystem->DirExists(parentPath + checkDirs[i]))
  430. {
  431. parentHasKnownDirs = true;
  432. break;
  433. }
  434. }
  435. // If path does not have known subdirectories, but the parent path has, use the parent instead
  436. if (parentHasKnownDirs)
  437. fixedPath = parentPath;
  438. }
  439. return fixedPath;
  440. }
  441. void ResourceCache::StoreNameHash(const String& name)
  442. {
  443. if (name.Empty())
  444. return;
  445. hashToName_[StringHash(name)] = name;
  446. }
  447. const SharedPtr<Resource>& ResourceCache::FindResource(ShortStringHash type, StringHash nameHash)
  448. {
  449. Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  450. if (i == resourceGroups_.End())
  451. return noResource;
  452. Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  453. if (j == i->second_.resources_.End())
  454. return noResource;
  455. return j->second_;
  456. }
  457. void ResourceCache::ReleasePackageResources(PackageFile* package, bool force)
  458. {
  459. HashSet<ShortStringHash> affectedGroups;
  460. const Map<String, PackageEntry>& entries = package->GetEntries();
  461. for (Map<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i)
  462. {
  463. StringHash nameHash(i->first_);
  464. // We do not know the actual resource type, so search all type containers
  465. for (Map<ShortStringHash, ResourceGroup>::Iterator j = resourceGroups_.Begin();
  466. j != resourceGroups_.End(); ++j)
  467. {
  468. Map<StringHash, SharedPtr<Resource> >::Iterator k = j->second_.resources_.Find(nameHash);
  469. if (k != j->second_.resources_.End())
  470. {
  471. // If other references exist, do not release, unless forced
  472. if (k->second_.Refs() == 1 || force)
  473. {
  474. j->second_.resources_.Erase(k);
  475. affectedGroups.Insert(j->first_);
  476. }
  477. break;
  478. }
  479. }
  480. }
  481. for (HashSet<ShortStringHash>::Iterator i = affectedGroups.Begin(); i != affectedGroups.End(); ++i)
  482. UpdateResourceGroup(*i);
  483. }
  484. void ResourceCache::UpdateResourceGroup(ShortStringHash type)
  485. {
  486. Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  487. if (i == resourceGroups_.End())
  488. return;
  489. for (;;)
  490. {
  491. unsigned totalSize = 0;
  492. unsigned oldestTimer = 0;
  493. Map<StringHash, SharedPtr<Resource> >::Iterator oldestResource = i->second_.resources_.End();
  494. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  495. j != i->second_.resources_.End(); ++j)
  496. {
  497. totalSize += j->second_->GetMemoryUse();
  498. unsigned useTimer = j->second_->GetUseTimer();
  499. if (useTimer > oldestTimer)
  500. {
  501. oldestTimer = useTimer;
  502. oldestResource = j;
  503. }
  504. }
  505. i->second_.memoryUse_ = totalSize;
  506. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  507. // (resources in use always return a zero timer and can not be removed)
  508. if (i->second_.memoryBudget_ && i->second_.memoryUse_ > i->second_.memoryBudget_ &&
  509. oldestResource != i->second_.resources_.End())
  510. {
  511. LOGDEBUG("Resource group " + oldestResource->second_->GetTypeName() + " over memory budget, releasing resource " +
  512. oldestResource->second_->GetName());
  513. i->second_.resources_.Erase(oldestResource);
  514. }
  515. else
  516. break;
  517. }
  518. }
  519. void RegisterResourceLibrary(Context* context)
  520. {
  521. Image::RegisterObject(context);
  522. XMLFile::RegisterObject(context);
  523. }