BsResources.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "BsModule.h"
  6. namespace BansheeEngine
  7. {
  8. /** @addtogroup Resources
  9. * @{
  10. */
  11. /** Flags that can be used to control resource loading. */
  12. enum class ResourceLoadFlag
  13. {
  14. /** No flags. */
  15. None = 0,
  16. /** If enabled all resources referenced by the root resource will be loaded as well. */
  17. LoadDependencies = 1 << 0,
  18. /**
  19. * If enabled the resource system will keep an internal reference to the resource so it doesn't get destroyed with
  20. * it goes out of scope. You can call Resources::release() to release the internal reference. Each call to load will
  21. * create a new internal reference and therefore must be followed by the same number of release calls. If
  22. * dependencies are being loaded, they will not have internal references created regardless of this parameter.
  23. */
  24. KeepInternalRef = 1 << 1,
  25. /**
  26. * Determines if the loaded resource keeps original data loaded. Sometime resources will process loaded data
  27. * and discard the original (e.g. uncompressing audio on load). This flag can prevent the resource from discarding
  28. * the original data. The original data might be required for saving the resource (via Resources::save), but will
  29. * use up extra memory. Normally you want to keep this enabled if you plan on saving the resource to disk.
  30. */
  31. KeepSourceData = 1 << 2,
  32. /** Default set of flags used for resource loading. */
  33. Default = LoadDependencies | KeepInternalRef
  34. };
  35. typedef Flags<ResourceLoadFlag> ResourceLoadFlags;
  36. BS_FLAGS_OPERATORS(ResourceLoadFlag);
  37. /**
  38. * Manager for dealing with all engine resources. It allows you to save new resources and load existing ones.
  39. *
  40. * @note Sim thread only.
  41. */
  42. class BS_CORE_EXPORT Resources : public Module<Resources>
  43. {
  44. /** Information about a loaded resource. */
  45. struct LoadedResourceData
  46. {
  47. LoadedResourceData()
  48. :numInternalRefs(0)
  49. { }
  50. LoadedResourceData(const WeakResourceHandle<Resource>& resource)
  51. :resource(resource), numInternalRefs(0)
  52. { }
  53. WeakResourceHandle<Resource> resource;
  54. UINT32 numInternalRefs;
  55. };
  56. /** Information about a resource that's currently being loaded. */
  57. struct ResourceLoadData
  58. {
  59. ResourceLoadData(const WeakResourceHandle<Resource>& resource, UINT32 numDependencies)
  60. :resData(resource), remainingDependencies(numDependencies)
  61. { }
  62. LoadedResourceData resData;
  63. SPtr<Resource> loadedData;
  64. UINT32 remainingDependencies;
  65. Vector<HResource> dependencies;
  66. bool notifyImmediately;
  67. };
  68. public:
  69. Resources();
  70. ~Resources();
  71. /**
  72. * Loads the resource from a given path. Returns an empty handle if resource can't be loaded. Resource is loaded
  73. * synchronously.
  74. *
  75. * All loaded resources are reference counted and will be automatically unloaded when all of their references go out
  76. * of scope.
  77. *
  78. * @param[in] filePath File path to the resource to load. This can be absolute or relative to the working
  79. * folder.
  80. * @param[in] loadFlags Flags used to control the load process.
  81. *
  82. * @see release(ResourceHandleBase&), unloadAllUnused()
  83. */
  84. HResource load(const Path& filePath, ResourceLoadFlags loadFlags = ResourceLoadFlag::Default);
  85. /** @copydoc load(const Path&, ResourceLoadFlags) */
  86. template <class T>
  87. ResourceHandle<T> load(const Path& filePath, ResourceLoadFlags loadFlags = ResourceLoadFlag::Default)
  88. {
  89. return static_resource_cast<T>(load(filePath, loadFlags));
  90. }
  91. /**
  92. * Loads the resource for the provided weak resource handle, or returns a loaded resource if already loaded.
  93. *
  94. * @see load(const Path&, ResourceLoadFlags)
  95. */
  96. HResource load(const WeakResourceHandle<Resource>& handle, ResourceLoadFlags loadFlags = ResourceLoadFlag::Default);
  97. /** @copydoc load(const WeakResourceHandle<Resource>&, ResourceLoadFlags) */
  98. template <class T>
  99. ResourceHandle<T> load(const WeakResourceHandle<T>& handle, ResourceLoadFlags loadFlags = ResourceLoadFlag::Default)
  100. {
  101. return static_resource_cast<T>(load((const WeakResourceHandle<Resource>&)handle, loadFlags));
  102. }
  103. /**
  104. * Loads the resource asynchronously. Initially returned resource handle will be invalid until resource loading is
  105. * done.
  106. *
  107. * @param[in] filePath Full pathname of the file.
  108. * @param[in] loadFlags Flags used to control the load process.
  109. *
  110. * @note
  111. * You can use returned invalid handle in many engine systems as the engine will check for handle validity before
  112. * using it.
  113. *
  114. * @see load(const Path&, ResourceLoadFlags)
  115. */
  116. HResource loadAsync(const Path& filePath, ResourceLoadFlags loadFlags = ResourceLoadFlag::Default);
  117. /** @copydoc loadAsync */
  118. template <class T>
  119. ResourceHandle<T> loadAsync(const Path& filePath, ResourceLoadFlags loadFlags = ResourceLoadFlag::Default)
  120. {
  121. return static_resource_cast<T>(loadAsync(filePath, loadFlags));
  122. }
  123. /**
  124. * Loads the resource with the given UUID. Returns an empty handle if resource can't be loaded.
  125. *
  126. * @param[in] uuid UUID of the resource to load.
  127. * @param[in] async If true resource will be loaded asynchronously. Handle to non-loaded resource will be
  128. * returned immediately while loading will continue in the background.
  129. * @param[in] loadFlags Flags used to control the load process.
  130. *
  131. * @see load(const Path&, bool)
  132. */
  133. HResource loadFromUUID(const String& uuid, bool async = false, ResourceLoadFlags loadFlags = ResourceLoadFlag::Default);
  134. /**
  135. * Releases an internal reference to the resource held by the resources system. This allows the resource to be
  136. * unloaded when it goes out of scope, if the resource was loaded with @p keepInternalReference parameter.
  137. *
  138. * Alternatively you can also skip manually calling release() and call unloadAllUnused() which will unload all
  139. * resources that do not have any external references, but you lose the fine grained control of what will be
  140. * unloaded.
  141. *
  142. * @param[in] resource Handle of the resource to release.
  143. */
  144. void release(ResourceHandleBase& resource);
  145. /**
  146. * Finds all resources that aren't being referenced outside of the resources system and unloads them.
  147. *
  148. * @see release(ResourceHandleBase&)
  149. */
  150. void unloadAllUnused();
  151. /**
  152. * Saves the resource at the specified location.
  153. *
  154. * @param[in] resource Handle to the resource.
  155. * @param[in] filePath Full pathname of the file to save as.
  156. * @param[in] overwrite (optional) If true, any existing resource at the specified location will be overwritten.
  157. *
  158. * @note
  159. * If the resource is a GpuResource and you are in some way modifying it from the core thread, make sure all those
  160. * commands are submitted before you call this method. Otherwise an obsolete version of the resource might get saved.
  161. * @note
  162. * If saving a core thread resource this is a potentially very slow operation as we must wait on the core thread
  163. * and the GPU in order to read the resource.
  164. */
  165. void save(const HResource& resource, const Path& filePath, bool overwrite);
  166. /**
  167. * Saves an existing resource to its previous location.
  168. *
  169. * @param[in] resource Handle to the resource.
  170. *
  171. * @note
  172. * If the resource is a GpuResource and you are in some way modifying it from the Core thread, make sure all those
  173. * commands are submitted before you call this method. Otherwise an obsolete version of the resource might get saved.
  174. * @note
  175. * If saving a core thread resource this is a potentially very slow operation as we must wait on the core thread
  176. * and the GPU in order to read the resource.
  177. */
  178. void save(const HResource& resource);
  179. /**
  180. * Updates an existing resource handle with a new resource. Caller must ensure that new resource type matches the
  181. * original resource type.
  182. */
  183. void update(HResource& handle, const SPtr<Resource>& resource);
  184. /**
  185. * Returns a list of dependencies from the resources at the specified path. Resource will not be loaded or parsed,
  186. * but instead the saved list of dependencies will be read from the file and returned.
  187. *
  188. * @param[in] filePath Full path to the resource to get dependencies for.
  189. * @return List of dependencies represented as UUIDs.
  190. */
  191. Vector<String> getDependencies(const Path& filePath);
  192. /**
  193. * Checks is the resource with the specified UUID loaded.
  194. *
  195. * @param[in] uuid UUID of the resource to check.
  196. * @param[in] checkInProgress Should this method also check resources that are in progress of being
  197. * asynchronously loaded.
  198. * @return True if loaded or loading in progress, false otherwise.
  199. */
  200. bool isLoaded(const String& uuid, bool checkInProgress = true);
  201. /**
  202. *Allows you to set a resource manifest containing UUID <-> file path mapping that is used when resolving
  203. * resource references.
  204. *
  205. * @note
  206. * If you want objects that reference resources (using ResourceHandles) to be able to find that resource even after
  207. * application restart, then you must save the resource manifest before closing the application and restore it
  208. * upon startup. Otherwise resources will be assigned brand new UUIDs and references will be broken.
  209. */
  210. void registerResourceManifest(const SPtr<ResourceManifest>& manifest);
  211. /** Unregisters a resource manifest previously registered with registerResourceManifest(). */
  212. void unregisterResourceManifest(const SPtr<ResourceManifest>& manifest);
  213. /**
  214. * Allows you to retrieve resource manifest containing UUID <-> file path mapping that is used when resolving
  215. * resource references.
  216. *
  217. * @note
  218. * Resources module internally holds a "Default" manifest that it automatically updated whenever a resource is saved.
  219. *
  220. * @see registerResourceManifest
  221. */
  222. SPtr<ResourceManifest> getResourceManifest(const String& name) const;
  223. /** Attempts to retrieve file path from the provided UUID. Returns true if successful, false otherwise. */
  224. bool getFilePathFromUUID(const String& uuid, Path& filePath) const;
  225. /** Attempts to retrieve UUID from the provided file path. Returns true if successful, false otherwise. */
  226. bool getUUIDFromFilePath(const Path& path, String& uuid) const;
  227. /**
  228. * Called when the resource has been successfully loaded.
  229. *
  230. * @note
  231. * It is undefined from which thread this will get called from. Most definitely not the sim thread if resource was
  232. * being loaded asynchronously.
  233. */
  234. Event<void(const HResource&)> onResourceLoaded;
  235. /**
  236. * Called when the resource has been destroyed. Provides UUID of the destroyed resource.
  237. *
  238. * @note It is undefined from which thread this will get called from.
  239. */
  240. Event<void(const String&)> onResourceDestroyed;
  241. /**
  242. * Called when the internal resource the handle is pointing to has changed.
  243. *
  244. * @note It is undefined from which thread this will get called from.
  245. */
  246. Event<void(const HResource&)> onResourceModified;
  247. public: // ***** INTERNAL ******
  248. /** @name Internal
  249. * @{
  250. */
  251. /**
  252. * Creates a new resource handle from a resource pointer.
  253. *
  254. * @note Internal method used primarily be resource factory methods.
  255. */
  256. HResource _createResourceHandle(const SPtr<Resource>& obj);
  257. /**
  258. * Creates a new resource handle from a resource pointer, with a user defined UUID.
  259. *
  260. * @note Internal method used primarily be resource factory methods.
  261. */
  262. HResource _createResourceHandle(const SPtr<Resource>& obj, const String& UUID);
  263. /** Returns an existing handle for the specified UUID if one exists, or creates a new one. */
  264. HResource _getResourceHandle(const String& uuid);
  265. /** @} */
  266. private:
  267. friend class ResourceHandleBase;
  268. /**
  269. * Starts resource loading or returns an already loaded resource. Both UUID and filePath must match the same
  270. * resource, although you may provide an empty path in which case the resource will be retrieved from memory if its
  271. * currently loaded.
  272. */
  273. HResource loadInternal(const String& UUID, const Path& filePath, bool synchronous, ResourceLoadFlags loadFlags);
  274. /** Performs actually reading and deserializing of the resource file. Called from various worker threads. */
  275. SPtr<Resource> loadFromDiskAndDeserialize(const Path& filePath, bool loadWithSaveData);
  276. /** Triggered when individual resource has finished loading. */
  277. void loadComplete(HResource& resource);
  278. /** Callback triggered when the task manager is ready to process the loading task. */
  279. void loadCallback(const Path& filePath, HResource& resource, bool loadWithSaveData);
  280. /** Destroys a resource, freeing its memory. */
  281. void destroy(ResourceHandleBase& resource);
  282. private:
  283. Vector<SPtr<ResourceManifest>> mResourceManifests;
  284. SPtr<ResourceManifest> mDefaultResourceManifest;
  285. Mutex mInProgressResourcesMutex;
  286. Mutex mLoadedResourceMutex;
  287. UnorderedMap<String, WeakResourceHandle<Resource>> mHandles;
  288. UnorderedMap<String, LoadedResourceData> mLoadedResources;
  289. UnorderedMap<String, ResourceLoadData*> mInProgressResources; // Resources that are being asynchronously loaded
  290. UnorderedMap<String, Vector<ResourceLoadData*>> mDependantLoads; // Allows dependency to be notified when a dependant is loaded
  291. };
  292. /** Provides easier access to Resources manager. */
  293. BS_CORE_EXPORT Resources& gResources();
  294. /** @} */
  295. }