BsResources.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. //__________________________ Banshee Project - A modern game development toolkit _________________________________//
  2. //_____________________________________ www.banshee-project.com __________________________________________________//
  3. //________________________ Copyright (c) 2014 Marko Pintera. All rights reserved. ________________________________//
  4. #include "BsResources.h"
  5. #include "BsResource.h"
  6. #include "BsResourceManifest.h"
  7. #include "BsException.h"
  8. #include "BsFileSerializer.h"
  9. #include "BsFileSystem.h"
  10. #include "BsTaskScheduler.h"
  11. #include "BsUUID.h"
  12. #include "BsPath.h"
  13. #include "BsDebug.h"
  14. namespace BansheeEngine
  15. {
  16. Resources::Resources()
  17. {
  18. mDefaultResourceManifest = ResourceManifest::create("Default");
  19. mResourceManifests.push_back(mDefaultResourceManifest);
  20. }
  21. Resources::~Resources()
  22. {
  23. // Unload and invalidate all resources
  24. UnorderedMap<String, HResource> loadedResourcesCopy = mLoadedResources;
  25. for (auto& loadedResourcePair : loadedResourcesCopy)
  26. {
  27. unload(loadedResourcePair.second);
  28. // Invalidate the handle
  29. loadedResourcePair.second._setHandleData(nullptr, "");
  30. }
  31. }
  32. HResource Resources::load(const Path& filePath)
  33. {
  34. return loadInternal(filePath, true);
  35. }
  36. HResource Resources::loadAsync(const Path& filePath)
  37. {
  38. return loadInternal(filePath, false);
  39. }
  40. HResource Resources::loadFromUUID(const String& uuid)
  41. {
  42. Path filePath;
  43. bool foundPath = false;
  44. // Default manifest is at 0th index but all other take priority since Default manifest could
  45. // contain obsolete data.
  46. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  47. {
  48. if((*iter)->uuidToFilePath(uuid, filePath))
  49. {
  50. foundPath = true;
  51. break;
  52. }
  53. }
  54. if(!foundPath)
  55. {
  56. gDebug().logWarning("Cannot load resource. Resource with UUID '" + uuid + "' doesn't exist.");
  57. return HResource();
  58. }
  59. return load(filePath);
  60. }
  61. HResource Resources::loadFromUUIDAsync(const String& uuid)
  62. {
  63. Path filePath;
  64. bool foundPath = false;
  65. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  66. {
  67. if((*iter)->uuidToFilePath(uuid, filePath))
  68. {
  69. foundPath = true;
  70. break;
  71. }
  72. }
  73. if(!foundPath)
  74. {
  75. gDebug().logWarning("Cannot load resource. Resource with UUID '" + uuid + "' doesn't exist.");
  76. return HResource();
  77. }
  78. return loadAsync(filePath);
  79. }
  80. HResource Resources::loadInternal(const Path& filePath, bool synchronous)
  81. {
  82. String uuid;
  83. bool foundUUID = false;
  84. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  85. {
  86. if((*iter)->filePathToUUID(filePath, uuid))
  87. {
  88. foundUUID = true;
  89. break;
  90. }
  91. }
  92. if(!foundUUID)
  93. uuid = UUIDGenerator::instance().generateRandom();
  94. {
  95. BS_LOCK_MUTEX(mLoadedResourceMutex);
  96. auto iterFind = mLoadedResources.find(uuid);
  97. if(iterFind != mLoadedResources.end()) // Resource is already loaded
  98. {
  99. return iterFind->second;
  100. }
  101. }
  102. bool resourceLoadingInProgress = false;
  103. HResource existingResource;
  104. {
  105. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  106. auto iterFind2 = mInProgressResources.find(uuid);
  107. if(iterFind2 != mInProgressResources.end())
  108. {
  109. existingResource = iterFind2->second;
  110. resourceLoadingInProgress = true;
  111. }
  112. }
  113. if(resourceLoadingInProgress) // We're already loading this resource
  114. {
  115. if(!synchronous)
  116. return existingResource;
  117. else
  118. {
  119. // Previously being loaded as async but now we want it synced, so we wait
  120. existingResource.synchronize();
  121. return existingResource;
  122. }
  123. }
  124. if(!FileSystem::isFile(filePath))
  125. {
  126. gDebug().logWarning("Specified file: " + filePath.toString() + " doesn't exist.");
  127. return HResource();
  128. }
  129. HResource newResource(uuid);
  130. {
  131. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  132. mInProgressResources[uuid] = newResource;
  133. }
  134. if(synchronous)
  135. {
  136. loadCallback(filePath, newResource);
  137. }
  138. else
  139. {
  140. String fileName = filePath.getFilename();
  141. String taskName = "Resource load: " + fileName;
  142. TaskPtr task = Task::create(taskName, std::bind(&Resources::loadCallback, this, filePath, newResource));
  143. TaskScheduler::instance().addTask(task);
  144. }
  145. return newResource;
  146. }
  147. ResourcePtr Resources::loadFromDiskAndDeserialize(const Path& filePath)
  148. {
  149. FileSerializer fs;
  150. std::shared_ptr<IReflectable> loadedData = fs.decode(filePath);
  151. if(loadedData == nullptr)
  152. BS_EXCEPT(InternalErrorException, "Unable to load resource.");
  153. if(!loadedData->isDerivedFrom(Resource::getRTTIStatic()))
  154. BS_EXCEPT(InternalErrorException, "Loaded class doesn't derive from Resource.");
  155. ResourcePtr resource = std::static_pointer_cast<Resource>(loadedData);
  156. return resource;
  157. }
  158. void Resources::unload(HResource resource)
  159. {
  160. if(!resource.isLoaded()) // If it's still loading wait until that finishes
  161. resource.synchronize();
  162. resource->destroy();
  163. {
  164. BS_LOCK_MUTEX(mLoadedResourceMutex);
  165. mLoadedResources.erase(resource.getUUID());
  166. }
  167. }
  168. void Resources::unloadAllUnused()
  169. {
  170. Vector<HResource> resourcesToUnload;
  171. {
  172. BS_LOCK_MUTEX(mLoadedResourceMutex);
  173. for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
  174. {
  175. if(iter->second.getInternalPtr().unique()) // We just have this one reference, meaning nothing is using this resource
  176. resourcesToUnload.push_back(iter->second);
  177. }
  178. }
  179. for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
  180. {
  181. unload(*iter);
  182. }
  183. }
  184. void Resources::save(HResource resource, const Path& filePath, bool overwrite)
  185. {
  186. if(!resource.isLoaded())
  187. resource.synchronize();
  188. bool fileExists = FileSystem::isFile(filePath);
  189. if(fileExists)
  190. {
  191. if(overwrite)
  192. FileSystem::remove(filePath);
  193. else
  194. BS_EXCEPT(InvalidParametersException, "Another file exists at the specified location.");
  195. }
  196. mDefaultResourceManifest->registerResource(resource.getUUID(), filePath);
  197. FileSerializer fs;
  198. fs.encode(resource.get(), filePath);
  199. }
  200. void Resources::registerResourceManifest(const ResourceManifestPtr& manifest)
  201. {
  202. if(manifest->getName() == "Default")
  203. return;
  204. auto findIter = std::find(mResourceManifests.begin(), mResourceManifests.end(), manifest);
  205. if(findIter == mResourceManifests.end())
  206. mResourceManifests.push_back(manifest);
  207. else
  208. *findIter = manifest;
  209. }
  210. ResourceManifestPtr Resources::getResourceManifest(const String& name) const
  211. {
  212. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  213. {
  214. if(name == (*iter)->getName())
  215. return (*iter);
  216. }
  217. return nullptr;
  218. }
  219. HResource Resources::_createResourceHandle(const ResourcePtr& obj)
  220. {
  221. String uuid = UUIDGenerator::instance().generateRandom();
  222. HResource newHandle(obj, uuid);
  223. {
  224. BS_LOCK_MUTEX(mLoadedResourceMutex);
  225. mLoadedResources[uuid] = newHandle;
  226. }
  227. return newHandle;
  228. }
  229. bool Resources::getFilePathFromUUID(const String& uuid, Path& filePath) const
  230. {
  231. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  232. {
  233. if((*iter)->uuidToFilePath(uuid, filePath))
  234. return true;
  235. }
  236. return false;
  237. }
  238. bool Resources::getUUIDFromFilePath(const Path& path, String& uuid) const
  239. {
  240. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  241. {
  242. if((*iter)->filePathToUUID(path, uuid))
  243. return true;
  244. }
  245. return false;
  246. }
  247. void Resources::loadCallback(const Path& filePath, HResource& resource)
  248. {
  249. ResourcePtr rawResource = loadFromDiskAndDeserialize(filePath);
  250. {
  251. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  252. mInProgressResources.erase(resource.getUUID());
  253. }
  254. resource._setHandleData(rawResource, resource.getUUID());
  255. {
  256. BS_LOCK_MUTEX(mLoadedResourceMutex);
  257. mLoadedResources[resource.getUUID()] = resource;
  258. }
  259. }
  260. BS_CORE_EXPORT Resources& gResources()
  261. {
  262. return Resources::instance();
  263. }
  264. }