ResourceCache.cpp 19 KB

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