resource_loader.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /**************************************************************************/
  2. /* resource_loader.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #pragma once
  31. #include "core/io/resource.h"
  32. #include "core/object/gdvirtual.gen.inc"
  33. #include "core/object/worker_thread_pool.h"
  34. #include "core/os/thread.h"
  35. namespace CoreBind {
  36. class ResourceLoader;
  37. }
  38. class ConditionVariable;
  39. template <int Tag>
  40. class SafeBinaryMutex;
  41. class ResourceFormatLoader : public RefCounted {
  42. GDCLASS(ResourceFormatLoader, RefCounted);
  43. public:
  44. enum CacheMode {
  45. CACHE_MODE_IGNORE,
  46. CACHE_MODE_REUSE,
  47. CACHE_MODE_REPLACE,
  48. CACHE_MODE_IGNORE_DEEP,
  49. CACHE_MODE_REPLACE_DEEP,
  50. };
  51. protected:
  52. static void _bind_methods();
  53. GDVIRTUAL0RC(Vector<String>, _get_recognized_extensions)
  54. GDVIRTUAL2RC(bool, _recognize_path, String, StringName)
  55. GDVIRTUAL1RC(bool, _handles_type, StringName)
  56. GDVIRTUAL1RC(String, _get_resource_type, String)
  57. GDVIRTUAL1RC(String, _get_resource_script_class, String)
  58. GDVIRTUAL1RC(ResourceUID::ID, _get_resource_uid, String)
  59. GDVIRTUAL2RC(Vector<String>, _get_dependencies, String, bool)
  60. GDVIRTUAL1RC(Vector<String>, _get_classes_used, String)
  61. GDVIRTUAL2RC(Error, _rename_dependencies, String, Dictionary)
  62. GDVIRTUAL1RC(bool, _exists, String)
  63. GDVIRTUAL4RC(Variant, _load, String, String, bool, int)
  64. public:
  65. virtual Ref<Resource> load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE);
  66. virtual bool exists(const String &p_path) const;
  67. virtual void get_recognized_extensions(List<String> *p_extensions) const;
  68. virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const;
  69. virtual bool recognize_path(const String &p_path, const String &p_for_type = String()) const;
  70. virtual bool handles_type(const String &p_type) const;
  71. virtual void get_classes_used(const String &p_path, HashSet<StringName> *r_classes);
  72. virtual String get_resource_type(const String &p_path) const;
  73. virtual String get_resource_script_class(const String &p_path) const;
  74. virtual ResourceUID::ID get_resource_uid(const String &p_path) const;
  75. virtual bool has_custom_uid_support() const;
  76. virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
  77. virtual Error rename_dependencies(const String &p_path, const HashMap<String, String> &p_map);
  78. virtual bool is_import_valid(const String &p_path) const { return true; }
  79. virtual bool is_imported(const String &p_path) const { return false; }
  80. virtual int get_import_order(const String &p_path) const { return 0; }
  81. virtual String get_import_group_file(const String &p_path) const { return ""; } //no group
  82. virtual ~ResourceFormatLoader() {}
  83. };
  84. VARIANT_ENUM_CAST(ResourceFormatLoader::CacheMode)
  85. typedef void (*ResourceLoadErrorNotify)(const String &p_text);
  86. typedef void (*DependencyErrorNotify)(const String &p_loading, const String &p_which, const String &p_type);
  87. typedef Error (*ResourceLoaderImport)(const String &p_path);
  88. typedef void (*ResourceLoadedCallback)(Ref<Resource> p_resource, const String &p_path);
  89. class ResourceLoader {
  90. friend class LoadToken;
  91. friend class CoreBind::ResourceLoader;
  92. enum {
  93. MAX_LOADERS = 64
  94. };
  95. struct ThreadLoadTask;
  96. public:
  97. enum ThreadLoadStatus {
  98. THREAD_LOAD_INVALID_RESOURCE,
  99. THREAD_LOAD_IN_PROGRESS,
  100. THREAD_LOAD_FAILED,
  101. THREAD_LOAD_LOADED
  102. };
  103. enum LoadThreadMode {
  104. LOAD_THREAD_FROM_CURRENT,
  105. LOAD_THREAD_SPAWN_SINGLE,
  106. LOAD_THREAD_DISTRIBUTE,
  107. };
  108. struct LoadToken : public RefCounted {
  109. String local_path;
  110. String user_path;
  111. uint32_t user_rc = 0; // Having user RC implies regular RC incremented in one, until the user RC reaches zero.
  112. ThreadLoadTask *task_if_unregistered = nullptr;
  113. void clear();
  114. virtual ~LoadToken();
  115. };
  116. static const int BINARY_MUTEX_TAG = 1;
  117. static Ref<LoadToken> _load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode, bool p_for_user = false);
  118. static Ref<Resource> _load_complete(LoadToken &p_load_token, Error *r_error);
  119. private:
  120. static LoadToken *_load_threaded_request_reuse_user_token(const String &p_path);
  121. static void _load_threaded_request_setup_user_token(LoadToken *p_token, const String &p_path);
  122. static Ref<Resource> _load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock);
  123. static Ref<ResourceFormatLoader> loader[MAX_LOADERS];
  124. static int loader_count;
  125. static bool timestamp_on_load;
  126. static void *err_notify_ud;
  127. static ResourceLoadErrorNotify err_notify;
  128. static void *dep_err_notify_ud;
  129. static DependencyErrorNotify dep_err_notify;
  130. static bool abort_on_missing_resource;
  131. static bool create_missing_resources_if_class_unavailable;
  132. static HashMap<String, Vector<String>> translation_remaps;
  133. static String _path_remap(const String &p_path, bool *r_translation_remapped = nullptr);
  134. friend class Resource;
  135. static SelfList<Resource>::List remapped_list;
  136. friend class ResourceFormatImporter;
  137. static Ref<Resource> _load(const String &p_path, const String &p_original_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error, bool p_use_sub_threads, float *r_progress);
  138. static ResourceLoadedCallback _loaded_callback;
  139. static Ref<ResourceFormatLoader> _find_custom_resource_format_loader(const String &path);
  140. struct ThreadLoadTask {
  141. WorkerThreadPool::TaskID task_id = 0; // Used if run on a worker thread from the pool.
  142. Thread::ID thread_id = 0; // Used if running on an user thread (e.g., simple non-threaded load).
  143. bool awaited = false; // If it's in the pool, this helps not awaiting from more than one dependent thread.
  144. ConditionVariable *cond_var = nullptr; // In not in the worker pool or already awaiting, this is used as a secondary awaiting mechanism.
  145. uint32_t awaiters_count = 0;
  146. bool need_wait = true;
  147. LoadToken *load_token = nullptr;
  148. String local_path;
  149. String type_hint;
  150. float progress = 0.0f;
  151. float max_reported_progress = 0.0f;
  152. uint64_t last_progress_check_main_thread_frame = UINT64_MAX;
  153. ThreadLoadStatus status = THREAD_LOAD_IN_PROGRESS;
  154. ResourceFormatLoader::CacheMode cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE;
  155. Error error = OK;
  156. Ref<Resource> resource;
  157. bool use_sub_threads = false;
  158. HashSet<String> sub_tasks;
  159. struct ResourceChangedConnection {
  160. Resource *source = nullptr;
  161. Callable callable;
  162. uint32_t flags = 0;
  163. };
  164. LocalVector<ResourceChangedConnection> resource_changed_connections;
  165. };
  166. static void _run_load_task(void *p_userdata);
  167. static thread_local bool import_thread;
  168. static thread_local int load_nesting;
  169. static thread_local HashMap<int, HashMap<String, Ref<Resource>>> res_ref_overrides; // Outermost key is nesting level.
  170. static thread_local Vector<String> load_paths_stack;
  171. static thread_local ThreadLoadTask *curr_load_task;
  172. static SafeBinaryMutex<BINARY_MUTEX_TAG> thread_load_mutex;
  173. friend SafeBinaryMutex<BINARY_MUTEX_TAG> &_get_res_loader_mutex();
  174. static HashMap<String, ThreadLoadTask> thread_load_tasks;
  175. static bool cleaning_tasks;
  176. static HashMap<String, LoadToken *> user_load_tokens;
  177. static float _dependency_get_progress(const String &p_path);
  178. static bool _ensure_load_progress();
  179. static String _validate_local_path(const String &p_path);
  180. public:
  181. static Error load_threaded_request(const String &p_path, const String &p_type_hint = "", bool p_use_sub_threads = false, ResourceFormatLoader::CacheMode p_cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE);
  182. static ThreadLoadStatus load_threaded_get_status(const String &p_path, float *r_progress = nullptr);
  183. static Ref<Resource> load_threaded_get(const String &p_path, Error *r_error = nullptr);
  184. static bool is_within_load() { return load_nesting > 0; }
  185. static void resource_changed_connect(Resource *p_source, const Callable &p_callable, uint32_t p_flags);
  186. static void resource_changed_disconnect(Resource *p_source, const Callable &p_callable);
  187. static void resource_changed_emit(Resource *p_source);
  188. static Ref<Resource> load(const String &p_path, const String &p_type_hint = "", ResourceFormatLoader::CacheMode p_cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE, Error *r_error = nullptr);
  189. static bool exists(const String &p_path, const String &p_type_hint = "");
  190. static void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions);
  191. static void add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front = false);
  192. static void remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader);
  193. static void get_classes_used(const String &p_path, HashSet<StringName> *r_classes);
  194. static String get_resource_type(const String &p_path);
  195. static String get_resource_script_class(const String &p_path);
  196. static ResourceUID::ID get_resource_uid(const String &p_path);
  197. static bool has_custom_uid_support(const String &p_path);
  198. static bool should_create_uid_file(const String &p_path);
  199. static void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
  200. static Error rename_dependencies(const String &p_path, const HashMap<String, String> &p_map);
  201. static bool is_import_valid(const String &p_path);
  202. static String get_import_group_file(const String &p_path);
  203. static bool is_imported(const String &p_path);
  204. static int get_import_order(const String &p_path);
  205. static void set_is_import_thread(bool p_import_thread);
  206. static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load = p_timestamp; }
  207. static bool get_timestamp_on_load() { return timestamp_on_load; }
  208. // Loaders can safely use this regardless which thread they are running on.
  209. static void notify_load_error(const String &p_err) {
  210. if (err_notify) {
  211. MessageQueue::get_main_singleton()->push_callable(callable_mp_static(err_notify).bind(p_err));
  212. }
  213. }
  214. static void set_error_notify_func(ResourceLoadErrorNotify p_err_notify) {
  215. err_notify = p_err_notify;
  216. }
  217. // Loaders can safely use this regardless which thread they are running on.
  218. static void notify_dependency_error(const String &p_path, const String &p_dependency, const String &p_type) {
  219. if (dep_err_notify) {
  220. if (Thread::get_caller_id() == Thread::get_main_id()) {
  221. dep_err_notify(p_path, p_dependency, p_type);
  222. } else {
  223. MessageQueue::get_main_singleton()->push_callable(callable_mp_static(dep_err_notify).bind(p_path, p_dependency, p_type));
  224. }
  225. }
  226. }
  227. static void set_dependency_error_notify_func(DependencyErrorNotify p_err_notify) {
  228. dep_err_notify = p_err_notify;
  229. }
  230. static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource = p_abort; }
  231. static bool get_abort_on_missing_resources() { return abort_on_missing_resource; }
  232. static String path_remap(const String &p_path);
  233. static String import_remap(const String &p_path);
  234. static void reload_translation_remaps();
  235. static void load_translation_remaps();
  236. static void clear_translation_remaps();
  237. static void clear_thread_load_tasks();
  238. static void set_load_callback(ResourceLoadedCallback p_callback);
  239. static ResourceLoaderImport import;
  240. static bool add_custom_resource_format_loader(const String &script_path);
  241. static void add_custom_loaders();
  242. static void remove_custom_loaders();
  243. static void set_create_missing_resources_if_class_unavailable(bool p_enable);
  244. _FORCE_INLINE_ static bool is_creating_missing_resources_if_class_unavailable_enabled() { return create_missing_resources_if_class_unavailable; }
  245. static Ref<Resource> ensure_resource_ref_override_for_outer_load(const String &p_path, const String &p_res_type);
  246. static Ref<Resource> get_resource_ref_override(const String &p_path);
  247. static bool is_cleaning_tasks();
  248. static Vector<String> list_directory(const String &p_directory);
  249. static void initialize();
  250. static void finalize();
  251. };