BsResources.cpp 13 KB

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