BackgroundLoader.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "BackgroundLoader.h"
  24. #include "Context.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "ResourceCache.h"
  28. #include "ResourceEvents.h"
  29. #include "Timer.h"
  30. #include "DebugNew.h"
  31. namespace Urho3D
  32. {
  33. BackgroundLoader::BackgroundLoader(ResourceCache* owner) :
  34. owner_(owner)
  35. {
  36. }
  37. void BackgroundLoader::ThreadFunction()
  38. {
  39. while (shouldRun_)
  40. {
  41. backgroundLoadMutex_.Acquire();
  42. // Search for a queued resource that has not been loaded yet
  43. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Begin();
  44. while (i != backgroundLoadQueue_.End())
  45. {
  46. if (i->second_.resource_->GetAsyncLoadState() == ASYNC_QUEUED)
  47. break;
  48. else
  49. ++i;
  50. }
  51. if (i == backgroundLoadQueue_.End())
  52. {
  53. // No resources to load found
  54. backgroundLoadMutex_.Release();
  55. Time::Sleep(5);
  56. }
  57. else
  58. {
  59. BackgroundLoadItem& item = i->second_;
  60. Resource* resource = item.resource_;
  61. // We can be sure that the item is not removed from the queue as long as it is in the
  62. // "queued" or "loading" state
  63. backgroundLoadMutex_.Release();
  64. bool success = false;
  65. SharedPtr<File> file = owner_->GetFile(resource->GetName(), item.sendEventOnFailure_);
  66. if (file)
  67. {
  68. resource->SetAsyncLoadState(ASYNC_LOADING);
  69. success = resource->BeginLoad(*file);
  70. }
  71. // Process dependencies now
  72. // Need to lock the queue again when manipulating other entries
  73. Pair<StringHash, StringHash> key = MakePair(resource->GetType(), resource->GetNameHash());
  74. backgroundLoadMutex_.Acquire();
  75. if (item.dependents_.Size())
  76. {
  77. for (HashSet<Pair<StringHash, StringHash> >::Iterator i = item.dependents_.Begin(); i != item.dependents_.End();
  78. ++i)
  79. {
  80. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator j =
  81. backgroundLoadQueue_.Find(*i);
  82. if (j != backgroundLoadQueue_.End())
  83. j->second_.dependencies_.Erase(key);
  84. }
  85. item.dependents_.Clear();
  86. }
  87. resource->SetAsyncLoadState(success ? ASYNC_SUCCESS : ASYNC_FAIL);
  88. backgroundLoadMutex_.Release();
  89. }
  90. }
  91. }
  92. bool BackgroundLoader::QueueResource(StringHash type, const String& name, bool sendEventOnFailure, Resource* caller)
  93. {
  94. StringHash nameHash(name);
  95. Pair<StringHash, StringHash> key = MakePair(type, nameHash);
  96. MutexLock lock(backgroundLoadMutex_);
  97. // Check if already exists in the queue
  98. if (backgroundLoadQueue_.Find(key) != backgroundLoadQueue_.End())
  99. return false;
  100. BackgroundLoadItem& item = backgroundLoadQueue_[key];
  101. item.sendEventOnFailure_ = sendEventOnFailure;
  102. // Make sure the pointer is non-null and is a Resource subclass
  103. item.resource_ = DynamicCast<Resource>(owner_->GetContext()->CreateObject(type));
  104. if (!item.resource_)
  105. {
  106. LOGERROR("Could not load unknown resource type " + String(type));
  107. if (sendEventOnFailure && Thread::IsMainThread())
  108. {
  109. using namespace UnknownResourceType;
  110. VariantMap& eventData = owner_->GetEventDataMap();
  111. eventData[P_RESOURCETYPE] = type;
  112. owner_->SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  113. }
  114. backgroundLoadQueue_.Erase(key);
  115. return false;
  116. }
  117. LOGDEBUG("Background loading resource " + name);
  118. item.resource_->SetName(name);
  119. item.resource_->SetAsyncLoadState(ASYNC_QUEUED);
  120. // If this is a resource calling for the background load of more resources, mark the dependency as necessary
  121. if (caller)
  122. {
  123. Pair<StringHash, StringHash> callerKey = MakePair(caller->GetType(), caller->GetNameHash());
  124. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator j = backgroundLoadQueue_.Find(callerKey);
  125. if (j != backgroundLoadQueue_.End())
  126. {
  127. BackgroundLoadItem& callerItem = j->second_;
  128. item.dependents_.Insert(callerKey);
  129. callerItem.dependencies_.Insert(key);
  130. }
  131. else
  132. LOGWARNING("Resource " + caller->GetName() + " requested for a background loaded resource but was not in the background load queue");
  133. }
  134. // Start the background loader thread now
  135. if (!IsStarted())
  136. Run();
  137. return true;
  138. }
  139. void BackgroundLoader::WaitForResource(StringHash type, StringHash nameHash)
  140. {
  141. backgroundLoadMutex_.Acquire();
  142. // Check if the resource in question is being background loaded
  143. Pair<StringHash, StringHash> key = MakePair(type, nameHash);
  144. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Find(key);
  145. if (i != backgroundLoadQueue_.End())
  146. {
  147. backgroundLoadMutex_.Release();
  148. {
  149. Resource* resource = i->second_.resource_;
  150. HiresTimer waitTimer;
  151. bool didWait = false;
  152. for (;;)
  153. {
  154. unsigned numDeps = i->second_.dependencies_.Size();
  155. AsyncLoadState state = resource->GetAsyncLoadState();
  156. if (numDeps > 0 || state == ASYNC_QUEUED || state == ASYNC_LOADING)
  157. {
  158. didWait = true;
  159. Time::Sleep(1);
  160. }
  161. else
  162. break;
  163. }
  164. if (didWait)
  165. LOGDEBUG("Waited " + String(waitTimer.GetUSec(false) / 1000) + " ms for background loaded resource " + resource->GetName());
  166. }
  167. // This may take a long time and may potentially wait on other resources, so it is important we do not hold the mutex during this
  168. FinishBackgroundLoading(i->second_);
  169. backgroundLoadMutex_.Acquire();
  170. backgroundLoadQueue_.Erase(i);
  171. backgroundLoadMutex_.Release();
  172. }
  173. else
  174. backgroundLoadMutex_.Release();
  175. }
  176. void BackgroundLoader::FinishResources(int maxMs)
  177. {
  178. if (IsStarted())
  179. {
  180. HiresTimer timer;
  181. backgroundLoadMutex_.Acquire();
  182. for (HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Begin();
  183. i != backgroundLoadQueue_.End();)
  184. {
  185. Resource* resource = i->second_.resource_;
  186. unsigned numDeps = i->second_.dependencies_.Size();
  187. AsyncLoadState state = resource->GetAsyncLoadState();
  188. if (numDeps > 0 || state == ASYNC_QUEUED || state == ASYNC_LOADING)
  189. ++i;
  190. else
  191. {
  192. // Finishing a resource may need it to wait for other resources to load, in which case we can not
  193. // hold on to the mutex
  194. backgroundLoadMutex_.Release();
  195. FinishBackgroundLoading(i->second_);
  196. backgroundLoadMutex_.Acquire();
  197. i = backgroundLoadQueue_.Erase(i);
  198. }
  199. // Break when the time limit passed so that we keep sufficient FPS
  200. if (timer.GetUSec(false) >= maxMs * 1000)
  201. break;
  202. }
  203. backgroundLoadMutex_.Release();
  204. }
  205. }
  206. unsigned BackgroundLoader::GetNumQueuedResources() const
  207. {
  208. MutexLock lock(backgroundLoadMutex_);
  209. return backgroundLoadQueue_.Size();
  210. }
  211. void BackgroundLoader::FinishBackgroundLoading(BackgroundLoadItem& item)
  212. {
  213. Resource* resource = item.resource_;
  214. bool success = resource->GetAsyncLoadState() == ASYNC_SUCCESS;
  215. // If BeginLoad() phase was successful, call EndLoad() and get the final success/failure result
  216. if (success)
  217. {
  218. #ifdef URHO3D_PROFILING
  219. String profileBlockName("Finish" + resource->GetTypeName());
  220. Profiler* profiler = owner_->GetSubsystem<Profiler>();
  221. if (profiler)
  222. profiler->BeginBlock(profileBlockName.CString());
  223. #endif
  224. LOGDEBUG("Finishing background loaded resource " + resource->GetName());
  225. success = resource->EndLoad();
  226. #ifdef URHO3D_PROFILING
  227. if (profiler)
  228. profiler->EndBlock();
  229. #endif
  230. }
  231. resource->SetAsyncLoadState(ASYNC_DONE);
  232. if (!success && item.sendEventOnFailure_)
  233. {
  234. using namespace LoadFailed;
  235. VariantMap& eventData = owner_->GetEventDataMap();
  236. eventData[P_RESOURCENAME] = resource->GetName();
  237. owner_->SendEvent(E_LOADFAILED, eventData);
  238. }
  239. // Send event, either success or failure
  240. {
  241. using namespace ResourceBackgroundLoaded;
  242. VariantMap& eventData = owner_->GetEventDataMap();
  243. eventData[P_RESOURCENAME] = resource->GetName();
  244. eventData[P_SUCCESS] = success;
  245. eventData[P_RESOURCE] = resource;
  246. owner_->SendEvent(E_RESOURCEBACKGROUNDLOADED, eventData);
  247. }
  248. // Store to the cache; use same mechanism as for manual resources
  249. if (success || owner_->GetReturnFailedResources())
  250. owner_->AddManualResource(resource);
  251. }
  252. }