BsResources.cpp 12 KB

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