CmResources.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. #include "CmResources.h"
  2. #include "CmResource.h"
  3. #include "CmException.h"
  4. #include "CmFileSerializer.h"
  5. #include "CmFileSystem.h"
  6. #include "CmUUID.h"
  7. #include "CmPath.h"
  8. #include "CmDebug.h"
  9. #include "CmResourcesRTTI.h"
  10. namespace CamelotFramework
  11. {
  12. bool Resources::ResourceRequestHandler::canHandleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
  13. {
  14. return true;
  15. }
  16. WorkQueue::Response* Resources::ResourceRequestHandler::handleRequest(WorkQueue::Request* req, const WorkQueue* srcQ)
  17. {
  18. ResourceLoadRequestPtr resRequest = boost::any_cast<ResourceLoadRequestPtr>(req->getData());
  19. ResourceLoadResponsePtr resResponse = cm_shared_ptr<Resources::ResourceLoadResponse, ScratchAlloc>();
  20. resResponse->rawResource = gResources().loadFromDiskAndDeserialize(resRequest->filePath);
  21. return cm_new<WorkQueue::Response, ScratchAlloc>(req, true, resResponse);
  22. }
  23. bool Resources::ResourceResponseHandler::canHandleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
  24. {
  25. return true;
  26. }
  27. void Resources::ResourceResponseHandler::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
  28. {
  29. ResourceLoadRequestPtr resRequest = boost::any_cast<ResourceLoadRequestPtr>(res->getRequest()->getData());
  30. if(res->getRequest()->getAborted())
  31. return;
  32. gResources().notifyResourceLoadingFinished(resRequest->resource);
  33. if(res->succeeded())
  34. {
  35. ResourceLoadResponsePtr resResponse = boost::any_cast<ResourceLoadResponsePtr>(res->getData());
  36. // This should be thread safe without any sync primitives, if other threads read a few cycles out of date value
  37. // and think this resource isn't created when it really is, it hardly makes any difference
  38. resRequest->resource.resolve(resResponse->rawResource);
  39. if(!gResources().metaExists_UUID(resResponse->rawResource->getUUID()))
  40. {
  41. gDebug().logWarning("Loading a resource that doesn't have meta-data. Creating meta-data automatically. Resource path: " + resRequest->filePath);
  42. gResources().addMetaData(resResponse->rawResource->getUUID(), resRequest->filePath);
  43. }
  44. gResources().notifyNewResourceLoaded(resRequest->resource);
  45. }
  46. else
  47. {
  48. gDebug().logWarning("Resource load request failed.");
  49. }
  50. }
  51. Resources::Resources(const String& metaDataFolder)
  52. :mRequestHandler(nullptr), mResponseHandler(nullptr), mWorkQueue(nullptr)
  53. {
  54. mMetaDataFolderPath = metaDataFolder;
  55. if(!FileSystem::dirExists(mMetaDataFolderPath))
  56. {
  57. FileSystem::createDir(mMetaDataFolderPath);
  58. }
  59. loadMetaData();
  60. mWorkQueue = cm_new<WorkQueue>();
  61. mWorkQueueChannel = mWorkQueue->getChannel("Resources");
  62. mRequestHandler = cm_new<ResourceRequestHandler>();
  63. mResponseHandler = cm_new<ResourceResponseHandler>();
  64. mWorkQueue->addRequestHandler(mWorkQueueChannel, mRequestHandler);
  65. mWorkQueue->addResponseHandler(mWorkQueueChannel, mResponseHandler);
  66. // TODO Low priority - I might want to make this more global so other classes can use it
  67. #if CM_THREAD_SUPPORT
  68. mWorkQueue->setWorkerThreadCount(CM_THREAD_HARDWARE_CONCURRENCY);
  69. #endif
  70. mWorkQueue->startup();
  71. }
  72. Resources::~Resources()
  73. {
  74. if(mWorkQueue)
  75. {
  76. if(mRequestHandler != nullptr)
  77. mWorkQueue->removeRequestHandler(mWorkQueueChannel, mRequestHandler);
  78. if(mResponseHandler != nullptr)
  79. mWorkQueue->removeResponseHandler(mWorkQueueChannel, mResponseHandler);
  80. mWorkQueue->shutdown();
  81. cm_delete(mWorkQueue);
  82. }
  83. if(mRequestHandler != nullptr)
  84. cm_delete(mRequestHandler);
  85. if(mResponseHandler != nullptr)
  86. cm_delete(mResponseHandler);
  87. }
  88. HResource Resources::load(const String& filePath)
  89. {
  90. return loadInternal(filePath, true);
  91. }
  92. HResource Resources::loadAsync(const String& filePath)
  93. {
  94. return loadInternal(filePath, false);
  95. }
  96. HResource Resources::loadFromUUID(const String& uuid)
  97. {
  98. if(!metaExists_UUID(uuid))
  99. {
  100. gDebug().logWarning("Cannot load resource. Resource with UUID '" + uuid + "' doesn't exist.");
  101. return HResource();
  102. }
  103. ResourceMetaDataPtr metaEntry = mResourceMetaData[uuid];
  104. return load(metaEntry->mPath);
  105. }
  106. HResource Resources::loadFromUUIDAsync(const String& uuid)
  107. {
  108. if(!metaExists_UUID(uuid))
  109. {
  110. gDebug().logWarning("Cannot load resource. Resource with UUID '" + uuid + "' doesn't exist.");
  111. return HResource();
  112. }
  113. ResourceMetaDataPtr metaEntry = mResourceMetaData[uuid];
  114. return loadAsync(metaEntry->mPath);
  115. }
  116. HResource Resources::loadInternal(const String& filePath, bool synchronous)
  117. {
  118. // TODO Low priority - Right now I don't allow loading of resources that don't have meta-data, because I need to know resources UUID
  119. // at this point. And I can't do that without having meta-data. Other option is to partially load the resource to read the UUID but due to the
  120. // nature of the serializer it could complicate things. (But possible if this approach proves troublesome)
  121. // The reason I need the UUID is that when resource is loaded Async, the returned ResourceHandle needs to have a valid UUID, in case I assign that
  122. // ResourceHandle to something and then save that something. If I didn't assign it, the saved ResourceHandle would have a blank (i.e. invalid) UUID.
  123. if(!metaExists_Path(filePath))
  124. {
  125. CM_EXCEPT(InternalErrorException, "Cannot load resource that isn't registered in the meta database. Call Resources::create first.");
  126. }
  127. String uuid = getUUIDFromPath(filePath);
  128. {
  129. CM_LOCK_MUTEX(mLoadedResourceMutex);
  130. auto iterFind = mLoadedResources.find(uuid);
  131. if(iterFind != mLoadedResources.end()) // Resource is already loaded
  132. {
  133. return iterFind->second;
  134. }
  135. }
  136. bool resourceLoadingInProgress = false;
  137. HResource existingResource;
  138. {
  139. CM_LOCK_MUTEX(mInProgressResourcesMutex);
  140. auto iterFind2 = mInProgressResources.find(uuid);
  141. if(iterFind2 != mInProgressResources.end())
  142. {
  143. existingResource = iterFind2->second.resource;
  144. resourceLoadingInProgress = true;
  145. }
  146. }
  147. if(resourceLoadingInProgress) // We're already loading this resource
  148. {
  149. if(!synchronous)
  150. return existingResource;
  151. else
  152. {
  153. // Previously being loaded as async but now we want it synced, so we wait
  154. existingResource.synchronize();
  155. return existingResource;
  156. }
  157. }
  158. if(!FileSystem::fileExists(filePath))
  159. {
  160. gDebug().logWarning("Specified file: " + filePath + " doesn't exist.");
  161. return HResource();
  162. }
  163. HResource newResource;
  164. newResource.setUUID(uuid); // UUID needs to be set immediately if the resource gets loaded async
  165. ResourceLoadRequestPtr resRequest = cm_shared_ptr<Resources::ResourceLoadRequest, ScratchAlloc>();
  166. resRequest->filePath = filePath;
  167. resRequest->resource = newResource;
  168. WorkQueue::RequestID requestId = mWorkQueue->peekNextFreeRequestId();
  169. ResourceAsyncOp newAsyncOp;
  170. newAsyncOp.resource = newResource;
  171. newAsyncOp.requestID = requestId;
  172. {
  173. CM_LOCK_MUTEX(mInProgressResourcesMutex);
  174. mInProgressResources[uuid] = newAsyncOp;
  175. }
  176. mWorkQueue->addRequest(mWorkQueueChannel, resRequest, 0, synchronous);
  177. return newResource;
  178. }
  179. ResourcePtr Resources::loadFromDiskAndDeserialize(const String& filePath)
  180. {
  181. FileSerializer fs;
  182. std::shared_ptr<IReflectable> loadedData = fs.decode(filePath);
  183. if(loadedData == nullptr)
  184. CM_EXCEPT(InternalErrorException, "Unable to load resource.");
  185. if(!loadedData->isDerivedFrom(Resource::getRTTIStatic()))
  186. CM_EXCEPT(InternalErrorException, "Loaded class doesn't derive from Resource.");
  187. ResourcePtr resource = std::static_pointer_cast<Resource>(loadedData);
  188. return resource;
  189. }
  190. void Resources::unload(HResource resource)
  191. {
  192. if(!resource.isLoaded()) // If it's still loading wait until that finishes
  193. resource.synchronize();
  194. resource->destroy();
  195. {
  196. CM_LOCK_MUTEX(mLoadedResourceMutex);
  197. mLoadedResources.erase(resource.getUUID());
  198. }
  199. }
  200. void Resources::unloadAllUnused()
  201. {
  202. Vector<HResource>::type resourcesToUnload;
  203. {
  204. CM_LOCK_MUTEX(mLoadedResourceMutex);
  205. for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
  206. {
  207. if(iter->second.getInternalPtr().unique()) // We just have this one reference, meaning nothing is using this resource
  208. resourcesToUnload.push_back(iter->second);
  209. }
  210. }
  211. for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
  212. {
  213. unload(*iter);
  214. }
  215. }
  216. void Resources::create(HResource resource, const String& filePath, bool overwrite)
  217. {
  218. if(resource == nullptr)
  219. CM_EXCEPT(InvalidParametersException, "Trying to save an uninitialized resource.");
  220. resource.synchronize();
  221. if(metaExists_UUID(resource->getUUID()))
  222. CM_EXCEPT(InvalidParametersException, "Specified resource already exists.");
  223. bool fileExists = FileSystem::fileExists(filePath);
  224. const String& existingUUID = getUUIDFromPath(filePath);
  225. bool metaExists = metaExists_UUID(existingUUID);
  226. if(fileExists)
  227. {
  228. if(overwrite)
  229. FileSystem::remove(filePath);
  230. else
  231. CM_EXCEPT(InvalidParametersException, "Another file exists at the specified location.");
  232. }
  233. if(metaExists)
  234. removeMetaData(existingUUID);
  235. addMetaData(resource->getUUID(), filePath);
  236. save(resource);
  237. {
  238. CM_LOCK_MUTEX(mLoadedResourceMutex);
  239. mLoadedResources[resource->getUUID()] = resource;
  240. }
  241. }
  242. void Resources::save(HResource resource)
  243. {
  244. if(!resource.isLoaded())
  245. resource.synchronize();
  246. if(!metaExists_UUID(resource->getUUID()))
  247. CM_EXCEPT(InvalidParametersException, "Cannot find resource meta-data. Please call Resources::create before trying to save the resource.");
  248. const String& filePath = getPathFromUUID(resource->getUUID());
  249. FileSerializer fs;
  250. fs.encode(resource.get(), filePath);
  251. }
  252. void Resources::loadMetaData()
  253. {
  254. Vector<String>::type allFiles = FileSystem::getFiles(mMetaDataFolderPath);
  255. for(auto iter = allFiles.begin(); iter != allFiles.end(); ++iter)
  256. {
  257. String& path = *iter;
  258. if(Path::hasExtension(path, "resmeta"))
  259. {
  260. FileSerializer fs;
  261. std::shared_ptr<IReflectable> loadedData = fs.decode(path);
  262. ResourceMetaDataPtr metaData = std::static_pointer_cast<ResourceMetaData>(loadedData);
  263. mResourceMetaData[metaData->mUUID] = metaData;
  264. mResourceMetaData_FilePath[metaData->mPath] = metaData;
  265. }
  266. }
  267. }
  268. void Resources::saveMetaData(const ResourceMetaDataPtr metaData)
  269. {
  270. String fullPath = Path::combine(mMetaDataFolderPath, metaData->mUUID + ".resmeta");
  271. FileSerializer fs;
  272. fs.encode(metaData.get(), fullPath);
  273. }
  274. void Resources::removeMetaData(const String& uuid)
  275. {
  276. String fullPath = Path::combine(mMetaDataFolderPath, uuid + ".resmeta");
  277. FileSystem::remove(fullPath);
  278. auto iter = mResourceMetaData.find(uuid);
  279. if(iter != mResourceMetaData.end())
  280. {
  281. mResourceMetaData.erase(iter);
  282. mResourceMetaData_FilePath.erase(iter->second->mPath);
  283. }
  284. else
  285. gDebug().logWarning("Trying to remove meta data that doesn't exist.");
  286. }
  287. void Resources::addMetaData(const String& uuid, const String& filePath)
  288. {
  289. if(metaExists_Path(filePath))
  290. CM_EXCEPT(InvalidParametersException, "Resource with the path '" + filePath + "' already exists.");
  291. if(metaExists_UUID(uuid))
  292. CM_EXCEPT(InternalErrorException, "Resource with the same UUID already exists. UUID: " + uuid);
  293. ResourceMetaDataPtr dbEntry = cm_shared_ptr<ResourceMetaData>();
  294. dbEntry->mPath = filePath;
  295. dbEntry->mUUID = uuid;
  296. mResourceMetaData[uuid] = dbEntry;
  297. mResourceMetaData_FilePath[filePath] = dbEntry;
  298. saveMetaData(dbEntry);
  299. }
  300. void Resources::updateMetaData(const String& uuid, const String& newFilePath)
  301. {
  302. if(!metaExists_UUID(uuid))
  303. {
  304. CM_EXCEPT(InvalidParametersException, "Cannot update a resource that doesn't exist. UUID: " + uuid + ". File path: " + newFilePath);
  305. }
  306. ResourceMetaDataPtr dbEntry = mResourceMetaData[uuid];
  307. dbEntry->mPath = newFilePath;
  308. saveMetaData(dbEntry);
  309. }
  310. const String& Resources::getPathFromUUID(const String& uuid) const
  311. {
  312. auto findIter = mResourceMetaData.find(uuid);
  313. if(findIter != mResourceMetaData.end())
  314. return findIter->second->mPath;
  315. else
  316. return StringUtil::BLANK;
  317. }
  318. const String& Resources::getUUIDFromPath(const String& path) const
  319. {
  320. auto findIter = mResourceMetaData_FilePath.find(path);
  321. if(findIter != mResourceMetaData_FilePath.end())
  322. return findIter->second->mUUID;
  323. else
  324. return StringUtil::BLANK;
  325. }
  326. bool Resources::metaExists_UUID(const String& uuid) const
  327. {
  328. auto findIter = mResourceMetaData.find(uuid);
  329. return findIter != mResourceMetaData.end();
  330. }
  331. bool Resources::metaExists_Path(const String& path) const
  332. {
  333. auto findIter = mResourceMetaData_FilePath.find(path);
  334. return findIter != mResourceMetaData_FilePath.end();
  335. }
  336. void Resources::notifyResourceLoadingFinished(HResource& handle)
  337. {
  338. CM_LOCK_MUTEX(mInProgressResourcesMutex);
  339. mInProgressResources.erase(handle.getUUID());
  340. }
  341. void Resources::notifyNewResourceLoaded(HResource& handle)
  342. {
  343. CM_LOCK_MUTEX(mLoadedResourceMutex);
  344. mLoadedResources[handle.getUUID()] = handle;
  345. }
  346. CM_EXPORT Resources& gResources()
  347. {
  348. return Resources::instance();
  349. }
  350. /************************************************************************/
  351. /* SERIALIZATION */
  352. /************************************************************************/
  353. RTTITypeBase* Resources::ResourceMetaData::getRTTIStatic()
  354. {
  355. return ResourceMetaDataRTTI::instance();
  356. }
  357. RTTITypeBase* Resources::ResourceMetaData::getRTTI() const
  358. {
  359. return Resources::ResourceMetaData::getRTTIStatic();
  360. }
  361. }