CmResources.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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.setResourcePtr(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(uuid);
  164. ResourceLoadRequestPtr resRequest = cm_shared_ptr<Resources::ResourceLoadRequest, ScratchAlloc>();
  165. resRequest->filePath = filePath;
  166. resRequest->resource = newResource;
  167. WorkQueue::RequestID requestId = mWorkQueue->peekNextFreeRequestId();
  168. ResourceAsyncOp newAsyncOp;
  169. newAsyncOp.resource = newResource;
  170. newAsyncOp.requestID = requestId;
  171. {
  172. CM_LOCK_MUTEX(mInProgressResourcesMutex);
  173. mInProgressResources[uuid] = newAsyncOp;
  174. }
  175. mWorkQueue->addRequest(mWorkQueueChannel, resRequest, 0, synchronous);
  176. return newResource;
  177. }
  178. ResourcePtr Resources::loadFromDiskAndDeserialize(const String& filePath)
  179. {
  180. FileSerializer fs;
  181. std::shared_ptr<IReflectable> loadedData = fs.decode(filePath);
  182. if(loadedData == nullptr)
  183. CM_EXCEPT(InternalErrorException, "Unable to load resource.");
  184. if(!loadedData->isDerivedFrom(Resource::getRTTIStatic()))
  185. CM_EXCEPT(InternalErrorException, "Loaded class doesn't derive from Resource.");
  186. ResourcePtr resource = std::static_pointer_cast<Resource>(loadedData);
  187. return resource;
  188. }
  189. void Resources::unload(HResource resource)
  190. {
  191. if(!resource.isLoaded()) // If it's still loading wait until that finishes
  192. resource.synchronize();
  193. resource->destroy();
  194. {
  195. CM_LOCK_MUTEX(mLoadedResourceMutex);
  196. mLoadedResources.erase(resource.getUUID());
  197. }
  198. }
  199. void Resources::unloadAllUnused()
  200. {
  201. Vector<HResource>::type resourcesToUnload;
  202. {
  203. CM_LOCK_MUTEX(mLoadedResourceMutex);
  204. for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
  205. {
  206. if(iter->second.getInternalPtr().unique()) // We just have this one reference, meaning nothing is using this resource
  207. resourcesToUnload.push_back(iter->second);
  208. }
  209. }
  210. for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
  211. {
  212. unload(*iter);
  213. }
  214. }
  215. void Resources::create(HResource resource, const String& filePath, bool overwrite)
  216. {
  217. if(resource == nullptr)
  218. CM_EXCEPT(InvalidParametersException, "Trying to save an uninitialized resource.");
  219. resource.synchronize();
  220. if(metaExists_UUID(resource->getUUID()))
  221. CM_EXCEPT(InvalidParametersException, "Specified resource already exists.");
  222. bool fileExists = FileSystem::fileExists(filePath);
  223. const String& existingUUID = getUUIDFromPath(filePath);
  224. bool metaExists = metaExists_UUID(existingUUID);
  225. if(fileExists)
  226. {
  227. if(overwrite)
  228. FileSystem::remove(filePath);
  229. else
  230. CM_EXCEPT(InvalidParametersException, "Another file exists at the specified location.");
  231. }
  232. if(metaExists)
  233. removeMetaData(existingUUID);
  234. addMetaData(resource->getUUID(), filePath);
  235. save(resource);
  236. {
  237. CM_LOCK_MUTEX(mLoadedResourceMutex);
  238. mLoadedResources[resource->getUUID()] = resource;
  239. }
  240. }
  241. void Resources::save(HResource resource)
  242. {
  243. if(!resource.isLoaded())
  244. resource.synchronize();
  245. if(!metaExists_UUID(resource->getUUID()))
  246. CM_EXCEPT(InvalidParametersException, "Cannot find resource meta-data. Please call Resources::create before trying to save the resource.");
  247. const String& filePath = getPathFromUUID(resource->getUUID());
  248. FileSerializer fs;
  249. fs.encode(resource.get(), filePath);
  250. }
  251. void Resources::loadMetaData()
  252. {
  253. Vector<String>::type allFiles = FileSystem::getFiles(mMetaDataFolderPath);
  254. for(auto iter = allFiles.begin(); iter != allFiles.end(); ++iter)
  255. {
  256. String& path = *iter;
  257. if(Path::hasExtension(path, "resmeta"))
  258. {
  259. FileSerializer fs;
  260. std::shared_ptr<IReflectable> loadedData = fs.decode(path);
  261. ResourceMetaDataPtr metaData = std::static_pointer_cast<ResourceMetaData>(loadedData);
  262. mResourceMetaData[metaData->mUUID] = metaData;
  263. mResourceMetaData_FilePath[metaData->mPath] = metaData;
  264. }
  265. }
  266. }
  267. void Resources::saveMetaData(const ResourceMetaDataPtr metaData)
  268. {
  269. String fullPath = Path::combine(mMetaDataFolderPath, metaData->mUUID + ".resmeta");
  270. FileSerializer fs;
  271. fs.encode(metaData.get(), fullPath);
  272. }
  273. void Resources::removeMetaData(const String& uuid)
  274. {
  275. String fullPath = Path::combine(mMetaDataFolderPath, uuid + ".resmeta");
  276. FileSystem::remove(fullPath);
  277. auto iter = mResourceMetaData.find(uuid);
  278. if(iter != mResourceMetaData.end())
  279. {
  280. mResourceMetaData.erase(iter);
  281. mResourceMetaData_FilePath.erase(iter->second->mPath);
  282. }
  283. else
  284. gDebug().logWarning("Trying to remove meta data that doesn't exist.");
  285. }
  286. void Resources::addMetaData(const String& uuid, const String& filePath)
  287. {
  288. if(metaExists_Path(filePath))
  289. CM_EXCEPT(InvalidParametersException, "Resource with the path '" + filePath + "' already exists.");
  290. if(metaExists_UUID(uuid))
  291. CM_EXCEPT(InternalErrorException, "Resource with the same UUID already exists. UUID: " + uuid);
  292. ResourceMetaDataPtr dbEntry = cm_shared_ptr<ResourceMetaData>();
  293. dbEntry->mPath = filePath;
  294. dbEntry->mUUID = uuid;
  295. mResourceMetaData[uuid] = dbEntry;
  296. mResourceMetaData_FilePath[filePath] = dbEntry;
  297. saveMetaData(dbEntry);
  298. }
  299. void Resources::updateMetaData(const String& uuid, const String& newFilePath)
  300. {
  301. if(!metaExists_UUID(uuid))
  302. {
  303. CM_EXCEPT(InvalidParametersException, "Cannot update a resource that doesn't exist. UUID: " + uuid + ". File path: " + newFilePath);
  304. }
  305. ResourceMetaDataPtr dbEntry = mResourceMetaData[uuid];
  306. dbEntry->mPath = newFilePath;
  307. saveMetaData(dbEntry);
  308. }
  309. const String& Resources::getPathFromUUID(const String& uuid) const
  310. {
  311. auto findIter = mResourceMetaData.find(uuid);
  312. if(findIter != mResourceMetaData.end())
  313. return findIter->second->mPath;
  314. else
  315. return StringUtil::BLANK;
  316. }
  317. const String& Resources::getUUIDFromPath(const String& path) const
  318. {
  319. auto findIter = mResourceMetaData_FilePath.find(path);
  320. if(findIter != mResourceMetaData_FilePath.end())
  321. return findIter->second->mUUID;
  322. else
  323. return StringUtil::BLANK;
  324. }
  325. bool Resources::metaExists_UUID(const String& uuid) const
  326. {
  327. auto findIter = mResourceMetaData.find(uuid);
  328. return findIter != mResourceMetaData.end();
  329. }
  330. bool Resources::metaExists_Path(const String& path) const
  331. {
  332. auto findIter = mResourceMetaData_FilePath.find(path);
  333. return findIter != mResourceMetaData_FilePath.end();
  334. }
  335. void Resources::notifyResourceLoadingFinished(HResource& handle)
  336. {
  337. CM_LOCK_MUTEX(mInProgressResourcesMutex);
  338. mInProgressResources.erase(handle.getUUID());
  339. }
  340. void Resources::notifyNewResourceLoaded(HResource& handle)
  341. {
  342. CM_LOCK_MUTEX(mLoadedResourceMutex);
  343. mLoadedResources[handle.getUUID()] = handle;
  344. }
  345. CM_EXPORT Resources& gResources()
  346. {
  347. return Resources::instance();
  348. }
  349. /************************************************************************/
  350. /* SERIALIZATION */
  351. /************************************************************************/
  352. RTTITypeBase* Resources::ResourceMetaData::getRTTIStatic()
  353. {
  354. return ResourceMetaDataRTTI::instance();
  355. }
  356. RTTITypeBase* Resources::ResourceMetaData::getRTTI() const
  357. {
  358. return Resources::ResourceMetaData::getRTTIStatic();
  359. }
  360. }