BsResources.cpp 12 KB

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