BsResources.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. unload(loadedResourcePair.second);
  26. }
  27. HResource Resources::load(const Path& filePath, bool loadDependencies)
  28. {
  29. String uuid;
  30. bool foundUUID = getUUIDFromFilePath(filePath, uuid);
  31. if (!foundUUID)
  32. uuid = UUIDGenerator::generateRandom();
  33. return loadInternal(uuid, filePath, true, loadDependencies);
  34. }
  35. HResource Resources::load(const WeakResourceHandle<Resource>& handle, bool loadDependencies)
  36. {
  37. if (handle.mData == nullptr)
  38. return HResource();
  39. String uuid = handle.getUUID();
  40. return loadFromUUID(uuid, false, loadDependencies);
  41. }
  42. HResource Resources::loadAsync(const Path& filePath, bool loadDependencies)
  43. {
  44. String uuid;
  45. bool foundUUID = getUUIDFromFilePath(filePath, uuid);
  46. if (!foundUUID)
  47. uuid = UUIDGenerator::generateRandom();
  48. return loadInternal(uuid, filePath, false, loadDependencies);
  49. }
  50. HResource Resources::loadFromUUID(const String& uuid, bool async, bool loadDependencies)
  51. {
  52. Path filePath;
  53. // Default manifest is at 0th index but all other take priority since Default manifest could
  54. // contain obsolete data.
  55. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  56. {
  57. if((*iter)->uuidToFilePath(uuid, filePath))
  58. break;
  59. }
  60. return loadInternal(uuid, filePath, !async, loadDependencies);
  61. }
  62. HResource Resources::loadInternal(const String& UUID, const Path& filePath, bool synchronous, bool loadDependencies)
  63. {
  64. HResource outputResource;
  65. // Check if resource is already full loaded
  66. bool alreadyLoading = false;
  67. {
  68. BS_LOCK_MUTEX(mLoadedResourceMutex);
  69. auto iterFind = mLoadedResources.find(UUID);
  70. if(iterFind != mLoadedResources.end()) // Resource is already loaded
  71. {
  72. outputResource = iterFind->second;
  73. alreadyLoading = true;
  74. }
  75. }
  76. // Check if resource is already being loaded on a worker thread
  77. bool loadInProgress = false;
  78. if (!alreadyLoading) // If not already detected as loaded
  79. {
  80. {
  81. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  82. auto iterFind2 = mInProgressResources.find(UUID);
  83. if (iterFind2 != mInProgressResources.end())
  84. {
  85. outputResource = iterFind2->second->resource;
  86. alreadyLoading = true;
  87. loadInProgress = true;
  88. }
  89. }
  90. // Previously being loaded as async but now we want it synced, so we wait
  91. if (loadInProgress && synchronous)
  92. outputResource.blockUntilLoaded();
  93. }
  94. // Not loaded and not in progress, start loading of new resource
  95. // (or if already loaded or in progress, load any dependencies)
  96. if (!alreadyLoading)
  97. {
  98. // Check if the handle already exists
  99. BS_LOCK_MUTEX(mLoadedResourceMutex);
  100. auto iterFind = mHandles.find(UUID);
  101. if (iterFind != mHandles.end())
  102. outputResource = iterFind->second.lock();
  103. else
  104. {
  105. outputResource = HResource(UUID);
  106. mHandles[UUID] = outputResource.getWeak();
  107. }
  108. }
  109. // We have nowhere to load from, warn and complete load if a file path was provided,
  110. // otherwise pass through as we might just want to load from memory.
  111. if (filePath.isEmpty())
  112. {
  113. if (!alreadyLoading)
  114. {
  115. gDebug().logWarning("Cannot load resource. Resource with UUID '" + UUID + "' doesn't exist.");
  116. // Complete the load as that the depedency counter is properly reduced, in case this
  117. // is a dependency of some other resource.
  118. loadComplete(outputResource);
  119. return outputResource;
  120. }
  121. }
  122. else if (!FileSystem::isFile(filePath))
  123. {
  124. LOGWRN("Cannot load resource. Specified file: " + filePath.toString() + " doesn't exist.");
  125. // Complete the load as that the depedency counter is properly reduced, in case this
  126. // is a dependency of some other resource.
  127. loadComplete(outputResource);
  128. assert(!loadInProgress); // Resource already being loaded but we can't find its path now?
  129. return outputResource;
  130. }
  131. // Load dependency data if a file path is provided
  132. SPtr<SavedResourceData> savedResourceData;
  133. if (!filePath.isEmpty())
  134. {
  135. FileDecoder fs(filePath);
  136. savedResourceData = std::static_pointer_cast<SavedResourceData>(fs.decode());
  137. }
  138. // If already loading keep the old load operation active, otherwise create a new one
  139. if (!alreadyLoading)
  140. {
  141. {
  142. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  143. ResourceLoadData* loadData = bs_new<ResourceLoadData>(outputResource, 0);
  144. mInProgressResources[UUID] = loadData;
  145. loadData->resource = outputResource;
  146. loadData->remainingDependencies = 1;
  147. loadData->notifyImmediately = synchronous; // Make resource listener trigger before exit if loading synchronously
  148. // Register dependencies and count them so we know when the resource is fully loaded
  149. if (loadDependencies && savedResourceData != nullptr)
  150. {
  151. for (auto& dependency : savedResourceData->getDependencies())
  152. {
  153. if (dependency != UUID)
  154. {
  155. mDependantLoads[dependency].push_back(loadData);
  156. loadData->remainingDependencies++;
  157. }
  158. }
  159. }
  160. }
  161. if (loadDependencies && savedResourceData != nullptr)
  162. {
  163. for (auto& dependency : savedResourceData->getDependencies())
  164. {
  165. loadFromUUID(dependency, !synchronous);
  166. }
  167. }
  168. }
  169. else if (loadDependencies && savedResourceData != nullptr) // Queue dependencies in case they aren't already loaded
  170. {
  171. const Vector<String>& dependencies = savedResourceData->getDependencies();
  172. if (!dependencies.empty())
  173. {
  174. {
  175. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  176. ResourceLoadData* loadData = nullptr;
  177. auto iterFind = mInProgressResources.find(UUID);
  178. if (iterFind == mInProgressResources.end()) // Fully loaded
  179. {
  180. loadData = bs_new<ResourceLoadData>(outputResource, 0);
  181. loadData->resource = outputResource;
  182. loadData->remainingDependencies = 0;
  183. loadData->notifyImmediately = synchronous; // Make resource listener trigger before exit if loading synchronously
  184. mInProgressResources[UUID] = loadData;
  185. }
  186. else
  187. {
  188. loadData = iterFind->second;
  189. }
  190. // Register dependencies and count them so we know when the resource is fully loaded
  191. for (auto& dependency : dependencies)
  192. {
  193. if (dependency != UUID)
  194. {
  195. bool registerDependency = true;
  196. auto iterFind2 = mDependantLoads.find(dependency);
  197. if (iterFind2 != mDependantLoads.end())
  198. {
  199. Vector<ResourceLoadData*>& dependantData = iterFind2->second;
  200. auto iterFind3 = std::find_if(dependantData.begin(), dependantData.end(),
  201. [&](ResourceLoadData* x)
  202. {
  203. return x->resource.getUUID() == outputResource.getUUID();
  204. });
  205. registerDependency = iterFind3 == dependantData.end();
  206. }
  207. if (registerDependency)
  208. {
  209. mDependantLoads[dependency].push_back(loadData);
  210. loadData->remainingDependencies++;
  211. }
  212. }
  213. }
  214. }
  215. for (auto& dependency : dependencies)
  216. loadFromUUID(dependency, !synchronous);
  217. }
  218. }
  219. // Actually start the file read operation if not already loaded or in progress
  220. if (!alreadyLoading && !filePath.isEmpty())
  221. {
  222. // Synchronous or the resource doesn't support async, read the file immediately
  223. if (synchronous || !savedResourceData->allowAsyncLoading())
  224. {
  225. loadCallback(filePath, outputResource);
  226. }
  227. else // Asynchronous, read the file on a worker thread
  228. {
  229. String fileName = filePath.getFilename();
  230. String taskName = "Resource load: " + fileName;
  231. TaskPtr task = Task::create(taskName, std::bind(&Resources::loadCallback, this, filePath, outputResource));
  232. TaskScheduler::instance().addTask(task);
  233. }
  234. }
  235. else // File already loaded or in progress
  236. {
  237. // Complete the load unless its in progress in which case we wait for its worker thread to complete it.
  238. // In case file is already loaded this will only decrement dependency count in case this resource is a dependency.
  239. if (!loadInProgress)
  240. loadComplete(outputResource);
  241. else
  242. {
  243. // In case loading finished in the meantime we cannot be sure at what point ::loadComplete was triggered,
  244. // so trigger it manually so that the dependency count is properly decremented in case this resource
  245. // is a dependency.
  246. BS_LOCK_MUTEX(mLoadedResourceMutex);
  247. auto iterFind = mLoadedResources.find(UUID);
  248. if (iterFind != mLoadedResources.end())
  249. loadComplete(outputResource);
  250. }
  251. }
  252. return outputResource;
  253. }
  254. ResourcePtr Resources::loadFromDiskAndDeserialize(const Path& filePath)
  255. {
  256. FileDecoder fs(filePath);
  257. fs.skip(); // Skipped over saved resource data
  258. std::shared_ptr<IReflectable> loadedData = fs.decode();
  259. if(loadedData == nullptr)
  260. BS_EXCEPT(InternalErrorException, "Unable to load resource.");
  261. if(!loadedData->isDerivedFrom(Resource::getRTTIStatic()))
  262. BS_EXCEPT(InternalErrorException, "Loaded class doesn't derive from Resource.");
  263. ResourcePtr resource = std::static_pointer_cast<Resource>(loadedData);
  264. return resource;
  265. }
  266. void Resources::unload(HResource resource)
  267. {
  268. if (resource == nullptr)
  269. return;
  270. if (!resource.isLoaded(false))
  271. {
  272. bool loadInProgress = false;
  273. {
  274. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  275. auto iterFind2 = mInProgressResources.find(resource.getUUID());
  276. if (iterFind2 != mInProgressResources.end())
  277. loadInProgress = true;
  278. }
  279. if (loadInProgress) // If it's still loading wait until that finishes
  280. resource.blockUntilLoaded();
  281. else
  282. return; // Already unloaded
  283. }
  284. Vector<ResourceDependency> dependencies = Utility::findResourceDependencies(*resource.get());
  285. // Notify external systems before we actually destroy it
  286. onResourceDestroyed(resource);
  287. resource->destroy();
  288. const String& uuid = resource.getUUID();
  289. {
  290. BS_LOCK_MUTEX(mLoadedResourceMutex);
  291. mLoadedResources.erase(uuid);
  292. }
  293. resource.setHandleData(nullptr, uuid);
  294. for (auto& dependency : dependencies)
  295. {
  296. HResource dependantResource = dependency.resource;
  297. // Last reference was kept by the unloaded resource, so unload the dependency too
  298. if ((UINT32)dependantResource.mData->mRefCount == (dependency.numReferences + 1))
  299. {
  300. // TODO - Use count is not thread safe. Meaning it might increase after above check, in
  301. // which case we will be unloading a resource that is in use. I don't see a way around
  302. // it at the moment.
  303. unload(dependantResource);
  304. }
  305. }
  306. }
  307. void Resources::unload(WeakResourceHandle<Resource> resource)
  308. {
  309. HResource handle = resource.lock();
  310. unload(handle);
  311. }
  312. void Resources::unloadAllUnused()
  313. {
  314. Vector<HResource> resourcesToUnload;
  315. {
  316. BS_LOCK_MUTEX(mLoadedResourceMutex);
  317. for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
  318. {
  319. if (iter->second.mData->mRefCount == 1) // We just have this one reference, meaning nothing is using this resource
  320. resourcesToUnload.push_back(iter->second);
  321. }
  322. }
  323. // Note: When unloading multiple resources it's possible that unloading one will also unload
  324. // another resource in "resourcesToUnload". This is fine because "unload" deals with invalid
  325. // handles gracefully.
  326. for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
  327. {
  328. unload(*iter);
  329. }
  330. }
  331. void Resources::save(const HResource& resource, const Path& filePath, bool overwrite)
  332. {
  333. if (resource == nullptr)
  334. return;
  335. if (!resource.isLoaded(false))
  336. {
  337. bool loadInProgress = false;
  338. {
  339. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  340. auto iterFind2 = mInProgressResources.find(resource.getUUID());
  341. if (iterFind2 != mInProgressResources.end())
  342. loadInProgress = true;
  343. }
  344. if (loadInProgress) // If it's still loading wait until that finishes
  345. resource.blockUntilLoaded();
  346. else
  347. return; // Nothing to save
  348. }
  349. bool fileExists = FileSystem::isFile(filePath);
  350. if(fileExists)
  351. {
  352. if(overwrite)
  353. FileSystem::remove(filePath);
  354. else
  355. BS_EXCEPT(InvalidParametersException, "Another file exists at the specified location.");
  356. }
  357. mDefaultResourceManifest->registerResource(resource.getUUID(), filePath);
  358. Vector<ResourceDependency> dependencyList = Utility::findResourceDependencies(*resource.get());
  359. Vector<String> dependencyUUIDs(dependencyList.size());
  360. for (UINT32 i = 0; i < (UINT32)dependencyList.size(); i++)
  361. dependencyUUIDs[i] = dependencyList[i].resource.getUUID();
  362. SPtr<SavedResourceData> resourceData = bs_shared_ptr_new<SavedResourceData>(dependencyUUIDs, resource->allowAsyncLoading());
  363. FileEncoder fs(filePath);
  364. fs.encode(resourceData.get());
  365. fs.encode(resource.get());
  366. }
  367. void Resources::save(const HResource& resource)
  368. {
  369. if (resource == nullptr)
  370. return;
  371. Path path;
  372. if (getFilePathFromUUID(resource.getUUID(), path))
  373. save(resource, path, true);
  374. }
  375. void Resources::update(HResource& handle, const ResourcePtr& resource)
  376. {
  377. handle.setHandleData(resource, handle.getUUID());
  378. onResourceModified(handle);
  379. }
  380. Vector<String> Resources::getDependencies(const Path& filePath)
  381. {
  382. SPtr<SavedResourceData> savedResourceData;
  383. if (!filePath.isEmpty())
  384. {
  385. FileDecoder fs(filePath);
  386. savedResourceData = std::static_pointer_cast<SavedResourceData>(fs.decode());
  387. }
  388. return savedResourceData->getDependencies();
  389. }
  390. void Resources::registerResourceManifest(const ResourceManifestPtr& manifest)
  391. {
  392. if(manifest->getName() == "Default")
  393. return;
  394. auto findIter = std::find(mResourceManifests.begin(), mResourceManifests.end(), manifest);
  395. if(findIter == mResourceManifests.end())
  396. mResourceManifests.push_back(manifest);
  397. else
  398. *findIter = manifest;
  399. }
  400. void Resources::unregisterResourceManifest(const ResourceManifestPtr& manifest)
  401. {
  402. if (manifest->getName() == "Default")
  403. return;
  404. auto findIter = std::find(mResourceManifests.begin(), mResourceManifests.end(), manifest);
  405. if (findIter != mResourceManifests.end())
  406. mResourceManifests.erase(findIter);
  407. }
  408. ResourceManifestPtr Resources::getResourceManifest(const String& name) const
  409. {
  410. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  411. {
  412. if(name == (*iter)->getName())
  413. return (*iter);
  414. }
  415. return nullptr;
  416. }
  417. bool Resources::isLoaded(const String& uuid, bool checkInProgress)
  418. {
  419. if (checkInProgress)
  420. {
  421. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  422. auto iterFind2 = mInProgressResources.find(uuid);
  423. if (iterFind2 != mInProgressResources.end())
  424. {
  425. return true;
  426. }
  427. {
  428. BS_LOCK_MUTEX(mLoadedResourceMutex);
  429. auto iterFind = mLoadedResources.find(uuid);
  430. if (iterFind != mLoadedResources.end())
  431. {
  432. return true;
  433. }
  434. }
  435. }
  436. return false;
  437. }
  438. HResource Resources::_createResourceHandle(const ResourcePtr& obj)
  439. {
  440. String uuid = UUIDGenerator::generateRandom();
  441. HResource newHandle(obj, uuid);
  442. {
  443. BS_LOCK_MUTEX(mLoadedResourceMutex);
  444. mLoadedResources[uuid] = newHandle;
  445. mHandles[uuid] = newHandle.getWeak();
  446. }
  447. return newHandle;
  448. }
  449. HResource Resources::_getResourceHandle(const String& uuid)
  450. {
  451. {
  452. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  453. auto iterFind2 = mInProgressResources.find(uuid);
  454. if (iterFind2 != mInProgressResources.end())
  455. {
  456. return iterFind2->second->resource;
  457. }
  458. {
  459. BS_LOCK_MUTEX(mLoadedResourceMutex);
  460. auto iterFind = mLoadedResources.find(uuid);
  461. if (iterFind != mLoadedResources.end()) // Resource is already loaded
  462. {
  463. return iterFind->second;
  464. }
  465. auto iterFind3 = mHandles.find(uuid);
  466. if (iterFind3 != mHandles.end()) // Not loaded, but handle does exist
  467. {
  468. return iterFind3->second.lock();
  469. }
  470. // Create new handle
  471. HResource handle(uuid);
  472. mHandles[uuid] = handle.getWeak();
  473. return handle;
  474. }
  475. }
  476. }
  477. bool Resources::getFilePathFromUUID(const String& uuid, Path& filePath) const
  478. {
  479. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  480. {
  481. if((*iter)->uuidToFilePath(uuid, filePath))
  482. return true;
  483. }
  484. return false;
  485. }
  486. bool Resources::getUUIDFromFilePath(const Path& path, String& uuid) const
  487. {
  488. Path manifestPath = path;
  489. if (!manifestPath.isAbsolute())
  490. manifestPath.makeAbsolute(FileSystem::getWorkingDirectoryPath());
  491. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  492. {
  493. if ((*iter)->filePathToUUID(manifestPath, uuid))
  494. return true;
  495. }
  496. return false;
  497. }
  498. void Resources::loadComplete(HResource& resource)
  499. {
  500. String uuid = resource.getUUID();
  501. ResourceLoadData* myLoadData = nullptr;
  502. bool finishLoad = true;
  503. Vector<ResourceLoadData*> dependantLoads;
  504. {
  505. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  506. auto iterFind = mInProgressResources.find(uuid);
  507. if (iterFind != mInProgressResources.end())
  508. {
  509. myLoadData = iterFind->second;
  510. finishLoad = myLoadData->remainingDependencies == 0;
  511. if (finishLoad)
  512. mInProgressResources.erase(iterFind);
  513. }
  514. auto iterFind2 = mDependantLoads.find(uuid);
  515. if (iterFind2 != mDependantLoads.end())
  516. dependantLoads = iterFind2->second;
  517. if (finishLoad)
  518. {
  519. mDependantLoads.erase(uuid);
  520. // If loadedData is null then we're probably completing load on an already loaded resource, triggered
  521. // by its dependencies.
  522. if (myLoadData != nullptr && myLoadData->loadedData != nullptr)
  523. {
  524. BS_LOCK_MUTEX(mLoadedResourceMutex);
  525. mLoadedResources[uuid] = resource;
  526. mHandles[uuid] = resource.getWeak();
  527. resource.setHandleData(myLoadData->loadedData, uuid);
  528. }
  529. for (auto& dependantLoad : dependantLoads)
  530. dependantLoad->remainingDependencies--;
  531. }
  532. }
  533. for (auto& dependantLoad : dependantLoads)
  534. loadComplete(dependantLoad->resource);
  535. if (finishLoad && myLoadData != nullptr)
  536. {
  537. onResourceLoaded(resource);
  538. // This should only ever be true on the main thread
  539. if (myLoadData->notifyImmediately)
  540. ResourceListenerManager::instance().notifyListeners(uuid);
  541. bs_delete(myLoadData);
  542. }
  543. }
  544. void Resources::loadCallback(const Path& filePath, HResource& resource)
  545. {
  546. ResourcePtr rawResource = loadFromDiskAndDeserialize(filePath);
  547. {
  548. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  549. // Check if all my dependencies are loaded
  550. ResourceLoadData* myLoadData = mInProgressResources[resource.getUUID()];
  551. myLoadData->loadedData = rawResource;
  552. myLoadData->remainingDependencies--;
  553. }
  554. loadComplete(resource);
  555. }
  556. BS_CORE_EXPORT Resources& gResources()
  557. {
  558. return Resources::instance();
  559. }
  560. }