ResourceCache.cpp 19 KB

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