BsResources.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #include "BsResources.h"
  2. #include "BsResource.h"
  3. #include "BsResourceManifest.h"
  4. #include "BsException.h"
  5. #include "BsFileSerializer.h"
  6. #include "BsFileSystem.h"
  7. #include "BsTaskScheduler.h"
  8. #include "BsUUID.h"
  9. #include "BsDebug.h"
  10. #include "BsUtility.h"
  11. #include "BsSavedResourceData.h"
  12. #include "BsResourceListenerManager.h"
  13. namespace BansheeEngine
  14. {
  15. Resources::Resources()
  16. {
  17. mDefaultResourceManifest = ResourceManifest::create("Default");
  18. mResourceManifests.push_back(mDefaultResourceManifest);
  19. }
  20. Resources::~Resources()
  21. {
  22. // Unload and invalidate all resources
  23. UnorderedMap<String, HResource> loadedResourcesCopy = mLoadedResources;
  24. for (auto& loadedResourcePair : loadedResourcesCopy)
  25. {
  26. unload(loadedResourcePair.second);
  27. // Invalidate the handle
  28. loadedResourcePair.second._setHandleData(nullptr, "");
  29. }
  30. }
  31. HResource Resources::load(const Path& filePath)
  32. {
  33. return loadInternal(filePath, true);
  34. }
  35. HResource Resources::loadAsync(const Path& filePath)
  36. {
  37. return loadInternal(filePath, false);
  38. }
  39. HResource Resources::loadFromUUID(const String& uuid, bool async)
  40. {
  41. Path filePath;
  42. bool foundPath = false;
  43. // Default manifest is at 0th index but all other take priority since Default manifest could
  44. // contain obsolete data.
  45. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  46. {
  47. if((*iter)->uuidToFilePath(uuid, filePath))
  48. {
  49. foundPath = true;
  50. break;
  51. }
  52. }
  53. if(!foundPath)
  54. {
  55. gDebug().logWarning("Cannot load resource. Resource with UUID '" + uuid + "' doesn't exist.");
  56. HResource outputResource(uuid);
  57. loadComplete(outputResource);
  58. return outputResource;
  59. }
  60. return loadInternal(filePath, !async);
  61. }
  62. HResource Resources::loadInternal(const Path& filePath, bool synchronous)
  63. {
  64. String uuid;
  65. bool foundUUID = false;
  66. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  67. {
  68. if((*iter)->filePathToUUID(filePath, uuid))
  69. {
  70. foundUUID = true;
  71. break;
  72. }
  73. }
  74. if(!foundUUID)
  75. uuid = UUIDGenerator::instance().generateRandom();
  76. HResource outputResource;
  77. bool alreadyLoading = false;
  78. {
  79. BS_LOCK_MUTEX(mLoadedResourceMutex);
  80. auto iterFind = mLoadedResources.find(uuid);
  81. if(iterFind != mLoadedResources.end()) // Resource is already loaded
  82. {
  83. outputResource = iterFind->second;
  84. alreadyLoading = true;
  85. }
  86. }
  87. if (!alreadyLoading) // If not already detected as loaded
  88. {
  89. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  90. auto iterFind2 = mInProgressResources.find(uuid);
  91. if(iterFind2 != mInProgressResources.end())
  92. {
  93. outputResource = iterFind2->second->resource;
  94. // Previously being loaded as async but now we want it synced, so we wait
  95. if (synchronous)
  96. outputResource.blockUntilLoaded();
  97. alreadyLoading = true;
  98. }
  99. }
  100. // Not loaded and not in progress, start loading of new resource
  101. // (or if already loaded or in progress, load any dependencies)
  102. if (!alreadyLoading)
  103. outputResource = HResource(uuid);
  104. if(!FileSystem::isFile(filePath))
  105. {
  106. gDebug().logWarning("Specified file: " + filePath.toString() + " doesn't exist.");
  107. loadComplete(outputResource);
  108. return outputResource;
  109. }
  110. // Load saved resource data
  111. FileDecoder fs(filePath);
  112. SPtr<SavedResourceData> savedResourceData = std::static_pointer_cast<SavedResourceData>(fs.decode());
  113. // If already loading keep the old load operation active,
  114. // otherwise create a new one
  115. if (!alreadyLoading)
  116. {
  117. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  118. ResourceLoadData* loadData = bs_new<ResourceLoadData>(outputResource, 0);
  119. mInProgressResources[uuid] = loadData;
  120. loadData->resource = outputResource;
  121. loadData->remainingDependencies = 1;
  122. loadData->notifyImmediately = synchronous; // Make resource listener trigger before exit if loading synchronously
  123. for (auto& dependency : savedResourceData->getDependencies())
  124. {
  125. if (dependency != uuid)
  126. {
  127. mDependantLoads[dependency].push_back(loadData);
  128. loadData->remainingDependencies++;
  129. }
  130. }
  131. }
  132. // Load dependencies
  133. {
  134. for (auto& dependency : savedResourceData->getDependencies())
  135. {
  136. loadFromUUID(dependency, !synchronous);
  137. }
  138. }
  139. // Actually queue the load
  140. if (!alreadyLoading)
  141. {
  142. if (synchronous || !savedResourceData->allowAsyncLoading())
  143. {
  144. loadCallback(filePath, outputResource);
  145. }
  146. else
  147. {
  148. String fileName = filePath.getFilename();
  149. String taskName = "Resource load: " + fileName;
  150. TaskPtr task = Task::create(taskName, std::bind(&Resources::loadCallback, this, filePath, outputResource));
  151. TaskScheduler::instance().addTask(task);
  152. }
  153. }
  154. else
  155. loadComplete(outputResource);
  156. return outputResource;
  157. }
  158. ResourcePtr Resources::loadFromDiskAndDeserialize(const Path& filePath)
  159. {
  160. FileDecoder fs(filePath);
  161. fs.skip(); // Skipped over saved resource data
  162. std::shared_ptr<IReflectable> loadedData = fs.decode();
  163. if(loadedData == nullptr)
  164. BS_EXCEPT(InternalErrorException, "Unable to load resource.");
  165. if(!loadedData->isDerivedFrom(Resource::getRTTIStatic()))
  166. BS_EXCEPT(InternalErrorException, "Loaded class doesn't derive from Resource.");
  167. ResourcePtr resource = std::static_pointer_cast<Resource>(loadedData);
  168. return resource;
  169. }
  170. void Resources::unload(HResource resource)
  171. {
  172. if (resource == nullptr)
  173. return;
  174. if (!resource.isLoaded()) // If it's still loading wait until that finishes
  175. {
  176. LOGWRN("Performance warning: Unloading a resource that is still in process of loading "
  177. "causes a stall until resource finishes loading.");
  178. resource.blockUntilLoaded();
  179. }
  180. Vector<ResourceDependency> dependencies = Utility::findResourceDependencies(*resource.get());
  181. // Call this before we actually destroy it
  182. onResourceDestroyed(resource);
  183. resource->destroy();
  184. {
  185. BS_LOCK_MUTEX(mLoadedResourceMutex);
  186. mLoadedResources.erase(resource.getUUID());
  187. }
  188. resource._setHandleData(nullptr, "");
  189. for (auto& dependency : dependencies)
  190. {
  191. HResource dependantResource = dependency.resource;
  192. // Last reference was kept by the unloaded resource, so unload the dependency too
  193. if ((UINT32)dependantResource.mData.use_count() == (dependency.numReferences + 1))
  194. {
  195. // TODO - Use count is not thread safe. Meaning it might increase after above check, in
  196. // which case we will be unloading a resource that is in use. I don't see a way around
  197. // it at the moment.
  198. unload(dependantResource);
  199. }
  200. }
  201. }
  202. void Resources::unloadAllUnused()
  203. {
  204. Vector<HResource> resourcesToUnload;
  205. {
  206. BS_LOCK_MUTEX(mLoadedResourceMutex);
  207. for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
  208. {
  209. if (iter->second.mData.unique()) // We just have this one reference, meaning nothing is using this resource
  210. resourcesToUnload.push_back(iter->second);
  211. }
  212. }
  213. // Note: When unloading multiple resources it's possible that unloading one will also unload
  214. // another resource in "resourcesToUnload". This is fine because "unload" deals with invalid
  215. // handles gracefully.
  216. for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
  217. {
  218. unload(*iter);
  219. }
  220. }
  221. void Resources::save(HResource resource, const Path& filePath, bool overwrite)
  222. {
  223. if(!resource.isLoaded())
  224. resource.blockUntilLoaded();
  225. bool fileExists = FileSystem::isFile(filePath);
  226. if(fileExists)
  227. {
  228. if(overwrite)
  229. FileSystem::remove(filePath);
  230. else
  231. BS_EXCEPT(InvalidParametersException, "Another file exists at the specified location.");
  232. }
  233. mDefaultResourceManifest->registerResource(resource.getUUID(), filePath);
  234. Vector<ResourceDependency> dependencyList = Utility::findResourceDependencies(*resource.get());
  235. Vector<String> dependencyUUIDs(dependencyList.size());
  236. for (UINT32 i = 0; i < (UINT32)dependencyList.size(); i++)
  237. dependencyUUIDs[i] = dependencyList[i].resource.getUUID();
  238. SPtr<SavedResourceData> resourceData = bs_shared_ptr<SavedResourceData>(dependencyUUIDs, resource->allowAsyncLoading());
  239. FileEncoder fs(filePath);
  240. fs.encode(resourceData.get());
  241. fs.encode(resource.get());
  242. }
  243. void Resources::registerResourceManifest(const ResourceManifestPtr& manifest)
  244. {
  245. if(manifest->getName() == "Default")
  246. return;
  247. auto findIter = std::find(mResourceManifests.begin(), mResourceManifests.end(), manifest);
  248. if(findIter == mResourceManifests.end())
  249. mResourceManifests.push_back(manifest);
  250. else
  251. *findIter = manifest;
  252. }
  253. ResourceManifestPtr Resources::getResourceManifest(const String& name) const
  254. {
  255. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  256. {
  257. if(name == (*iter)->getName())
  258. return (*iter);
  259. }
  260. return nullptr;
  261. }
  262. HResource Resources::_createResourceHandle(const ResourcePtr& obj)
  263. {
  264. String uuid = UUIDGenerator::instance().generateRandom();
  265. HResource newHandle(obj, uuid);
  266. {
  267. BS_LOCK_MUTEX(mLoadedResourceMutex);
  268. mLoadedResources[uuid] = newHandle;
  269. }
  270. return newHandle;
  271. }
  272. HResource Resources::_getResourceHandle(const String& uuid)
  273. {
  274. {
  275. BS_LOCK_MUTEX(mLoadedResourceMutex);
  276. auto iterFind = mLoadedResources.find(uuid);
  277. if (iterFind != mLoadedResources.end()) // Resource is already loaded
  278. {
  279. return iterFind->second;
  280. }
  281. }
  282. {
  283. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  284. auto iterFind2 = mInProgressResources.find(uuid);
  285. if (iterFind2 != mInProgressResources.end())
  286. {
  287. return iterFind2->second->resource;
  288. }
  289. }
  290. return HResource();
  291. }
  292. bool Resources::getFilePathFromUUID(const String& uuid, Path& filePath) const
  293. {
  294. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  295. {
  296. if((*iter)->uuidToFilePath(uuid, filePath))
  297. return true;
  298. }
  299. return false;
  300. }
  301. bool Resources::getUUIDFromFilePath(const Path& path, String& uuid) const
  302. {
  303. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  304. {
  305. if((*iter)->filePathToUUID(path, uuid))
  306. return true;
  307. }
  308. return false;
  309. }
  310. void Resources::loadComplete(HResource& resource)
  311. {
  312. String uuid = resource.getUUID();
  313. ResourceLoadData* myLoadData = nullptr;
  314. Vector<ResourceLoadData*> dependantLoads;
  315. {
  316. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  317. auto iterFind = mInProgressResources.find(uuid);
  318. if (iterFind != mInProgressResources.end())
  319. {
  320. myLoadData = iterFind->second;
  321. mInProgressResources.erase(iterFind);
  322. }
  323. dependantLoads = mDependantLoads[uuid];
  324. mDependantLoads.erase(uuid);
  325. }
  326. if (myLoadData != nullptr)
  327. {
  328. {
  329. BS_LOCK_MUTEX(mLoadedResourceMutex);
  330. mLoadedResources[uuid] = resource;
  331. }
  332. resource._setHandleData(myLoadData->loadedData, uuid);
  333. onResourceLoaded(resource);
  334. if (myLoadData->notifyImmediately)
  335. ResourceListenerManager::instance().notifyListeners(uuid);
  336. bs_delete(myLoadData);
  337. }
  338. for (auto& dependantLoad : dependantLoads)
  339. {
  340. dependantLoad->remainingDependencies--;
  341. if (dependantLoad->remainingDependencies == 0)
  342. loadComplete(dependantLoad->resource);
  343. }
  344. }
  345. void Resources::loadCallback(const Path& filePath, HResource& resource)
  346. {
  347. ResourcePtr rawResource = loadFromDiskAndDeserialize(filePath);
  348. bool finishLoad = false;
  349. {
  350. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  351. // Check if all my dependencies are loaded
  352. ResourceLoadData* myLoadData = mInProgressResources[resource.getUUID()];
  353. myLoadData->loadedData = rawResource;
  354. myLoadData->remainingDependencies--;
  355. finishLoad = myLoadData->remainingDependencies == 0;
  356. }
  357. if (finishLoad)
  358. loadComplete(resource);
  359. }
  360. BS_CORE_EXPORT Resources& gResources()
  361. {
  362. return Resources::instance();
  363. }
  364. }